Follow TaijiOS commit 9b2d053 (dis/ -> zx/) in src/interpreter.zi and tests/tcl_headless_api.zi.
Tcl for Ziran
A headless Tcl interpreter written in Ziran, based on the Inferno Limbo Tcl interpreter. It runs as a library in native programs and compiled ZX modules. The interpreter needs only Ziran's standard library; the host supplies file, channel, and clock services through callbacks.
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.