Design

ztcl uses only the Zig standard library. References lists the sources that it follows.

The files

File in src/ What it has
ztcl.zig The root of the module.
value.zig The values, the number forms, and the list form.
interp.zig The parser, the parsed form, the frames, and the general evaluator.
vm.zig The bytecode: the compiler and the instruction loop.
expr.zig The expression language: the parser and the evaluator.
cmds.zig The core commands.
format.zig The format command.
dict.zig The dict command and its hash table.
bigint.zig Integers above 64 bits.
compact.zig The reset that keeps the commands.
more.zig lset, lsort, binary, and scan.
regex.zig The regular expressions: regexp, regsub, and the matcher.
ns.zig The namespace command, ensembles, and the unknown handler.
mathns.zig The commands of tcl::mathop and tcl::mathfunc.
extra.zig array, case, tcl::prefix, and the word boundary procs.
trace.zig The trace command and the traced cell form.
coro.zig coroutine, yield, yieldto, and tailcall.
clock.zig The optional clock command and a small msgcat.
fsroot.zig The root folder jail of file and channels.
chan.zig The optional channel commands and source.
sys.zig The platform interface of channels, the event loop, and socket.
event.zig The optional event loop: after, vwait, update, and fileevent.
sock.zig The optional socket command and its network policy.
enc.zig The encoding command of the channel capability.
oo.zig TclOO: classes, objects, methods, next, mixins, and filters.
proc.zig The optional exec, pid, and command pipelines.
filecmd.zig The optional file, glob, cd, and pwd.
pkg.zig The optional package command.
child.zig The optional interp command.
ucd.zig A small model of Unicode classes and case maps.
noise.zig The gradient noise of noise3.
point.zig The point procs: the check, the vector program, and both paths.
jit.zig The JIT: the state, the options, the compile at a call count, and the entry of machine code.
jit/mem.zig The executable region: no page is writable and executable at once.
jit/x64.zig The x86-64 assembler. jit/x64_golden.zig has the bytes of zig cc for each form.
jit/layout.zig The layout probe: the offsets and tag numbers that machine code reads.
jit/verify.zig The bytecode verifier and the static stack depths.
jit/helpers.zig The helper table: one C-callable wrapper for each instruction function of vm.zig.
jit/abi.zig, jit/tier1.zig, jit/tier1_x64.zig The registers, the driver, and the templates of tier 1.
jit/tests.zig The tests of the JIT.
main.zig The runner.
tests.zig The tests of the language and the commands.
wasm.zig The WebAssembly interface.

Values

A value is a tagged union: an integer (64 bits), a double, a string, or a list.

The parser and the compiled form

The parser follows the 12 rules of the Tcl language. It reads a script once and makes a Script:

Each word of a command has a cache slot. A command such as while asks the interpreter for the compiled script or the compiled expression of an argument. If the argument is a literal word, the result stays in the slot. A loop body, a proc body, and a braced expr are parsed one time.

A command site also keeps the command that its name gave. The interpreter has an epoch number that changes when a command is added, renamed, or deleted. The site looks the name up again when the epoch differs.

The direct forms and the slot hints

The general path uses these steps for a command that is not in bytecode:

A string that is not a literal word (for example the argument of eval) uses a table from the address and length of the string to the compiled form. A string does not change while it lives, so the address and the length name the text. A collection clears the table, because the address of a freed string can come back for another string.

The bytecode

vm.zig compiles a parsed script to a flat list of instructions. An instruction has 16 bytes: the operation, a small operand x, and three numbers a, b, and c. run executes the list on a small stack of values. A labeled switch dispatches the next instruction from the end of most handlers, so each handler has its own indirect branch.

What compiles:

The instructions:

Group Instructions
Stack push, push_empty, pop, concat
Reads access, lassign, lassign_drop
Variables load, store, store_pop, incr, incr_drop, incr_value, append, lappend, dict_update, dict_update_drop, lset, lset_drop
Operators binary, unary, to_bool, number_form, bin_vv, bin_vi
Control guard, step, jump, jump_false, jump_true, jf_vv, jf_vi, str_eq_jump, foreach_init, foreach_next, ret
General path invoke, eval_cmd, word, node

switch compiles for switch ?-exact? ?--? string {pattern body ...} and for the same form with the patterns and the bodies as separate literal words. Each pattern and each body is a literal. Without --, the string is a literal that does not start with a minus sign, because the general command reads such a value as an option. str_eq_jump compares the string form of the top of the stack with a pattern and jumps to the body, and an integer needs no string. A body of - falls through to the next body. A last pattern default takes each string. The other options and each other form use the general command. The guard of the form uses one step.

A cell that holds the canonical text of an integer gets the integer when a compare or an operator reads it (shimmer). The string form does not change. A loop bound that comes from argv then needs no parse in each pass.

lassign writes each item to a slot with the store rules of foreach_next and pushes the list of the items that are left. lassign_drop pushes nothing. lset and lset_drop call more.lsetOwned: the first call on a cell copies the list and the cell owns the copy, and each later call writes in place. An index outside the list, a cell that is not plain, or an error goes to the general command. A result that the script uses ends the ownership.

The semantics of Tcl stay:

The evaluator

Namespaces

A namespace is a prefix of names (ns.zig).

Regular expressions

regex.zig parses a pattern to a tree. It accepts the advanced, extended, basic, and literal syntaxes of re_syntax.n, with the embedded options, lookahead, and back references.

regexp, regsub, switch -regexp (with -matchvar and -indexvar), and lsearch -regexp use it.

Strings

A string is UTF-8 bytes. The string subcommands and glob patterns work on characters. A string of ASCII uses the byte offsets directly. Other strings need a pass over the bytes for each call, so string index in a loop over a long string that is not ASCII is slow. string map, the regular expressions, and format %c still work on bytes. ucd.zig is a small model of Unicode classes and case maps. It covers ASCII, Latin, Greek, Cyrillic, the space characters, and the common punctuation blocks.

binary format and binary scan see a string as bytes: a character below 256 is one byte.

expr

expr.zig parses an expression into a tree and walks the tree. Two integers use a fast path with no string work. An integer that overflows 64 bits continues as a big integer, as in Tcl. A big integer has at most 2^20 bits. An operation on big integers uses steps of the step limit by the square of its size.

The functions are those of Tcl 8.6, and four additions for zslice: clamp, lerp, noise2, and noise3. rand() uses a fixed seed.

A variable with a trace has the cell form .traced, and upvar a(i) x makes the cell form .elem. The fast paths of the bytecode read only .val, so a read of these forms goes to the general path. A store checks the tag with one compare (Var.plainStore). While var_traces is above zero, the inline forms are off, and foreach stores through setVar. A command with an execution trace has a wrapper as its function, so a call of another command has no added cost. tcl_precision is a .traced cell that does not count in var_traces. Its write check sets the precision of the double output.

Coroutines and tail calls

A coroutine has its own native stack, word stack, and frame chain. An exported assembly routine switches the stack on x86-64 Linux. The resumer swaps the fields of the interpreter around each switch. max_native is half of the stack of the coroutine. compact gives InterpBusy while a coroutine is suspended.

tailcall ends the proc with a private return code. The proc call then runs the command in a loop, so a chain of tail calls uses no native stack.

Capabilities

Interp.allow turns on optional commands. The default interpreter has none. A child interpreter allocates through the counter of its parent, so the parent limit counts it. A call into a child passes the step limit, the nesting counts, and the native stack base. A child that is deleted while it runs is freed when the last call leaves it. compact gives InterpBusy for an interpreter with capabilities.

The event loop

One loop serves an interpreter and its children (event.zig). The state has the timers, the idle scripts, and the channels with a handler. One pass waits until a timer is due or a descriptor is ready, runs the due timers in the order of their times, runs the handlers of the ready channels, and runs the idle scripts when no other script ran. A script of the pass cannot make the pass longer: a new timer or idle script runs in a later pass. Each script runs at the global level of its interpreter. An error goes to the handler of interp bgerror as an idle entry. vwait adds a trace to the variable that sets a flag and runs no script.

A channel that does not block keeps output that the peer has no room for. The loop writes the rest when the descriptor is ready. A close of such a channel keeps the descriptor under a hidden name until the output is gone.

Sockets and processes

sock.zig has the network policy: loopback, a list of rules, or any. sys.resolve is the only name lookup. sock.zig checks each address against the policy before sys.listenAt or sys.connectTo, checks the peer address of a new connection again, and checks each peer that a server accepts. proc.zig starts each pipeline as one process group and keeps the groups of background pipelines. The interpreter sends SIGKILL to each group when it ends, at the time limit of the embedder, and at a failed start. exec is not sandboxed.

The platform interface

sys.zig has the host operations of channels, the event loop, and socket: read, write, close, seek, poll, the blocking mode, and the loopback socket calls. fsroot.zig has the root folder jail, and proc.zig has the process calls. These files have the Linux forms. A port to another system writes the same functions again.

Safety and determinism

The JIT compiler

The JIT is off by default. On x86-64 Linux, -Djit builds it, and an embedder turns it on with Interp.enableJit. The JIT plan has the reasons and the later tiers. Milestone 1 is tier 1:

Point procs: the fast path

point proc name {fields} {body} makes two things from one body.

  1. A normal proc. point.runSlow calls it once for each point. This is the slow path, for tests of one point.
  2. A vector program. Program.run runs it over points in a struct of arrays (x[], y[], z[], the feature numbers, and the output arrays).

The check accepts only numbers, local set, if / elseif / else, return with no value, expr with the math functions, noise3 and noise2, a compare of the feature with a name, and the output commands (offset, move, width, flow, speed, skip). For all other code, it gives an error with the line and the reason when the script loads.

The vector program:

A test runs the fuzzy skin proc, and a second proc with branches, on both paths and compares all outputs bit for bit.

Both paths apply the same limits to the outputs at the end (point.bound), so the bits stay equal. The unit is the line width of the point (the width input, or 0.4 when the points have no width). The rule, for each point:

The embedder changes the numbers in Points.limits. The seed of noise2 and noise3 is Points.seed on both paths, and Interp.noise_seed for a normal script. The noise code has 8 lanes in two AVX2 registers, with each hash in a 64-bit lane. It keeps the 8 corner hashes of the last group of points and uses them again when the next group is in the same cells.

Known differences of the two paths: an integer division by zero is an error on the slow path and gives Inf or NaN on the fast path, and integers above 2^53 lose bits on the fast path.