waozi 18aed671f6
Relocatable Tcl library / package (push) Successful in 6m23s
Update TaijiOS Tcl load error path from /dis/ to /zx/
Follow TaijiOS commit 9b2d053 (dis/ -> zx/) in src/interpreter.zi and tests/tcl_headless_api.zi.
2026-11-24 21:50:13 -03:00
2026-11-20 13:43:51 -03:00
2026-11-21 02:19:31 -03:00
2026-11-20 13:43:51 -03:00

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:

  • RegisterCommand adds a single host command, RegisterPrefix handles commands whose names are allocated at runtime, and RegisterLibrary provides command bundles activated by Tcl's load.
  • tcl/types holds text values and result types, tcl/packages adds versioned script packages, tcl/io adds channel backends. All exports are listed in ziran.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 trailing args; foreach takes a variable list and one value list; catch takes an optional result variable.
  • Frames and scope: array names, array size, global, upvar for one linked variable, uplevel, level, switch with exact patterns, - fallthrough and a final default, info args, body, commands, exists, procs. Frame selection accepts absolute levels (#0) and relative levels (-1, 1 for the caller). info commands and info procs accept 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, exact lsearch, lsort with optional -decreasing, split. One-argument split preserves 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, and end-N. A numeric last index in string range is exclusive, following Limbo; end and end-N are inclusive.
  • format: %%, %s, %d, %x, %f with width, left alignment, zero padding, and precision; literal text between fields is preserved. Following Limbo, %f defaults to one decimal place and %Nf sets precision; %W.Nf sets 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 as Inf, -Inf, NaN.
  • expr and calc accept signed 32-bit decimal, leading-zero octal, and 0x hexadecimal integers, decimal and scientific real literals, and the boolean words true/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 return NaN or Infinity.
  • 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 as return or exit propagates immediately. Supply a monotonic clock with SetClock; the callback receives a context ID and returns milliseconds or a negative value on failure.
  • dumpstack writes 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 libname activates a bundle registered with RegisterLibrary (a slice of LibraryCommand descriptors plus one context ID). Loaded commands are visible to info commands and callable; loads are idempotent, and a command conflict rejects the whole bundle. calc, io, list, and string are available by default.
  • puts string and puts -nonewline string write to the output buffer.
  • exit stops the current evaluation, including from a procedure, source file, or catch body; Eval returns .Exit to the embedding application. As in Limbo, exit ignores its arguments.
  • source ?-encoding utf-8? fileName evaluates the loaded script in the current frame and shares the command and nesting budgets. Library callers supply the reader with SetSourceLoader; the callback receives its context ID, the path, and a pointer to a Result, sets the result's owned value to the script on success, or returns an error with code = .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

  • open supports Limbo OREAD (the default), OWRITE, and ORDWR on existing files; r and r+ are aliases. w and w+ create or truncate a file, with optional octal or decimal permissions (default 0666). OWRITE preserves unwritten bytes. Append modes are unsupported.
  • close, eof, flush, gets, read, seek, tell, and channel puts ?-nonewline? fileId string are available. seek accepts SEEKSTART, SEEKRELA, and SEEKEND, as well as start, current, and end. Offsets and file sizes are signed 64-bit integers; failed seeks return Tcl errors.
  • Counted read returns up to the requested number of bytes. The Limbo line forms read one line; bare read appends a newline and read -nonewline returns the original line. gets strips 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, and file isdirectory use the configured backend. Writes take effect immediately, so flush validates 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.

S
Description
No description provided
Readme MIT
123 KiB
0 Stars 1 Watchers 0 Forks
Languages
Ziran 88.1%
Python 11.6%
Makefile 0.3%