Add the dependency
In your project’s ziran.toml; pin ref to a commit for reproducible builds.
[dependencies.tcl]
git = "https://git.waozi.xyz/ziranlang/tcl.git"
ref = "master"Overview
Use it in a Ziran project
ziran add https://git.waozi.xyz/ziranlang/tcl.git
#import "std/vec"
using Tcl :: #import "tcl/interpreter"
main :: () -> s32 {
interpreter: Tcl.Interpreter;
result := Tcl.Eval(*interpreter, "set width 6; expr {$width * 7}");
print("%\n", TextView(result.value));
return ifx result.code == .OK then 0 else 1;
}
A zero-initialized Interpreter is ready to use. Eval retains variables and
procedure definitions. TakeOutput takes and clears the text accumulated by
puts, including output written before an error. Results own their text.
Each top-level evaluation has a 10,000-command budget that also charges loop
iterations and permits up to 48 nested script levels.
Host extension points:
RegisterCommandadds a single host command,RegisterPrefixhandles commands whose names are allocated at runtime, andRegisterLibraryprovides command bundles activated by Tcl'sload.tcl/typesholds text values and result types,tcl/packagesadds versioned script packages,tcl/ioadds channel backends. All exports are listed inziran.toml.
Supported Tcl
- Syntax: command separators, comments, nested braces, quoted and empty words,
basic backslash escapes and line continuations,
$name,${name}, and$array(key)substitution (including inside parentheses), and nested[script]substitution. - Core commands:
set,unset,incr,append,lappend,proc,return,if,while,for,foreach,break,continue,catch,error,eval. Procedures accept defaults and a trailingargs;foreachtakes a variable list and one value list;catchtakes an optional result variable. - Frames and scope:
array names,array size,global,upvarfor one linked variable,uplevel,level,switchwith exact patterns,-fallthrough and a finaldefault,info args,body,commands,exists,procs. Frame selection accepts absolute levels (#0) and relative levels (-1,1for the caller).info commandsandinfo procsaccept the optional Limbo pattern argument without filtering. Prefix extensions supply command names dynamically and cannot be enumerated. - Lists:
list,llength,lindex,lrange,join,concat,linsert,lreplace, exactlsearch,lsortwith optional-decreasing,split. One-argumentsplitpreserves the string, following Limbo. - Strings:
string compare,equal,length,index,range,first,last,tolower,toupper,trim,trimleft,trimright. Lengths and indexes count UTF-8 characters; case conversion and trim use ASCII rules. Indexes accept decimal integers,end, andend-N. A numeric last index instring rangeis exclusive, following Limbo;endandend-Nare inclusive. format:%%,%s,%d,%x,%fwith width, left alignment, zero padding, and precision; literal text between fields is preserved. Following Limbo,%fdefaults to one decimal place and%Nfsets precision;%W.Nfsets both. Fixed formatting rounds binary64 values to nearest with ties to even; precision and width are limited to 4096. Invalid real arguments return Tcl errors; nonfinite reals format asInf,-Inf,NaN.exprandcalcaccept signed 32-bit decimal, leading-zero octal, and0xhexadecimal integers, decimal and scientific real literals, and the boolean wordstrue/false,yes/no,on/off. Operators: parentheses, unary+ - ! ~, binary+ - * / %, comparisons== != < <= > >=, and<< >> & ^ | && || ?:. Remainder, bitwise, and logical operators take integers; logical and conditional operands evaluate eagerly. A substitution inside braces must yield one numeric or boolean literal. Integer overflow and division by zero return errors; real arithmetic can returnNaNorInfinity.- Real functions:
abs,acos,asin,atan,atan2,ceil,cos,cosh,exp,floor,fmod,hypot,log,log10,pow,sin,sinh,sqrt,tan,tanh. time script ?count?runs the script repeatedly in the calling frame and reports milliseconds per iteration; it shares the script command limit. Script errors are reported after the requested repetitions, and control flow such asreturnorexitpropagates immediately. Supply a monotonic clock withSetClock; the callback receives a context ID and returns milliseconds or a negative value on failure.dumpstackwrites the scalar, array, and alias tables of the frames visible from the current frame to the output buffer, in variable insertion order, with no Limbo hash slot numbers.load libnameactivates a bundle registered withRegisterLibrary(a slice ofLibraryCommanddescriptors plus one context ID). Loaded commands are visible toinfo commandsand callable; loads are idempotent, and a command conflict rejects the whole bundle.calc,io,list, andstringare available by default.puts stringandputs -nonewline stringwrite to the output buffer.exitstops the current evaluation, including from a procedure, source file, orcatchbody;Evalreturns.Exitto the embedding application. As in Limbo,exitignores its arguments.source ?-encoding utf-8? fileNameevaluates the loaded script in the current frame and shares the command and nesting budgets. Library callers supply the reader withSetSourceLoader; the callback receives its context ID, the path, and a pointer to aResult, sets the result's owned value to the script on success, or returns an error withcode = .Error.
Unsupported: namespaces, {*} word expansion, numeric and Unicode backslash
escapes, wide expression integers, expression string operands, and lazy
expression operators. Several commands follow Inferno Tcl semantics as noted
above. Compare a library's requirements against this command set before use.
Tcl script packages
Import tcl/packages and call Packages.Attach(*interpreter) to enable the
package command; each interpreter has its own registry. Available
subcommands: provide, require, present, ifneeded, names, versions,
forget, vcompare, vsatisfies, prefer, unknown. require executes the
chosen initialization script in the global frame with the caller's command
budget and detects circular loads. Version checks include -exact, multiple
requirements, ranges, and alpha and beta versions.
List directories that contain pkgIndex.tcl files in auto_path; Tcl reads
them through the registered SetSourceLoader callback. An index sees its own
directory in the local variable dir:
# /path/to/sample/pkgIndex.tcl
package ifneeded sample 1.0 [list source [file join $dir sample.tcl]]
lappend auto_path /path/to/sample
package require sample 1.0
Discovery checks the auto_path directories directly and runs scripts with
the interpreter's supported commands. Tcl's standard library and Tcllib are
separate dependencies; C extension loading and .tm discovery are
unsupported. package unknown can supply a custom discovery command, and
registrations also work entirely in memory. After initializing a Ziran
extension, an embedder can call Packages.Provide(*interpreter, name, version)
and check the returned Result; an ifneeded script can also call
load name for a bundle supplied by RegisterLibrary.
Channels and files
opensupports LimboOREAD(the default),OWRITE, andORDWRon existing files;randr+are aliases.wandw+create or truncate a file, with optional octal or decimal permissions (default0666).OWRITEpreserves unwritten bytes. Append modes are unsupported.close,eof,flush,gets,read,seek,tell, and channelputs ?-nonewline? fileId stringare available.seekacceptsSEEKSTART,SEEKRELA, andSEEKEND, as well asstart,current, andend. Offsets and file sizes are signed 64-bit integers; failed seeks return Tcl errors.- Counted
readreturns up to the requested number of bytes. The Limbo line forms read one line; barereadappends a newline andread -nonewlinereturns the original line.getsstrips the last character and accepts the legacy optional variable name without setting it. EOF becomes sticky after an empty read. Reads and lines are bounded to 1 MiB per command. file join name ?name ...?joins POSIX paths without a file backend.file exists,file size,file isfile, andfile isdirectoryuse the configured backend. Writes take effect immediately, soflushvalidates the channel and returns success without sending another write.
Install a channel backend with SetChannelBackend and tcl/io.Backend;
callbacks receive the backend's context ID. File channels persist between
Eval calls, and CloseChannels releases them, including after .Exit.
Explicit stdout and implicit puts share TakeOutput.
Local tests
Run from the package root with ziran, zi2zx, and Python 3 on PATH:
python3 tests/run.py
Set ZIRAN and ZI2ZX to use specific toolchain binaries. For a checkout of
Ziran at ../../ziran, use an ignored ziran.local.toml with this override:
[overrides]
ziran = "../../ziran"
The suite runs the same fixtures as a native executable and a portable .zx
image. It checks parsing, control flow, error handling, numeric expressions,
fixed-point formatting, registered commands, script package discovery, and
injected I/O. The package discovery and channel fixtures use in-memory host
callbacks.
Relocatable Tcl libraries
The default profile includes every manifest export and uses no feature
defines. It ships as default.zx, with a default.json receipt recording the
source commit, package and toolchain identities, dependency lock, exports, and
SHA-256. Consumers import tcl/interpreter as usual, and Ziran uses the
relocatable library when bundling the application, so the consumer can build
without a Tcl source checkout.
For a production build, use a clean Tcl checkout without overrides and a
cached build of the exact compiler revision recorded in ziran.lock. The
compiler must support .zx objects with ziran pkg zx pack-ir and inspection
with ziran pkg zx inspect-ir. The Gitea workflow builds the locked compiler
before running these targets.
make check artifact artifact-smoke
The library and receipt land in build/artifacts/. The smoke runs ziran add
against a local fixture registry and a fresh cache, then runs ziran lock,
builds the consumer offline, and compares the output of
tests/fixtures/core.tcl byte for byte. Development targets use the usual
ignored ziran.local.toml overrides: pack-dev emits a local .zx library
with a source fingerprint and receipt in build/artifacts-dev/, and a
source-free consumer can load it from ZIRAN_DEV_ZX_DIR as <package-id>.zx.
make artifact-dev artifact-smoke ARTIFACT_FLAGS=--development
Once the library is published, ziran add and ziran lock discover its
default profile and record the digest in the consumer's ziran.lock. Run
ziran bundle --project --locked to build the application, adding --offline
once the library is cached. The consumer can also specify the same package ID,
profile, and digest explicitly in ziran.zx.lock. Native source development
continues to use the standard package imports and overrides.
The Gitea master workflow publishes the verified default.zx and its
default.zx.tsv descriptor through ziran pkg zx publish-ir to the
tcl-zx-library Generic package, using the TCL_PACKAGE_USER and
TCL_PACKAGE_TOKEN secrets for an account with package-write access. After
publication the workflow repeats discovery and the offline test from a fresh
cache against Gitea. Repeat that check with
make artifact-smoke ARTIFACT_FLAGS=--registry.
License
MIT. See LICENSE and NOTICE for the original Inferno and TaijiOS attribution.
tcl/src/interpreter.zi
interpreter
Ported from Inferno's Tcl_Core, TclLib and Tcl_Stack. See ../NOTICE (MIT).
Import with #import "tcl/interpreter".
Parameter :: struct { name: Text; fallback: Text; optional: bool; }Procedure :: struct { name: Text; parameters: Vec(Parameter); body: Text; variadic: bool; }Command words exclude the command name. A handler fills an owned result.
CommandHandler :: #type (context: s64, args: []Text, result: *Result)Command words exclude the command name. A handler fills an owned result. The client can use the context ID as a lookup key for its own widget state.
Extension :: struct { name: Text; context: s64; handler: CommandHandler; }LibraryCommand :: struct { name: string; handler: CommandHandler; }Library :: struct { name: Text; commands: Vec(Extension); loaded: bool; }MonotonicClock :: #type (context: s64) -> s64A prefix can supply dynamically named commands. A nonempty script is
PrefixHandler :: #type (context: s64, name: string, args: []Text, result: *Result, script: *Text)A prefix can supply dynamically named commands. A nonempty script is evaluated in the current frame and its result becomes the command result.
CommandPrefix :: struct { name: Text; context: s64; handler: PrefixHandler; }SourceLoader :: #type (context: s64, path: string, result: *Result)PackageScript :: struct { version: Text; script: Text; }Package :: struct { name: Text; provided: Text; scripts: Vec(PackageScript); }PackageTable :: struct { entries: Vec(Package); loading: Vec(Text); unknown: Text; custom_unknown: bool; discovering: bool; prefer_latest: bool; }PackageRunner :: #type (interpreter: *Interpreter, args: []Text, depth: s32, result: *Result)Interpreter :: struct { globals: Frame; procedures: Vec(Procedure); extensions: Vec(Extension); libraries: Vec(Library); prefixes: Vec(CommandPrefix); source_loader: SourceLoader; source_context: s64; clock: MonotonicClock; clock_context: s64; output: Text; channels: Io.ChannelTable; steps: s64; packages: PackageTable; package_runner: PackageRunner; }Eval :: (interpreter: *Interpreter, script: string) -> ResultA zero-initialized Interpreter is ready to use. Eval keeps globals and procedures between calls. Break/continue outside a loop are script errors.
TakeOutput :: (interpreter: *Interpreter) -> TextSetSourceLoader :: (interpreter: *Interpreter, loader: SourceLoader, context: s64)SetClock :: (interpreter: *Interpreter, clock: MonotonicClock, context: s64)The callback returns monotonic milliseconds, or a negative value on failure.
SetChannelBackend :: (interpreter: *Interpreter, backend: Io.Backend) -> ResultReconfiguration closes any channels previously opened by the interpreter.
CloseChannels :: (interpreter: *Interpreter) -> ResultRegisterCommand :: (interpreter: *Interpreter, name: string, handler: CommandHandler, context: s64) -> boolFindLibrary :: (interpreter: *Interpreter, name: string) -> *LibraryFindExtension :: (interpreter: *Interpreter, name: string) -> *ExtensionBUILTIN_LIBRARIES :: "calc io list string"A named bundle supplies commands when the script loads it. Copy each name so
RegisterLibrary :: (interpreter: *Interpreter, name: string, commands: []LibraryCommand, context: s64) -> boolA named bundle supplies commands when the script loads it. Copy each name so callers can pass short-lived descriptors. Activation is local to an interpreter.
RegisterPrefix :: (interpreter: *Interpreter, prefix: string, handler: PrefixHandler, context: s64) -> boolOutsideLoop :: (result: Result) -> ResultCopyResult :: (result: *Result) -> ResultCORE_COMMANDS :: "append array break calc catch continue dumpstack error eval exit expr for foreach format global if incr info lappend level load proc return set source string switch time unset uplevel upvar while"IsBuiltin :: (name: string) -> boolVariableSubstitution :: (interpreter: *Interpreter, frame: *Frame, cursor: *Cursor, depth: s32) -> ResultAtEnd :: (cursor: *Cursor, nested: bool) -> boolSkipWordSpace :: (cursor: *Cursor)ReadWord :: (interpreter: *Interpreter, frame: *Frame, cursor: *Cursor, depth: s32, nested: bool) -> ResultSubstitute :: (interpreter: *Interpreter, frame: *Frame, cursor: *Cursor, depth: s32, out: *Vec(u8)) -> ResultSubstitutionValue :: (interpreter: *Interpreter, frame: *Frame, cursor: *Cursor, depth: s32) -> ResultEvalScript :: (interpreter: *Interpreter, frame: *Frame, script: string, depth: s32) -> ResultEvalCursor :: (interpreter: *Interpreter, frame: *Frame, cursor: *Cursor, depth: s32, nested: bool) -> ResultExpressionValue :: (interpreter: *Interpreter, frame: *Frame, text: string, depth: s32) -> ResultFindProcedure :: (interpreter: *Interpreter, name: string) -> s64DefineProcedure :: (interpreter: *Interpreter, args: []Text) -> ResultCallProcedure :: (interpreter: *Interpreter, caller: *Frame, index: s64, args: []Text, depth: s32) -> ResultRunIf :: (interpreter: *Interpreter, frame: *Frame, args: []Text, depth: s32) -> ResultRunLoop :: (interpreter: *Interpreter, frame: *Frame, test_source: string, body: string, next: string, depth: s32) -> ResultRunFor :: (interpreter: *Interpreter, frame: *Frame, args: []Text, depth: s32) -> ResultRunForeach :: (interpreter: *Interpreter, frame: *Frame, args: []Text, depth: s32) -> ResultIncrement :: (frame: *Frame, args: []Text) -> ResultAppendVariable :: (frame: *Frame, args: []Text, as_list: bool) -> ResultJoinWords :: (args: []Text) -> TextSelectSwitch :: (interpreter: *Interpreter, frame: *Frame, value: string, pairs: []Text, depth: s32) -> ResultRunSwitch :: (interpreter: *Interpreter, frame: *Frame, args: []Text, depth: s32) -> ResultRunInfo :: (interpreter: *Interpreter, frame: *Frame, args: []Text) -> ResultFrameLevel :: (frame: *Frame, word: string) -> (*Frame, bool)RunFrameCommand :: (interpreter: *Interpreter, frame: *Frame, name: string, args: []Text, depth: s32) -> ResultRunSource :: (interpreter: *Interpreter, frame: *Frame, args: []Text, depth: s32) -> ResultRunLoad :: (interpreter: *Interpreter, args: []Text) -> ResultRunTime :: (interpreter: *Interpreter, frame: *Frame, args: []Text, depth: s32) -> ResultDispatch :: (interpreter: *Interpreter, frame: *Frame, words: []Text, depth: s32) -> Resulttcl/src/calc.zi
calc
Numeric expression parser adapted from Inferno tcl_calc.b. See ../NOTICE (MIT).
Import with #import "tcl/calc".
Value :: struct { integer: s64; real: float64; floating: bool; }Parser :: struct { cursor: Cursor; problem: string; }Int :: (value: s64) -> ValueReal :: (value: float64) -> ValueBoolean :: (value: bool) -> ValueToReal :: (value: Value) -> float64Truth :: (value: Value) -> boolSkipSpaces :: (cursor: *Cursor)Fail :: (parser: *Parser, message: string) -> ValueChecked :: (parser: *Parser, value: s64) -> ValueRadixDigit :: (byte: u8) -> s64IntegerLiteral :: (parser: *Parser, word: string, base: s64, negative: bool) -> ValueNumber :: (parser: *Parser, negative: bool) -> ValueNamedValue :: (word: string) -> (Value, bool)Function :: (parser: *Parser, name: string, arity: s32, depth: s32) -> ValueOperand :: (parser: *Parser, depth: s32) -> ValueOperator :: (cursor: *Cursor) -> (string, s32)ApplyReal :: (parser: *Parser, op: string, a: float64, b: float64) -> ValueApplyInteger :: (parser: *Parser, op: string, a: s64, b: s64) -> ValueApply :: (parser: *Parser, op: string, left: Value, right: Value) -> ValueBinary :: (parser: *Parser, minimum: s32, depth: s32) -> ValueConditional :: (parser: *Parser, depth: s32) -> ValueEvaluate :: (text: string) -> (Value, string)ScalarOperand :: (text: string) -> boolSubstitution accepts one literal, preventing text values from becoming operators.
Format :: (value: Value) -> Resulttcl/src/decimal.zi
decimal
Fixed-point conversion for the Inferno Tcl format command. See ../NOTICE (MIT).
Import with #import "tcl/decimal".
DecimalDigits :: (value: float64, digits: []u8) -> (s64, s64)The exact finite value is significand * 2^exponent. When the exponent is negative, represent it instead as significand * 5^-exponent / 10^-exponent. Base 10^9 limbs keep the longest binary64 expansion small.
Round :: (digits: []u8, count: s64, discard: s64) -> s64Drop decimal places using round-to-nearest, ties-to-even. Digits are least significant first. Caller storage is zero-filled past count.
Fixed :: (input: string, precision: s64) -> (Text, bool, bool)Return the sign separately so format can place zero padding after it.
tcl/src/io.zi
io
Tcl channel behavior adapted from Inferno tcl_io.b. See ../NOTICE (MIT).
Import with #import "tcl/io".
OpenCallback :: #type (context: s64, path: string, mode: s32) -> s32CreateCallback :: #type (context: s64, path: string, mode: s32, permissions: s32) -> s32ReadCallback :: #type (context: s64, handle: s32, buffer: []u8) -> s32WriteCallback :: #type (context: s64, handle: s32, data: string) -> s32CloseCallback :: #type (context: s64, handle: s32) -> s32SeekCallback :: #type (context: s64, handle: s32, offset: s64, origin: s32) -> s64StatCallback :: #type (context: s64, path: string, metadata: []u8) -> s32ErrorCallback :: #type (context: s64) -> stringBackend :: struct { context: s64; open: OpenCallback; create: CreateCallback; read: ReadCallback; write: WriteCallback; close: CloseCallback; seek: SeekCallback; stat: StatCallback; error: ErrorCallback; stdin: bool; }Channel :: struct { active: bool; handle: s32; mode: s32; eof: bool; pending: Vec(u8); next: s64; end: s64; }ChannelTable :: struct { backend: Backend; files: Vec(Channel); input: Channel; stdout_closed: bool; }COMMANDS :: "close eof file flush gets open puts read seek tell"CHUNK :: 4096MAX_READ :: 1048576BackendError :: (table: *ChannelTable, operation: string) -> ResultChannelError :: (name: string) -> ResultFindChannel :: (table: *ChannelTable, name: string) -> *ChannelOpenMode :: (name: string) -> (s32, bool)Permissions :: (text: string) -> s32OpenChannel :: (table: *ChannelTable, args: []Text) -> ResultCloseChannel :: (table: *ChannelTable, channel: *Channel) -> boolCloseAll :: (table: *ChannelTable) -> ResultAppendPending :: (channel: *Channel, output: *Text, limit: s64, line: bool) -> (bool, bool)ReadChannel :: (table: *ChannelTable, channel: *Channel, count: s64, line: bool) -> ResultWriteChannel :: (table: *ChannelTable, channel: *Channel, text: string, newline: bool) -> ResultRunPuts :: (table: *ChannelTable, output: *Text, args: []Text) -> ResultRunRead :: (table: *ChannelTable, command: string, args: []Text) -> ResultOrigin :: (name: string) -> s32RunSeek :: (table: *ChannelTable, channel: *Channel, args: []Text) -> ResultParseFileOffset :: (text: string) -> (s64, bool)AppendPath :: (path: *Text, part: string) -> boolRunFile :: (table: *ChannelTable, args: []Text) -> ResultRun :: (table: *ChannelTable, output: *Text, name: string, args: []Text) -> Resulttcl/src/lists.zi
lists
Ported from the Inferno Limbo tcl_list.b and tcl_utils.b. See ../NOTICE (MIT).
Import with #import "tcl/lists".
List :: struct { words: Vec(Text); problem: string; }ParseList :: (source: string) -> ListAppendElement :: (output: *Vec(u8), value: string, separate: bool)Favor brace quoting for ordinary grouped items. Unbalanced braces and a trailing backslash require backslash quoting instead for a round trip.
Index :: (word: string, length: s64) -> (s64, bool)LIST_COMMANDS :: "concat join lindex linsert list llength lrange lreplace lsearch lsort split"IsListCommand :: (name: string) -> boolAppendWords :: (output: *Text, words: []Text)Split :: (args: []Text) -> ResultSort :: (args: []Text) -> ResultRunList :: (name: string, args: []Text) -> Resulttcl/src/math.zi
math
Real-valued function vocabulary from Inferno tcl_calc.b. See ../NOTICE (MIT).
Import with #import "tcl/math".
Arity :: (name: string) -> s32Absolute :: (value: float64) -> float64Finite :: (value: float64) -> boolRoundDirected :: (value: float64, upward: bool) -> float64Hypot :: (first: float64, second: float64) -> float64Remainder :: (first: float64, second: float64) -> float64Call :: (name: string, first: float64, second: float64) -> float64tcl/src/packages.zi
packages
Versioned Tcl script libraries for the headless Inferno Tcl port. See ../NOTICE (MIT).
Import with #import "tcl/packages".
Attach :: (interpreter: *Tcl.Interpreter)Find :: (table: *Tcl.PackageTable, name: string) -> s64Ensure :: (table: *Tcl.PackageTable, name: string) -> s64Forget :: (table: *Tcl.PackageTable, name: string)ValidVersion :: (version: string) -> boolAlpha and beta markers occupy their own version component and sort below 0. Comparing decimal component text avoids truncating large version components.
NextComponent :: (version: string, at: *s64) -> stringCompareComponent :: (left: string, right: string) -> s64Compare :: (left: string, right: string) -> s64Prerelease :: (version: string) -> boolCompareBound :: (version: string, bound: string) -> s64Range endpoints use an implicit a0 on a stable version, so for example 1.2b1 is included at the lower bound 1.2 and excluded at the upper bound 1.2.
SplitRequirement :: (word: string) -> (string, string, bool)BadVersion :: (version: string) -> ResultValidate :: (requirements: []Text, exact: bool) -> ResultMatches :: (version: string, requirements: []Text, exact: bool) -> boolProvided :: (table: *Tcl.PackageTable, name: string) -> ResultConflict :: (name: string, have: string, requirements: []Text, wanted: string) -> ResultProvide :: (interpreter: *Tcl.Interpreter, name: string, version: string) -> ResultAn embedder calls Provide after it has attached its own implementation.
IfNeeded :: (table: *Tcl.PackageTable, name: string, version: string, args: []Text) -> ResultChoose :: (table: *Tcl.PackageTable, name: string, requirements: []Text, exact: bool) -> (s64, s64)ScanIndexes :: (interpreter: *Tcl.Interpreter, depth: s32) -> ResultDiscover :: (interpreter: *Tcl.Interpreter, name: string, requirements: []Text, exact: bool, depth: s32) -> ResultRequire :: (interpreter: *Tcl.Interpreter, name: string, requirements: []Text, exact: bool, present: bool, depth: s32) -> ResultRun :: (interpreter: *Tcl.Interpreter, args: []Text, depth: s32) -> ResultDispatch :: (interpreter: *Tcl.Interpreter, args: []Text, depth: s32, result: *Result)tcl/src/strings.zi
strings
Ported string operations from Inferno tcl_string.b. See ../NOTICE (MIT).
Import with #import "tcl/strings".
RunString :: (args: []Text) -> ResultFormatNumber :: (cursor: *Cursor) -> s64AppendField :: (output: *Text, value: string, width: s64, zeros: s64, negative: bool, left: bool, numeric: bool)RunFormat :: (args: []Text) -> Resulttcl/src/types.zi
types
Ported from the Inferno Limbo Tcl interpreter. See ../NOTICE (MIT).
Import with #import "tcl/types".
Code :: enum { OK = 0; Error = 1; Return = 2; Break = 3; Continue = 4; Exit = 5; }Result :: struct { code: Code; value: Text; }Success :: (value: string) -> ResultFailure :: (message: string) -> ResultWrongArgs :: (usage: string) -> ResultQuotedError :: (prefix: string, word: string, suffix: string) -> ResultInteger :: (value: s64) -> ResultSpace :: (byte: u8) -> boolInlineSpace :: (byte: u8) -> boolDigit :: (byte: u8) -> boolNameByte :: (byte: u8) -> boolNextCharacter :: (text: string, at: s64) -> s64CharacterOffset :: (text: string, count: s64) -> s64CharacterCount :: (text: string) -> s64CompareText :: (left: string, right: string) -> s64INT_MIN :: -2147483648The legacy interpreter's int is signed 32-bit. Wider intermediates let us detect overflow before returning an expression result.
INT_MAX :: 2147483647InRange :: (value: s64) -> boolParseInteger :: (text: string) -> (s64, bool)Cursor :: struct { text: string; at: s64; }Has :: (cursor: *Cursor) -> boolPeek :: (cursor: *Cursor) -> u8Take :: (cursor: *Cursor) -> u8WordIn :: (words: string, target: string) -> boolContinuesLine :: (cursor: *Cursor) -> boolSkipContinuation :: (cursor: *Cursor)Unescape :: (cursor: *Cursor) -> u8Braced :: (cursor: *Cursor) -> Resulttcl/src/variables.zi
variables
Tcl variables and stack links adapted from Inferno tcl_core.b and tcl_stack.b. See ../NOTICE.
Import with #import "tcl/variables".
Variable :: struct { name: Text; value: Text; }VariableTable :: struct { entries: Vec(Variable); }ArrayVariable :: struct { name: Text; elements: VariableTable; }Alias :: struct { name: Text; target: Text; frame: *Frame; }Frame :: struct { variables: VariableTable; arrays: Vec(ArrayVariable); aliases: Vec(Alias); parent: *Frame; level: s64; }VariableRef :: struct { frame: *Frame; base: Text; key: Text; element: bool; valid: bool; }Parts :: (frame: *Frame, name: string) -> VariableRefScalarName :: (name: string) -> boolFindAlias :: (frame: *Frame, name: string) -> s64ResolveVariable :: (frame: *Frame, name: string) -> VariableRefFindVariable :: (variables: *VariableTable, name: string) -> s64FindArray :: (frame: *Frame, name: string) -> s64VariableExists :: (frame: *Frame, name: string) -> boolReadVariable :: (frame: *Frame, name: string) -> ResultStoreValue :: (values: *VariableTable, name: string, value: string) -> boolStoreVariable :: (frame: *Frame, name: string, value: string) -> ResultRemoveValue :: (values: *VariableTable, name: string) -> boolRemoveVariable :: (frame: *Frame, name: string) -> ResultRunArray :: (frame: *Frame, args: []Text) -> ResultLinkVariable :: (frame: *Frame, name: string, target: *Frame, target_name: string) -> ResultAppendDumpHeader :: (out: *Text, label: string, level: s64) -> boolAppendDumpValues :: (out: *Text, table: *VariableTable, indent: string) -> boolAppendStackDump :: (out: *Text, frame: *Frame) -> bool