Artifact 4412cc1fed7e484febe9b57d66b6e43d9f1680b050a75b56e7dede9db4e5a94a:
- File typeparse/doc/764.md — part of check-in [dd10cbf51b] at 2026-11-29 17:26:47 on branch tip-764_tcl90 — Notes and types together Notes now follow a value at any depth: path writes (set P(y) $n), product fields (construction, $P(x), $P(x,y), $P(*)), and nested paths. Only data notes travel; a pending field label such as {point/x} stays with the constructor. type parse reads notes as data: {mm@src=capteur}1500 no longer fails. Typed collections keep their type on the way out The element type is carried once by the collection and applied when a value leaves it. Elements are not copied, and compact storage is kept. lindex, lsearch -inline, dict get and dict for give a typed element. lrange, lreverse, lsort (including -unique and -command), lsearch -all -inline and dict filter keep the collection type; dict values gives list.T. The comparison command of lsort -command receives typed values, so a {kg} parameter rejects an mm. Canonical text with modes type canonic and type parse share the options -type, -notes, -value, -deep and -list. With no option, they cover everything, at full depth. Element notes and element types under any are written as prefixes, for example {list.mm}{{{@ok}5} 7}. The round trip is exact, checked on randomly generated values. -list returns {type notes value}, ready for lassign or a tuple assignment. type parse -list splits a canonical text by syntax alone, so the type may be unknown to the reader. Reading a canonical text never executes anything. Proposed public C API: Tcl_GetCanonicObj, Tcl_ParseCanonicObj and the TCL_CANON_* flags. Behaviour change: type canonic -notes now returns the notes alone; the old meaning is -type -notes. Core conversions no longer drop annotations A typed value used as a number, a regexp, a script, a command name, an option, a subcommand, a channel, an encoding, a namespace or a clock format keeps its type and notes. Core patch: annot-conversions.patch. New loss detector: ::tcl::unsupported::annotlost or TCL_TYPE_TRACE=lost. Found along the way, a Tcl 9 bug: lsort checked getElementsProc on objv\[1\] instead of the list. Fixes In expr, x is T now agrees with type is: an mm is not a kg, even though both are built on int. An integer typed as double now prints as 7.0. Known limits A typed value used as a variable name loses its annotation. So does a value whose representation is taken over by an extension type. type parse -value on an unknown type leaves the element prefixes in place. Tests 128 script tests pass in 5 modes; valgrind finds no leaks or errors. The fuzzers give identical output across modes. In the full core suite, fileName, http11, socket and tcltest show failures that do not appear when these files run alone. The comparison run with the old version used different settings, so this is not confirmed as environment-only. Next type eval: implicit conversion inside its block, and unit algebra for * and /. (user: Florentis, size: 75222) [annotate] [blame] [check-ins using]
TIP 764: Annotated Values, Typed Variables and Generalized Paths
Author: Florent Merlet <[email protected]>
Author: Claude (Anthropic)
State: Draft
Type: Project
Vote: Pending
Created: 19-Oct-2026
Tcl-Version: 9.2
Keywords: annotation, type, typed variable, path, struct
Post-History:
Abstract
This TIP adds annotations to Tcl: a prefix {text}word that attaches metadata to a word without changing its value. An annotation resolved by a variable constructor is a type, and gives the variable a contract checked on every write; an unresolved annotation is a note that travels with the value. A small declarative type language (type def) describes enumerations, sums, products (structs), typed lists, typed dicts, variable links and parameterized types. Parts of a typed value are read and written with a path in the array index: $R(A.x), set R((A,B).x) 10 30.
Both new syntaxes take over forms that are syntax errors in Tcl 9.0 ({x}word) or fall back exactly to the Tcl 9.0 rule ($name(...)). No valid script changes meaning, and code that uses no annotation sees no difference.
Binary representations (type binary, chan binary) are built on this TIP but are left to a separate TIP.
Rationale
"Everything is a string" keeps Tcl simple, but the developer always knows more about a value than its string says: that 12 is in millimetres, that a list holds only integers, that a dict must have a name key. Today this knowledge lives in comments and in hand-written checks scattered through the code. Errors surface far from where the bad value was stored.
An annotation puts this knowledge beside the value, as metadata, without touching the string. The word comes from Latin ad notare, "to put a note beside"; the Greek protokollon was likewise the sheet glued to the head of a papyrus roll, describing it without being part of it. An annotated value has a raw part, the string every command sees, and an added part, read only by commands that ask for it.
The proposal is driven by four needs:
- Check where values are stored.
set {int}n 5givesna contract;set n abcthen fails at the faulty write, not later. - Name what is built.
set {pt}a {/age}12 {/name}Jeansays which value goes where, in the source, never guessed from the data. - Reach the parts of structured data.
$R(A.x)andset R((A,B).x) 10 30replace chains ofdict get,lindexandlset. - Tell kinds of values apart.
type def mm {quantity(L, 0.001)}andtype def kg {quantity(M)}are both doubles, but akgis never stored where anmmis expected.
The design rule throughout: annotations live outside the plane of raw values. A computation (expr, string toupper) returns a bare value; only copying, list access and argument passing keep the annotation. Scripts that use no annotation run exactly as before.
Specification
1. Annotated values
Syntax. A word of the form {text}rest, where rest is not empty, is an annotated word. text is the annotation; rest is parsed as an ordinary word (literal, $var, [cmd], "...", {...}). {*} keeps its meaning. The value of the word is the value of rest: the annotation never appears in the string.
puts {mm}12 ;# 12
string length {mm}12 ;# 2
Glued annotations {a}{b}$x are not a syntax: the form would be ambiguous with {int}{300}, an annotation on a braced literal. Annotations stack by annotating a value that is already annotated.
An annotation is an option (v18h). Like an option, an annotation is addressed to the command that receives the word, and that command decides what it means; its documentation says it, argument by argument, as it says its options. A command cannot know where an object came from (a variable, a command, a literal: EIAS), but it knows whether an annotation was written on the word of this very call, and it knows the role of each of its arguments. Six behaviours are provided for commands to draw on:
| behaviour | meaning of {T} |
examples |
|---|---|---|
| name | the type of the variable (its contract) | first argument of set, variables of foreach and lassign, a typed parameter {T}x |
| constructed value | the type of the value: T must exist; a bare value takes it, a typed value must enter it as it is |
the value of set, a typed argument, x = v and x is T = v in expr, a typed return, type {T}word |
| option | passed as is; the command reads it (note get) |
an untyped procedure parameter |
| kept | stored as a note on what the command stores | list, the elements of lappend, linsert, lreplace, lset, the values of dict |
| ignored | expires with the command | string length, puts |
| label | a field or a variant, read by the constructor of a product or a sum | {/name} |
{list} and {dict} are options of the commands that consume a value (foreach, lmap, lassign, dict for, dict map): they read a product as a list or a dict, through one C function.
Notes. A note is data carried by a value: it follows it through copies, arguments, return values and list elements, and no constructor ever reads it as a type. Notes are written in a text syntax: , separates siblings, . goes down, (...) groups children, = gives a leaf a value, "..." quotes; a later leaf removes what lies on its path, above or below (as a CSS shorthand resets its longhands). A leaf is stored as a.b=v.
set v [note set {style.(bold,color=red),link.target="https://tcl.tk"} 5]
note get $v ;# link.target="https://tcl.tk",style.bold,style.color=red
note has $v style ;# 1
set w [list {mm}5] ;# list keeps the annotation: a note
Types. A constructor resolves an annotation on a value against the types the interpreter knows (section 2); an unknown name is an error (unknown type "zz"). On a bare value the type is given, after validation; on a typed value the annotation checks, it never converts: the value must enter T as it is (widening, a nominal's base, a predicate that holds, a variant into its sum, any value into string, a structural collection into its nominal), otherwise type mismatch: the value is mm, the annotation says m (an annotation does not convert: use type cast m). type cast is the only conversion. Where an annotation acts. Only on the command that receives the word. Nothing is resolved during substitution: Tcl substitutes every word before it calls the command, and only the command knows whether a word is a value or a variable name. When that command is done, whatever is still pending expires: it becomes a note. So the error is always raised inside the command that holds the word, and an enclosing catch catches it. An untyped procedure parameter is not a constructor: what was written on the word expires at the binding and the procedure reads it as notes, labels included.
Computed note values (v18j). Like the text of expr, the text of an annotation is literal for the parser (TCL_TOKEN_ANNOT has no components); the annotation machinery substitutes the values of notes, =$name, =${name} and =[script], once, when the word is evaluated, in the scope of whoever wrote it. A substitution is one whole value, never read again as syntax: list {style.color=$c}5 with c holding blue,bold gives one note style.color="blue,bold", not two. Elsewhere, in a type, a key or a path, $ keeps its meaning (list($n).f64le names a field). An annotation written in the source whose text reads as several notes ({a,b}5) becomes several notes when it expires.
Computed annotations. annotate NOTES $v is the computed form of {NOTES}$v: it gives its result to the command that receives the word, and it expires with it. annotated $v is annotate [note get $v] $v, the value with its own notes pending again. A relay is therefore written in the source:
proc mk {v} { set {shape}S [annotated $v] } ;# mk {/side}2.0
Two stacks and unstacking. An annotated value carries at most one resolved type and a stack of pending annotations above its notes; they are displayed as type@note1,note2. A constructor:
- takes the most recent pending annotation and resolves it (an unknown name is an error);
- continues while annotations resolve;
- checks that the unstacked types are consistent, else
contradictory annotations A and B; - gives the value the most recent type, without converting it;
- lets the variable's contract make the final check.
A note never becomes a type later: type def gives no meaning to an existing note.
Labels. A field of a product or a variant of a sum is named by a label, {/name}value: set {pt}a {/age}12, set {S}v {/i}5. A label is a local annotation (below): it can never be a type, so a global type of the same name changes nothing, and {name} without the colon is always a type or a note. A label is read by the constructor that receives the word, even through another command (set {pt}a [f {/age}12]); a label that no constructor reads cannot be stored. The old form {age}12, when age names a field and no type, is an error that gives the new spelling.
Local annotations. An annotation whose text contains a character that type names refuse (-, ?, :...) can never be a type. It is local: it passes from a caller to the called command and is not stored. Three families are intended, with no possible collision with a type name: options {-name}, questions {name?} and labels {/name}. Storing or declaring with a local annotation is an error (local annotation {-v} cannot be stored by "set").
The empty annotation {}. On a value in a constructor (set v {}$x), it removes the resolved type and keeps the notes. On a variable name (set {}v $x), it lifts the variable's contract. On a value outside a constructor, the reader sees the bare content. The original value is never modified.
The note command.
note get VALUE ?PATH? the notes, grouped (a.(b,c)); a branch, or a leaf's value (v18i)
note dict ?-paths? VALUE a nested dict; with -paths, {path {value}|{}} (v18i)
note merge FROM VALUE VALUE with the notes of FROM underneath, its own winning (v18i)
note has VALUE NAME 1 if NAME is a note, or the path of one (a.b in a.b.c, a.b=v)
note delete VALUE ?NAME? the value without the note or the branch NAME, or without any
note set NOTES VALUE the value with these notes only (data, never types)
note add NOTES VALUE the same, merged: the later leaf wins
note delete, note set and note add return a new value; Tcl values stay immutable. Content and resolved type are unchanged.
Notes and types together (v18k). Notes follow a value at any depth: written by a path (set P(y) $n), put in a product field, read back by a path ($P(x), $P(x,y), $P(*)), a value keeps its data notes as a list element does. What comes out of a typed collection keeps its type, which the collection carries once and which is set on the way out (no per-element copy, compact storage kept): lindex, lassign, foreach, lsearch -inline, dict get and dict for give an element of the element type; lrange, lreverse, lsort (including -unique and -command), lsearch -all -inline and dict filter keep the collection type (a nominal, fixed-length or predicate collection keeps it when the slice fits, otherwise list.T); dict values gives list.T. A computation (lmap, lappend on the result) gives a plain value. The comparison command of lsort -command receives typed values: an untyped parameter accepts any of them, a {kg} parameter refuses an mm.
The canonical text and its modes (v18k). type canonic and type parse take the same options: -type, -notes, -value, -deep, -list; with none, everything at any depth. -value is the ordinary string; without -value, the prefix only (mm, ok, mm@ok); -list gives the parts in the order type, notes (in the form of note get), value, for lassign or a tuple assignment. In a structure an element writes as a prefix what the structure does not say: its notes ({list.mm}{{{@ok}5} 7}), its own type under any ({list.any}{{{mm}3} x}), the notes of a variant ({/fahrenheit@q}2.0); a scalar that would look like a prefix is written {}text, an untyped list with annotated elements {list}. type parse reads all of it back exactly; its options say what the value keeps (-value: the string; -type: no notes; -notes: no types, and then an unknown type is not an error); type parse -list splits a canonical text by syntax alone. Nothing is ever executed. The string of a typed value stays its bare value everywhere; the canonical text is the declared format for exchanges between two typed worlds. C: Tcl_GetCanonicObj(interp, v, flags, &res), Tcl_ParseCanonicObj(interp, text, flags, &res), flags TCL_CANON_VALUE, _TYPE, _NOTES, _DEEP, _LIST, _ALL.
Core conversions keep the annotation (v18k). A command that reads a number, a pattern, a script, a command name, an option, a subcommand, a channel, an encoding, a namespace or a clock format from a typed value works on its content: the value keeps its type and notes. ::tcl::unsupported::annotlost on|off|get|clear (or TCL_TYPE_TRACE=lost, on stderr) reports any remaining loss with the command, the type, the notes and the value. Known limits: a typed value used as a variable name, and an extension type that stores its representation in the object itself (Tcl_ConvertToType).
Debugging with notes (v16y). A note follows its value through copies, arguments, list elements, loop variables and procedure parameters, which is what is needed to follow a piece of data through a program. A note @name is an instrument note: it is never a type. type debug on traces every command (inline compilation is off while the trace is set; nothing is tested when it is off); before a command runs, the notes of its arguments are read. {@trace} reports each command that receives the value (command, parameter name, value, file:line, calling procedure); {@step} also stops there with a prompt (continue, step, run, quit, stack, locals, print a variable, or any Tcl command run where execution stopped). Stepping, or type debug next written in the code, stops at the next command whatever its notes. type debug when NAME EXPR makes {@NAME} conditional ($value, $cmd, $arg, $hits: type debug when neg {$value < 0}). type debug console shows a Tk window instead of the stdin prompt: the stack, the variables of the selected frame with their type and notes, the log of passages, and a command line run in the selected frame. type debug hook CMD replaces the display: CMD note words index; an error from the hook prevents the command (an assertion). Ordinary notes are proto-types, names put on values before the type exists (since v18h with note set, a constructor refusing an unknown name): while tracing, each name that is not a type is recorded (count, first location, commands, a few values with their location); type debug notes returns the inventory as a dict and type debug report as text, suggesting the nearest type name for a probable typo and, once the type has been defined, checking the recorded values against it.
type debug ?on|off? trace commands for instrument notes; without argument, the state
type debug next stop at the next command
type debug when ?NOTE ?EXPR?? a condition for {@NOTE}
type debug console ?on|off? the Tk console
type debug hook ?CMD? the hook (default ::tcl::typedebug::hit)
type debug notes|report|clear the inventory of proto-types
2. The type command and the type language
type def NAME DEFINITION define a nominal type, or a parameterized family
type def NAME DEFINITION {-compact}FORM ... the same type, and its forms in another layout (v17m)
type alias NAME DEFINITION give a structural name to a definition
type get VALUE the resolved type of a value (empty if none)
type cast TYPE VALUE the conversion: rules, families, variants, truncation
type {T}WORD give a type, as a constructor does: never converts (v18h)
type var NAME the type of the variable NAME (its contract), empty if free (v18h)
type def NAME the definition of NAME, of a variant S/v or a field P/f (v16o)
type proc NAME the signature of a typed procedure: args, return (v16p)
type {{*}T}WORD, {{**}T}WORD the same, returned unfolded as a list / a dict (v16r)
type is {disjoint?}S the pairs of variants that can take the same value
type is {union?}S 1 if S is a union (|) (v16w)
type is {sum?}T, {enum?}T a sum; an enumeration (literals only) (v17z)
type is TYPE VALUE 1 if the value is of TYPE, as string is: a typed value
whose type enters TYPE, or a bare value valid for it (v18f)
type match TYPE VALUE how the value enters TYPE: auto (set {TYPE}x and an
argument accept it as is), cast (only type cast does),
or mismatch (v18g)
type variant VALUE ?NAME? the named variant of a value (empty for a literal);
with NAME, the same payload under variant NAME (v17z)
type variant -of T ?NAME? the named variants of T, or the payload type of NAME
type literal -of T the literals of T (the values an enumeration allows)
type eq VALUE VALUE 1 if both have the same resolved type, variant included
(a bare value has no type: an error, v18f)
type include U T 1 if every value of T enters U unchanged, without a cast
and without a check that could fail (v17z)
type debug ... debugging with notes (v16y, § 1)
type convert FROM TO LAMBDA declare an explicit conversion
type deref VALUE a snapshot: each var link replaced by its value
type def creates a nominal type: type def port int(u,16) is distinct from int(u,16). type alias only names a definition. In expr, v is T tests a variable's type; x is T = v declares and assigns.
Base types. int (unbounded), double, string, list, dict (the ordinary Tcl list and dict), var (a link to a variable, by name), any (an element of a heterogeneous list.any). Refinements restrict a base type: int(u|s, n), double(32|64), string(ENC, N|z), bitarray(n). Their binary representation is outside the scope of this TIP.
Composition language. A definition is parsed on the model of expr. Operands are types (bare words), names (a word glued after }: {int}age) and values (quoted, braced, or after =). Operators, from the strongest:
| operator | role | example |
|---|---|---|
. |
nesting (right-associative) | list.dict.int |
( ) |
arguments, glued to the name | list(3).int, dict(x, y?) |
= or ?= |
default value of a field | {int}age ?= 0 |
; |
product | {double}x; {double}y |
, |
sum (tagged) | {int}i, {string}s |
\| |
union (v16w) | {int}n \| {list(2).int}pair |
{ }name |
grouping, named by the word glued after } |
{{int}x; {int}y}A |
;, , and | do not mix at one level; mixing them requires braces. A type name contains only ASCII letters, digits, _ and non-ASCII bytes, and does not start with a digit. Any other ASCII sign outside the grammar is refused with TCL PARSE TYPE BADCHAR; this is what keeps local annotations safe. A definition is declarative: nothing is substituted when it is read, except in default values.
Grammar (ISO EBNF). Precedence, from the weakest: ;, then , and |, then =, then ..
type = item , { ";" , item } (* product *)
| item , { "," , item } (* tagged sum *)
| item , { "|" , item } ; (* disjoint union *)
item = chain , [ default ] ;
default = ( "=" | "?=" ) , value ;
chain = primary , [ "." , chain ] ; (* nesting, right-associative *)
primary = group
| typename , [ "(" , args , ")" ] (* list(3), int(u,16), pt(double) *)
| "$" , name (* a parameter, in a family body *)
| "*(" , linkargs , ")" (* binary link *(origin, repr, options) *)
| quoted ; (* a literal: "red", "MZ" *)
group = "{" , type , "}" , [ fieldname ] ; (* {T}name: a field; {T} alone: grouping *)
fieldname = [ "-" ] , name , [ "..." ] ; (* -name: an option; name...: variadic *)
typename = [ "::" ] , name , { "::" , name } ;
name = namestart , { namechar } ;
namestart = letter | "_" | nonascii ;
namechar = namestart | digit ;
value = quoted | braced | bareword (* a literal default *)
| "[" , script , "]" (* computed at each construction *)
| "$" , name ; (* a parameter, or an argument already bound *)
comment = "#" , { any - newline } ;
args = count (* list(N) *)
| ( "u" | "s" ) , "," , count , [ "," , endian ] (* int *)
| ( "32" | "64" ) , [ "," , endian ] (* double *)
| encoding , "," , ( count | "z" | expr ) (* string(utf-8,z), string(raw,$len - 4) *)
| count , [ "," , ( "lsb0" | "msb0" ) ] , [ "," , endian ] (* bitarray *)
| [ key , { "," , key } ] (* dict(x, z?=0); dict() *)
| expr (* at($off) *)
| type , { "," , type } ; (* a family instance: pt(double) *)
key = name , [ "?" , [ "=" , value ] ] ;
endian = "be" | "le" ;
family-head = name , "(" , param , { "," , param } , ")" ; (* type def {pt({type}T)} ... *)
param = "{" , ( "type" | "int" | "double" | "string" ) , "}" , name ;
In a product every field and group has a name; in a sum every typed variant does; -name and name... exist only in a procedure signature.
Containers.
type def color {"red", "green", "blue"} ;# enumeration
type def S {{int}i, {string}s} ;# sum: the value is "i 5" or "s abc"
type def U {{int}n | {list(2).int}pair} ;# union: the value is 5 or {3 4}
type def pt {{string}name ?= "?"; {int}age ?= 0} ;# product
set {list.int}L 10 20 30 ;# typed list
set {list(2).int}c 3 4 ;# list of exactly 2
type def record {dict(name, age?=0).string} ;# dict: name required, age optional
set A 1; set {list.var.int}V A ;# link: V(0) reads ::A
Structure comes from the type, never from re-reading the string. A typed scalar (a string, a number) is one list element: the elements of a list.string are never split again into words, at any nesting depth. A container (list, dict, product) unfolds: a product's list view is its fields, each in its type (lassign $P x y on a point). Dict keys are always text; only values are typed.
Default values. A default is a literal, a $variable or a [script], evaluated at each construction. A field with no default must be given: field "x" of pt has no value and no default.
Forms of a type (v17m). For C, a list of doubles stored as contiguous cells and a list of Tcl objects are different types; for Tcl, they are the same values. type def poly list.double {-compact}polyc defines poly and its form polyc: the same type in another layout (only layout options are allowed on a form, and the layout must be possible, which is checked by type def). A form enters its type unchanged: a parameter {poly}p, a constructor set {poly}x, or a plain assignment to a variable holding a poly, accept a polyc as it is, without conversion. Entering a form is a layout contract, written explicitly: {polyc}p refuses a poly ("use an explicit cast"), and type cast polyc $v / type cast poly $v change the layout without any type convert rule (cells from the same layout cost a copy, 0.5 ns per element). type get returns the exact form, which C, cproc, ffi and the specialised operations see as a distinct type. Forms of a parameterized family are not yet possible.
Parameterized types. The name in type def may declare parameters, written like fields and used with $ in the body. Types may be recursive.
type def {pair({type}T)} {{$T}x; {$T}y ?= 0}
set {pair(double)}p {/x}1.5 ;# 1.5 0
type def {tree({type}T)} {{$T}value; {list.tree($T)}children}
Phantom parameters. A parameter absent from the body distinguishes instances without changing values. Units of measure follow:
type def {quantity({string}dim, {double}f = 1.0, {double}o = 0.0)} double
type def mm {quantity(L, 0.001)}
type def m {quantity(L)}
type def kg {quantity(M)}
type convert quantity quantity {{x from to} {
if {$from(dim) ne $to(dim)} {return -code continue}
expr {($x * $from(f) + $from(o) - $to(o)) / $to(f)}
}}
set {mm}a 1500
set b {m}$a ;# 1.5
set {m}c $a ;# type mismatch: expected m but got mm (use an explicit cast)
set d {kg}$a ;# unknown way to cast the value from mm to kg
A type convert rule targets a type or a family; return -code continue means "not applicable". Conversions between nominal types are always explicit.
Namespaces (v16u). A type belongs to the namespace where it is defined, like a procedure: namespace eval geom {type def point …} defines ::geom::point; type def ::point … a global type. A name resolves like a command: the current namespace, its namespace path, then the global namespace. A procedure's signature resolves in the procedure's namespace, a family's body in the family's namespace. type get returns the qualified name of a namespaced type (::geom::point) and the simple name of a global one; namespace tail gives the short form. namespace delete removes the names; values keep their type. A typed value keeps the type table of its interpreter alive, so it survives interp delete.
Predicates (v17u). A type can be restricted by a predicate, written as its last argument in parentheses, the expression form of TIP 759, where $ alone stands for the value: type def even int(($%2==0)), int(u,8,($ < 100)), string(($ ne "")), double((0 <= $ && $ <= 100)), and list.even restricts each element. The predicate is checked when a value enters the type (set {T}x, a parameter, type cast, a write through a path, incr, list construction, type repeat, a typed type map result): it works as a visa, so a value already of that type enters as it is and is not checked again. A typed int enters even without a cast when the predicate holds, and an even is accepted wherever an int is expected. The predicate may read qualified variables (int(($ < $::max))): the value certifies the condition held when it entered. An unqualified variable is refused at definition, since it would be read in whatever frame checks the value. The predicate must not change any state, like a C assert: it is not evaluated when checking is off, and a value with a visa is not checked again. A predicate that reads only the value, numbers and numeric qualified variables is computed without the interpreter; otherwise it goes through expr, with the value written in as a literal.
Mapping an expression: type map
type map varList list ?varList list ...? {(expression)} applies an expression to every element and returns the list of results. The lists advance together and must have the same length; a list of K variables takes a list of K columns, which is what a path with several fields returns:
set d [type map {x y z} $P(*.(a,b,c)) {($x + $y * $z)}]
set s [type map {x} $L {k} $weights {($x * $k)}]
The body must be an expression in parentheses, the form of TIP 759. When it uses only numbers, variables, arithmetic, comparisons, &&, ||, !, ?: and the usual math functions, it is compiled once into a small numeric program and evaluated in C, element by element, without objects; variables that are not loop variables are read once. Any element this program cannot handle exactly as expr would (overflow to a big integer, division by zero, a non finite result, a value that is not a plain number) is evaluated by expr, and so is every element of an expression outside this subset: the result is always the result of expr. Like lmap, the variables keep the values of the last element. With -min or -max, the smallest or largest result, as ::tcl::mathfunc::min / max would return it. With -sum, type map returns the sum of the results, as ::tcl::mathop::+ would compute it from left to right (in C while the numbers allow it, otherwise by ::tcl::mathop::+ itself). The result is a list.double or a list.int, stored compactly, when all results are of that kind, and an ordinary list otherwise. Reading a strided slice of a compact list of numbers ($L(1::2)) or a column of a compact list of products ($P(*.a), $P(*.(a,b,c))) gives a view: the base cells, an offset, a step and a count, without copying (an internal representation, like the result of lrange; the base is shared and copied before any write, as any Tcl value). Writing a compact slice into a compact list copies the cells, without an object per element. When the compiled expression computes in doubles only, it is evaluated in blocks of 256 elements: the values of each column are first gathered into a small array (from cells, views or objects), then each operation of the program is applied to the whole block; an element that is not a plain double, or for which an operation gives a non finite result, is evaluated again on its own by the ordinary path, so the result is still the result of expr. From 10,000 to 100,000 elements: 3–5 ns per element from cells, 9–10 ns from objects, against 100–150 ns for lmap; on a million elements, 7–8 ns and 17–20 ns.
The variables of type map may be declared as the parameters of a procedure, and its body may state what it returns: type map {{double}x; {double}y} $pl((0,1)::2) {{double}u; {double}v}{($c*$x - $s*$y, $s*$x + $c*$y)}. An input signature (an annotation {T}name, or a ;) names the variables; each column is checked, or stored as a list.T, once on entry, as an argument is, and the computation follows the declared types. An annotated body {T}{(...)} gives the type of what the body returns for each element: a scalar type gives a column list.T (with -sum, -min or -max, a T); a product written inline gives one column per field, filled in order by the tuple of the body; a named product gives a list of that product. Each column is stored in the type of its field. An empty annotated body {T}{} is a projection by names: the fields of T are taken among the input variables (selected, reordered, converted; a missing name is an error, there is no renaming). Without any annotation, type map keeps its meaning (that of expr). The components of a tuple are compiled separately when they can be; otherwise the whole body is evaluated by expr, element by element, and its tuples are split into columns. -fold {s init} makes type map an accumulation: s starts at init, the body gives its new value for each element, and the command returns the last one (and leaves it in s), exactly as set s init; foreach u $U v $V {set s [expr {body}]} would, bit for bit: operations are performed in the same order, without parallel partial sums. When the top of the body is a binary operation one side of which reads only s (and fixed values) and the other does not read s, that other side is computed by blocks and only the combination remains sequential. foreach and lmap consult, on each call, a registry of vectorisable loops (TclVecRegister, entries tried by decreasing priority; an entry returns TCL_CONTINUE when it cannot run that call exactly as the loop would). The built-in entry runs on the type map engine and accepts one variable per list (neither traced, typed nor an array), lists of equal length, a body that is a pure expression (E) or expr {E} (or, for foreach, an accumulation (s = E) or set s [expr {E}]), with the built-in expr and set, or, for foreach, incr s ?E? with the built-in incr (an integer accumulation: when a value is not an integer, the ordinary loop run again gives the error of incr). type repeat T N ?value? returns a list.T made of N times the value, and type repeat -into L N ?value? a value of the list type L (its element type; a length fixed by L, list(N) or list(a:b), is checked). The value defaults to the zero of the element type (0 or 0.0) and is required for other element types; it is checked once. The result is always stored in cells when the element type has a cell layout, without -compact: the value is encoded once into the first cell and copied as a block into the others, without an intermediate list (one million bytes: 0.1 ms, against 2.5 ms for type cast of an lrepeat list). Loops compiled inline (a literal body in a procedure) whose body has one of these forms are compiled with a guarded call to ::tcl::unsupported::vecloop placed before the ordinary bytecode; it returns {1 result}, or {0 list ...} with the lists already evaluated, and the ordinary loop runs on them. Results, errors (message and errorInfo: on error the ordinary loop is run again from the start, the body being pure) and the variables after the loop are those of the ordinary loop. Since the raw commands of TIP 759 are compiled as any command, they benefit without change. This is the engine a comprehension in expressions (s = 0; u @ $U, v @ $V : (s = $s + $u*$v), TIP 759) would compile to. The annotation is placed on the body rather than on the command name because it types the value the body produces, as {T}value types any value, and because it keeps the order of the data flow: what comes in, the data, what comes out, how.
In place: type map -in (v17w). type map -in var(path) varList ?varList list ...? body computes like type map, with the first varList bound to what the path designates in the variable, and writes the result back at the same place: one value per column of the path (a tuple for a window), all or nothing. It returns the new value of the variable, like lset or ledit. The output type is the type of the target: each value is stored as by an assignment (validation, cells, predicates); an annotated body only declares a type, checked once to enter the target's element type. type map -in pl((0,1)::2) {x y} {($c*$x - $s*$y, $s*$x + $c*$y)} rotates a polyline in place; on a shared list in cells, the buffer is copied once (or not at all when the path covers every cell) and the results are written at their stride.
3. Typed variables and constructors
Contract. A variable declared with set {T}v ... checks every later write, whatever its origin: set, lappend, lset, incr, dict set, a path write, or expr {v = ...}.
set {list.int}M 1 2
lappend M 3 ;# 1 2 3
lappend M x ;# expected integer but got "x"
Widening and casts. A refinement goes where a wider type is expected (int(u,8) into int); narrowing needs an explicit cast. A nominal type gives way to its base, but two nominal types with no base link are never equivalent. type cast T $x tries, in order: a type convert rule, the chain of bases, a sum's variant, a family rule, the built-in scalar conversions. Otherwise: unknown way to cast the value from A to B. Since v18h an annotation never converts (set v {T}$x, type {T}$x, a typed argument): only what keeps the string, else type mismatch ... use type cast T.
A typed string is an element, not a list. List commands see a typed scalar value (string, a number, a string nominal) as one element, whatever its spaces or braces: llength $s is 1, lindex $s 0 returns the whole string, any other index is outside the list (empty, as everywhere in Tcl), foreach iterates once. The only way to a list is split, which starts from the string and returns a bare list. This is the advice given to Tcl programmers all along, "never use list commands on arbitrary strings, use split", whose neglect also reaches everything that embeds Tcl (Tkinter and industrial products report "unmatched open brace in list"); a value typed string guarantees it instead of asking for it. Bare values are unchanged: foreach x "a b c" and lindex $argv 0 still see lists.
Two types: the variable's and the value's (v18h). type var NAME gives the type of the variable, its contract; type get $NAME the type of the value it holds. set y {m}1500 leaves y free and stores an m; set {m}y 1500 gives y a contract.
Commands ignore types; scripts ask (v18g). A command sees the value only: incr a $c adds two numbers whatever their types, and a typed variable checks what it receives (incr on an int(u,8) past 255 is refused). Only variable constructors consult the type: set {T}x, a typed argument, type cast. A script that wants to decide asks type match T $v, which answers auto (the constructor and an argument accept the value as it is), cast (only type cast does: a rule, a family, another variant, a truncation) or mismatch. Both tries are the real paths, so the answer never contradicts what set and type cast will do:
switch [type match [type get $a] $c] {
auto { incr a $c }
cast { incr a [type cast [type get $a] $c] }
mismatch { error "type mismatch" }
}
Since v18g a typed argument and type cast follow set {T}x for predicates: a value whose type enters the predicate's base enters the restricted type without a cast, the predicate checked.
What keeps the annotation.
| operation | type | notes |
|---|---|---|
| copy, argument, return value | kept | kept |
lindex, foreach, $L(i) on a list.T |
element typed T |
- |
string cat $x (one argument) |
kept | kept |
computation (expr, string toupper, dict set on a value) |
lost | lost |
{T}$x in a constructor (gives the type, never converts) |
given | kept |
type cast T $x |
changed | kept |
Value types and contracts. A value keeps its type wherever it goes, but only an annotation on a variable's name gives the variable a contract. In set A $B or set A {T}$B, A holds a value of type T (type get $A), and any later write to A is still accepted. Procedure arguments follow the same rule: an argument receives typed values without becoming strict. foreach, lmap, dict for and dict map forget the type of their loop variable before each assignment.
set {list.int}L 1 2 3
set e [lindex $L 1] ;# e holds a value of type int
type get $e ;# int
set e hello ;# accepted: e has no contract
set {int}n [lindex $L 1] ;# the contract comes from the name
set n hello ;# expected integer but got "hello"
Declaring in any writing command. A type annotation on the variable name declares the variable in every command that writes it, not only in set: lappend {list}M x is set {list}M $M followed by lappend M x. The new contract is built from the current content and replaces any previous one; {}M lifts it. This is done once, where every access by name converges (TclObjLookupVarEx), so lappend, lset, incr, append and dict set behave alike.
set {list.int}L 1 2 3
set M $L ;# M holds a list<int> value, without a contract
lappend M x ;# 1 2 3 x: a modification is a computation, M is now a plain list
lappend L x ;# expected integer but got "x": L has a contract
lappend {list}L x ;# 1 2 3 x, L is now declared list
incr {int}n ;# n receives the contract int
dict set {dict.int}D b 2 ;# D is now dict<int>
A modification is a computation. Without a contract, lappend, lset, incr, append or dict set on a typed value return a plain value, as expr does; they never fail because of the value's type. Under a contract, the result is checked when it is stored, and the variable keeps its old value if the contract refuses it. Seen from a command that ignores annotations, a value is its string; only declarations, visible in the source on a name, add checks.
Collections and elements. A declaration says what an element is. Only collections (list, dict) show their elements to the list view (llength, lindex, foreach, lassign, {*}); a scalar, a product or a link is one element, and a sum takes the nature of its active variant. The parts of an element are reached by path: $P(x), or $P(*) for all of them in order.
type def Point {{int}x = 0; {int}y = 0}
set {Point}P 100 7
llength $P ;# 1: a point is one element
set {list.string}L {hello world} b
llength [lindex $L 0] ;# 1: "hello world" is one string
deux {*}$P(*) ;# the fields as two arguments
expr {(x,y) = $P} ;# tuple assignment reads the fields
This separates two entities that untyped Tcl lists conflate, and removes a family of bugs (a string split into words, an element dug into, a misplaced {*}). Undeclared values keep the Tcl rule: their list view is the list view of their string.
Building a product. A product of n fields is built in one of these forms; nothing is guessed from the data.
| form | example | rule |
|---|---|---|
| positional | set {pt}a Jean 12 |
exactly n values, in field order |
| field labels | set {pt}a {/age}12 {/name}Jean |
every value tagged, any order; omitted fields take their default |
| one field | set {pt}a {pt/name}Jean |
the other fields take their default |
| path + positional | set {pt}a(age,name) 12 Jean |
one value per leaf of the path, or per group |
| no argument | set {pt}a |
every field at its default |
| copy | set {pt}a $b |
$b already of type pt |
Anything else is wrong # args: pt needs 2 values; to name fields (the others take their default), write {/field}value or set {pt}var(field,...) value....
Field labels. Each argument names its field with a label, {/field}value. Labels are all or nothing:
type def couple {{string}name; {int}age ?= 0}
set {couple}p {/name}jean {/age}12 ;# jean 12
set {couple}p {/name}zoe ;# zoe 0
set {couple}p {/name}jean 12 ;# can't mix values named by a field label ...
set {couple}p {/name}a {/size}3 ;# unknown field "size:" in couple
set {couple}p {/name}a {/name}b ;# duplicate field "name" in couple
set {couple}p {name}jean ;# {name} is not a type: ... write {/name}
Path and positional values. set {T}v(path) v1 v2 ... builds the product and its nested products. The number of values chooses the distribution: one per leaf, one per element of the head group, or one for the whole path. Each value has the shape its read would return.
type def rect {{{int}x; {int}y}A; {{int}x; {int}y}B}
set {rect}R(A.x,A.y,B.x,B.y) 1 2 3 4
set {rect}R((A,B).(x,y)) 1 2 3 4
set {rect}R(A.(x,y),B.(x,y)) {1 2} {3 4}
Sums and unions (v16w, v17z). The variant of a sum is metadata, like the type: the value of a sum (,) is its payload alone, and type get gives S/v. Every typed variant has a name. Nothing is guessed: a bare value takes the variant only when exactly one variant accepts it (a literal always wins, being a single value); otherwise it is an error that shows the label (value "5" fits variants i and s of S: write {/i}5). A variant is not sticky either: a bare assignment is deduced again. The variant follows the value through copies, arguments, returns, list elements and fields; outside the interpreter (a file, a socket, C) it is lost like the type, and a value read back is an error when ambiguous, never another choice. type canonic writes the variant when the string does not tell it ({S/s}5, and a label {/s}5 for an element of a structure), and type parse reads it back. Equality is on values: eq, == and dict keys see 5 whether it is S/i or S/s; type eq compares the types, variant included. A union (|) is a sum whose alternatives must be disjoint, which is checked when it is defined (type is {disjoint?}S gives the overlapping pairs): its alternative is always deduced, the strictest one winning (num). A sum is built with a label (set {S}v {/i}5), by the variant's type (set {S/s}w abc) or by a path (set {S}v(i) 5); lappend and lset read the label of an element; type variant $v NAME relabels the same payload (converting is type cast S/NAME $v, through type convert). $v(i) reads the payload checking the variant, $f(w) reads a part of the current payload, type variant $v gives the variant. A sum reads as its variant's type (expr {$v * 2}, type cast int $v). opt(T) is {T}some, "none". A sum placed in the payload of another sum keeps its own variant (v18b).
Members (v18a). A field of a product and a variant of a sum are the members of their type, and both are written with /, on the value side and on the type side. A label is {/name}value (it names the field or the variant the constructor reading it fills: set {pt}a {/age}12 {/name}Jean, set {S}v {/i}5, return {/v}$x, f {/dx}3). P/f is the type of field f of product P (type def point/x gives double); S/v names variant v of sum S ({temp/celsius}4, type cast temp/fahrenheit $t, type include temp temp/celsius, and what type get returns); {P/f}value is a label checked against P; in expr, x is S/v tests that variable x holds a value of S with variant v. The bar is used because . composes types (list.int) and : separates namespaces (::geo::point); / enters no type name, so a member never collides with a type, and a variant may be named like a type ({{int}int, {string}string}: {/int}5, V/string). The former spellings {name:} and S.v are refused with a message that gives the new one. Paths are unchanged ($p(x), R(A.x, A.y)). Chains of members (mesure/some/celsius, list.temp/celsius) came with v18b, where a variant is a type of its own.
Variants are types (v18b). A sum is a collection of alternative types, and each variant is a type: S/v is the sum S restricted to its variant v, a subtype of S. A variable, an argument, a return, a field or an element declared S/v accepts only that variant (set {temp/celsius}u 4; set u 5 is a celsius, a fahrenheit value is refused); a value of S/v enters S unchanged; a value of S enters S/v only if its variant is v, and converting is a written cast through type convert. The bar binds tighter than the dot: list.temp/celsius is list.(temp/celsius). Members chain: mesure/some/celsius restricts the payload of some to its variant celsius. The payload of a sum keeps its own variant (set {mesure}m {/some}$t gives mesure/some/celsius, $m(some) gives the temp/celsius), which lifts the former nested-sum limit; labels chain too ({/some/celsius}5), and type get, type canonic, type parse, is, type include and type eq follow the chain. A literal is a variant with a single value, as {string(($ eq "none"))}none would be: type get gives opt(int)/none, type variant gives none, and a literal that is not a name is quoted (binop/"+"). A variant type can be named (type def hot temp/celsius). Inside a structure, type canonic writes a chain of labels ({list.mesure}{{{/some/celsius}1.0} none}). On the left of is, a text that is a type and no variable ([type get $r] is T) is an error, not a false. The value of a sum is unchanged: its payload alone; the variant chain is metadata.
Testing a result (v18c). The left operand of is is a variable, as on the left of = (TIP 759). A parenthesized assignment designates its variable, as an assignment is an lvalue in C++: if {(r = [openfile $fn]) is result/ok} { read $r } assigns then tests r; (r is result = …) is result/ok declares, assigns and tests. A tuple assignment designates several variables, so ((a,b) = $Z) is Complex tests the assigned value; (a,b) = Z is Complex, without the parentheses, would give the boolean of is to the tuple and is an error that shows both spellings (((a,b) = $Z) is T, Z is T = (a,b)).
Numbers (v17z). num is built in: the union of its representations, num/int and num/double, read the way expr reads a number. A typed integer enters double only when the double is exact (up to 2^53, or when it happens to be representable); otherwise it is an error, and rounding is asked for with type cast inexact $n (inexact is a nominal of double). type include follows ==: double includes int(s,32) but not int. A variant whose type is a product is built by its fields, like a named product: set {S/v}x {/f}a {/g}b, set {S/v}x a b, or by a path through the sum, set {S}x(v.(f,g)) a b (a path can be computed: set {S}x($v.($fields)) {*}$values). A list takes its elements one by one (set {list.int}L 1 2 3); a single argument is one element.
Typed procedures (v16p)
The argument list of proc may be a product type, and the annotation on the name gives the return type:
proc {pt}shift {{pt}p; {double}dx ?= 0; {double}dy ?= 0} { ... }
shift $a 1 1 ;# positional
shift $a {/dy}5 ;# positional, then labels
Each field is a local variable with its contract; ?= v and ?= [cmd] give defaults; a last {list.T}args field takes the remaining arguments; a {var.T}n field links n to the caller's variable (automatic upvar, current value checked). On a normal return the result is cast to the return type; when it is a sum, return {/v}$x selects the variant. A return {U}$x is only a local note and expires with the procedure. A field type may be written in place ({{double}x; {double}y}p), so a bare list is checked and becomes the field; a product field whose own fields all have defaults may be omitted. A valid Tcl list stays a classic argument list. A typed procedure runs as fast as a classic one doing the same checks by hand (exemples/bench_procs.tcl). type proc NAME gives the signature; info args and info default see the fields.
Unfolded results (v16r). proc {{*}T}name checks the result as a T and returns it unfolded as plain Tcl data: {*} a list of the values (like $P(*) and Tcl's {*}), {**} a dict of names and values (like Python's *args / **kwargs), deeply (nested products become nested lists or dicts; a sum gives its variant, named under {**}). type {{*}T}word and type {{**}T}word do the same for an explicit cast. A typed product is one list element; its unfolded form is the plain list an untyped caller expects.
Options and flags (v16q)
A field whose name starts with - is an option, given at the start of the call (until the first word that is not one, or --); a unique prefix is enough; the local variable drops the dash.
proc {list}sort {
{flag}-decreasing;
{int}-index ?= -1;
{"ascii", "dictionary", {string}command}-mode ?= ascii;
{list}l
} { ... }
sort -dec -index 1 -dictionary $L
{flag}-x is a flag (local 1 or 0). A sum makes exclusive options: each variant is an option (a literal takes no value, a typed variant takes one); the field's local gets the variant name, the variant's local its value. A product variant takes its plain fields after the option, and its -x fields are options that depend on it. {T}-o, with T a product, is a reusable group: T's fields are the options and o is a T value.
Links and computed defaults
A {var.T} field, positional or option, links the local to a variable of the caller (an automatic upvar). The variable's current value, if it exists, must be a T; the check happens before the body runs, and nothing is modified when it fails. A link may have a default name: {var.list}-into ?= log. A default may be computed: ?= [cmd] is evaluated at each call, after the positional arguments are bound, so it can read them. The usage message is generated from the signature, in the notation of the manual pages (?-n value?, ?-count varName?, ?--?).
proc bar {{var.int}a; {var.int}b} { incr a; incr b } ;# TIP 460's *a *b
proc {list.int}search {
{"exact", "glob", "regexp"}-mode ?= glob; ;# exclusive options
{flag}-nocase;
{int}-start ?= 0;
{int}-end ?= [expr {[llength $list] - 1}]; ;# computed at the call
{var.int}-count; ;# upvar: the number found
{list}list;
{string}pattern
} { ... }
Variadic fields (v16y)
A field {T}name... takes a variable number of words, anywhere in the signature; the fields after it are taken from the end. Without a default it takes at least one repetition; with ?=, zero or more. When T is a product, the repetition spreads over its fields: the words are taken by groups. The local is a list.T. Only one variadic field is allowed per signature, no field with a default may follow it, and it cannot be a var.T. A last plain args keeps its classic meaning.
proc each {{{list}vars; {list}values}args...; {string}body} { ... } ;# foreach
proc dict_set {{var.dict}d; {string}args...; {string}value} { ... } ;# dict set
proc {double}length {{pt}args...} { ... } ;# x1 y1 x2 y2 ...
The usage messages follow the manual pages: each vars values ?vars values ...? body, length x y ?x y ...?.
The reified call (v16z)
A signature is a product, so the bound arguments of a call are a value of it. type call, inside a procedure, returns the current call as a value of the signature's record: each field under its local's name (an option -mode gives mode), with its type; a variadic field is a list.T, a var.T link the variable's value; a field with no value at this call (an absent option without default) is left out. type call T builds a value of the named product T instead, each field taking the local of the same name, or its default. type proc NAME returns the record's text under the key record.
proc {Rec}move {{pt}p; {double}dx; {string}-note ?= "?"} {
set evt [type call Rec]
lappend ::log $evt
return $evt
}
The call becomes data: it can be logged, stored, or passed to another call. exemples/attentrel uses it for events whose actants are arguments, whose circumstances are options, and which can target one another.
Lambdas (v16z)
A lambda is a procedure without a name. The argument list of apply accepts the same signature, and the annotation on the lambda word is its return type, as the annotation on the name is for proc. Types are resolved in the lambda's namespace (its third element). The annotation may be written on a substitution: apply {T}$f ... gives a return type to a lambda kept in a variable. A type convert rule, being a lambda, can type its argument.
set sum [apply {double}{{{double}a; {double}b} {( $a + $b )}} 5 10] ;# 15
apply {int}$f 20.5 5 ;# return value {int}: expected integer but got "25.5"
type convert celsius kelvin {{{celsius}c} {expr {$c + 273.15}}}
The literal {T}{...} is rebuilt at each execution; the interpreter keeps one compiled procedure per {T}lambda text (at most 512), so the body is not recompiled at each call.
4. Paths
A typed value is read and written with array syntax; for a typed scalar variable, the index is a path. The language is the one proposed on the Tcl wiki page A better way to do indexation, parsed on the model of expr.
set {rect}R(A.x,A.y,B.x,B.y) 1 2 3 4
$R(A.x) ;# 1
set R(B) {5 6} ;# write a whole field
set R((A,B).x) 10 30 ;# multiple write
${R(A.x, B.y)} ;# read; spaces allowed
Operands. A bare word is a field, a dict key, a variant name or a list index (3, end, end-1): the container's type decides. 'key' is always a key ('end' is the key "end"). "tag" is literal text copied into the result.
Operators, from the weakest:
| operator | role | example |
|---|---|---|
, |
collection (a group) | A,B |
* (unary) |
unfolding: the group merges into its parent | *0:2,4 |
. |
nesting; distributes over a group | A.(x,y) = A.x,A.y |
: |
list range, with an optional step | 0:end-1, 0:end:2, ::-1 |
( ) |
grouping | (A,B).x |
Strided ranges. start:end:step, as in Python's slices, the end staying inclusive as everywhere in Tcl. Each part may be omitted: :end, start:, ::step (start 0, end end, step 1; with a negative step, start end and end 0). Bounds are clamped to the container, keeping the alignment, as in Python. A strided range is a selection: $L(0:end:2) reads every other element, $L(::-1) reads the list reversed. Writing gives one value per selected element, or one value for all (set L(1::2) 0); the length never changes. On a bitarray, $b(0:6:2) gathers the bits 0, 2, 4, 6 into a bitarray(4) of the same bit order; set b([($i*$i)]::$i) 1 sets every selected bit (0 or 1 for all, a list of bits one by one, or a typed bitarray of the right width as a pattern). Python's syntax was chosen because it is known, and because : is already the range operator of paths, leaving the arithmetic operators free for later extensions. A compact list or a large bitarray held only by its variable is written in place: the sieve of Eratosthenes over a million bits takes about 5 ms with one strided write per prime.
Windows. (s0,s1,...):end:step gives one column per start, all advancing by the same step: the end, if given, bounds the first start, and only complete windows are kept (no column leaves the list). On a flat polyline x1 y1 x2 y2 ..., $pl((0,1)::2) reads the x and y columns and $pl((0,1,2,3)::2) reads, for each vertex i, x[i], y[i], x[i+1], y[i+1] as four columns, which type map {x0 y0 x1 y1} ... takes as they are; set out((0,1)::2) $X $Y interleaves two columns back. The starts are simple indices (an integer, end-k, or a substituted value). A window of a single round reads like a range of one element. A fully substituted index stays a single name, as for any path: $L($s) with s = 1:3 looks for the element 1:3, so that a value never brings path syntax. Strided ranges and window columns of a typed list of scalars are views, for compact lists and for lists of objects alike: for a list of objects the view holds the base through a copy that shares its storage (as lrange does in Tcl 9), so neither the range nor its release touch the elements. Bulk commands such as type map read a view in its base; llength and lindex read it without unfolding it; other commands see an ordinary list, built once on demand. Writing typed columns of the element type into a list of numbers (or of the num union) held only by its variable is done in place, without checking each element again.
A multiple read returns lists nested like the groups: $R((A,B).(x,y)) gives {1 2} {3 4}; $L(0:2,4) gives {10 20 30} 50; $L(*0:2,4) gives 10 20 30 50.
Per container. Product: $a(name), $R(A.(x,y)); sum: $v(i) reads the current variant; list: $L(2), $L(1:3), $L(0,2); dict: $D(a), $D('end'); bitarray: $b(3), $b(1:4), $b(0:end:2). Writes go through the variable's contract and are revalidated. Reading then writing back the same path always works: set R(c) [set R(c)].
A path substitutes nothing. Tcl substitutes $x, [cmd] and [(expr)] in $R(...) and in bare words; each substituted value is one leaf, never parsed again as a path. In braces and in ${...}, $ and [ are errors. Data is therefore never executed by the path parser.
set k file.txt ; $D($k) ;# the key "file.txt", not D.file.txt
set idx {0 2} ; $L(*$idx) ;# * unfolds a list value
set p {[exec ls]} ; $L($p) ;# nothing runs: bad index "[exec ls]"
A computed path is read by naming the variable with it: set ref R($path); set $ref.
Spaces. Spaces are allowed in $R(...), ${R(...)} and in an annotated word {T}R(...). In a bare word (set R(A.x, A.y) ...) Tcl splits at spaces as it always has.
Arrays are unchanged. For an array, or for an index that is not a well-formed path, the Tcl 9.0 rule applies exactly. In particular a parenthesized index is not an expression: set A((1+1)) 3 keeps the key (1+1); a computed index is written A([(1+1)]) (TIP 759).
Grammar (EBNF). Precedence, from the weakest: ,, then *, then ., then :, then ( ).
path = spread , { "," , spread } ; (* collection: a group *)
spread = [ "*" ] , nest ; (* unfolding: the group merges into its parent *)
nest = range , [ "." , nest ] ; (* nesting; distributes: A.(x,y) = A.x,A.y *)
range = [ step ] , ":" , [ step ] , [ ":" , [ step ] ] (* list range: 0:end-1, 0:end:2, ::2 *)
| step ;
step = word (* field, key, variant or index: the type decides *)
| "'" , key , "'" (* always a key: 'end' *)
| '"' , label , '"' (* a label, copied as is into the result *)
| "(" , path , ")" ;
index = integer | "end" , [ "-" , integer ] ;
read = "$" , varname , "(" , path , ")"
| "${" , varname , "(" , path , ")" , "}" ;
write = "set " , varname , "(" , path , ")" , value , { value } ;
construct = "set {" , type , "}" , varname , "(" , path , ")" , value , { value } ;
5. C level
No new stub functions. The public C API (tcl.decls) is unchanged. The additions visible from C are two token types and one object type.
Parser tokens (tcl.h):
| token | value | produced by | meaning |
|---|---|---|---|
TCL_TOKEN_ANNOT |
2048 | Tcl_ParseCommand, ParseTokens |
the annotation of a word {text}rest; the tokens of rest follow |
TCL_TOKEN_INDEX |
1024 | Tcl_ParseVarName, only when the extended index syntax is used |
wraps the components of an index $name(...); an index valid in Tcl 9.0 keeps exactly its Tcl 9.0 tokens |
Tools that walk token arrays (testparser, static checkers) must accept these two types.
The annotated object. An annotated value is a Tcl_Obj of type annotated. Its string is the string of its content, so any code that ignores annotations sees the content.
Tcl_Obj (typePtr = &annotatedObjType)
bytes/length the content's string, computed on demand
twoPtrValue.ptr1 the content V: an ordinary, shared Tcl_Obj
twoPtrValue.ptr2 the annotation, one of:
- a resolved type reference
- the raw text of an unresolved annotation
- "" (the empty annotation {})
- a state {T, N}: resolved type T (or NULL) and notes N
The object is immutable and shared: Tcl_DuplicateObj shares the state, and annotating, unstacking or removing a note makes a new object. setFromAnyProc refuses: an annotated value is born only from the parser or a typed assignment (TCL VALUE ANNOTATED). The type is a Tcl 9 abstract list (TCL_OBJTYPE_V2), so lindex, llength, lrange, foreach and lset return typed elements of a list.T. Core conversions (Tcl_GetIntFromObj, dict and string access) read the content and never convert an annotated value in place.
Compilation.
- A word whose rest is literal compiles to a raw note (
::tcl::annotraw); otherwise to::tcl::annotate text value. - A
setwith an annotated name, andTcl_SetObjCmdwith an annotated first argument, call the constructor. - New instruction
INST_INDEX_CONCATbuilds a path index that remembers which spans were substituted, so a substituted value stays one leaf.TclSubstTokensproduces the same object when not compiled. - New instruction
INST_TYPE_FORGETforgets a loop variable's type before assignment (compileddict for,dict map). INST_STORE_SCALARtakes the slow path only for an annotated value; writes to a typed variable go through its contract (tclVar.c).
Specialised operations (tclTypesOps.h). A type is known when it is defined, so the hot operations need not rediscover it from each value. Each type can carry a table of specialised operations, chosen once from a registry and recomputed when a library is loaded:
typedef struct TclTypeOps {
int version; /* TCL_TYPE_OPS_VERSION (1) */
const char *name;
Tcl_Obj *(*index)(const TclType *tp, Tcl_Obj *content, Tcl_Size i);
Tcl_Obj *(*elemField)(const TclType *tp, Tcl_Obj *content, Tcl_Size i,
Tcl_Size f);
int (*indexDouble)(const TclType *tp, Tcl_Obj *content, Tcl_Size i,
double *outPtr);
} TclTypeOps;
typedef struct TclTypeSpec {
int version;
const char *name;
int priority; /* highest wins; built-in: 0 */
int (*match)(Tcl_Interp *interp, const TclType *tp, void *clientData);
const TclTypeOps *ops;
void *clientData;
} TclTypeSpec;
A specialisation may only go faster: an absent operation, or one that returns NULL or 0, leaves the general path, and the result must be the same value, string and type. The built-in library specialises lists of plain numbers (list-scalar) and lists of products (list-product, field read from the cells of a compact list). The bytecode uses it for $P($i.field): indexConcat followed by loadArray on a typed variable reads the field through elemField without building the index. type ops TYPE names the active specialisation (empty if none). The environment variable TCL_TYPE_OPS selects off (general path only) or check (both paths, compared; a difference is reported on stderr and the general result is used).
This TIP opens the door with a simplified external interface: an extension takes Tcl_GetAssocData(interp, "tclTypesOps", NULL), a TclTypesOpsApi table (version, registerOps, read-only accessors to an opaque type: kind, name, element, fields, and wrap to make a typed value), and registers its TclTypeSpec. No stub function is added; a full interface (more operations, stubs) is left to a later TIP. The example exemples/ops/produits_ordinaires.c specialises field reads in ordinary (non compact) lists of products.
Error codes. Type errors use TCL TYPE ... (INT, SUM, DICT, LIST, FIELD, PATH, MISMATCH, CONTRADICT, UNKNOWN, LOCALANNOT, STALE, DEREF) and TCL PARSE TYPE BADCHAR. Path parsing errors use TCL PARSE INDEX ...; wrong argument counts use TCL WRONGARGS.
Compatibility
No valid script changes meaning. Both syntaxes take over forms that Tcl 9.0 rejects or reads the same way:
{x}wordis a syntax error in Tcl 9.0 (extra characters after close-brace), except{*}, which keeps its meaning.- A value never begins with
] } ) = < > ! & | ^ ? , ; ~ %: after a close brace, these characters keep the Tcl 9.0 error. A misplaced brace (proc p {} {set w foo}]) is still reported, instead of silently defining a procedure whose body is]. - With this rule,
make testfails only where an unmodified Tcl 9.0 fails in the same environment (the network tests ofhttpProxy). The core tests that assumed{x}wordis an error are updated: those that check the error message write{x}=word, which keeps it. - An extended
$name(...)index falls back exactly to the Tcl 9.0 rule as soon as it is not a well-formed path, and an array is never read as a path.info completegives the same answers. Bare words are not affected:puts a(b c)is still two words. - Commands and values that carry no annotation behave as in Tcl 9.0; an annotated value passed to an unaware command is seen as its content.
Checks on the reference implementation.
- Tcl test files
parse,parseExpr,parseOld,subst(including 257testparsertests),var,compile,set,upvar,basic,execute,incr,append,lset,dict,info: results identical to the base. The one known failure,info-20.2, comes from the extra math functionspopcountandbitlenand is present in the base too. - Equivalence with a stock Tcl 9.0 on 18,000 generated cases (
$z(...),"<$z(...)>",set z(...),info complete): no valid result changed. - AddressSanitizer clean; memory stable over 1,000,000 constructions.
Dependencies. The expr assignments x = v and (a,b) = $L, and the [(expr)] substitution, come from TIP 759. This TIP adds v is T and the declaring assignment x is T = v. Without TIP 759, typed variables are declared with set only.
Performance. The cost for unannotated code is one test on the object type in the hot paths (INST_STORE_SCALAR, conversions). It has not yet been measured against stock Tcl 9.0; this is an open issue.
Reference Implementation
A prototype on core-9-0-branch with the TIP 759 branch, by Florent Merlet with Claude. It adds eight C files and their headers (about 30,000 lines) and one Tcl script, and hooks in 23 core files (about 2,600 lines added). The Tcl test suite gives the same results as an unmodified Tcl 9.0; the prototype's own tests are in tests_tclsh/.
| file | content |
|---|---|
tclAnnotObj.c |
the annotated object, the {T, N} state, resolution, note |
tclTypes.c |
typology, the type command, validation, widening, casts |
tclTypeParse.c |
parser and compiler of type expressions |
tclTypeGeneric.c |
parameterized types, instances, phantom parameters |
tclTypedVar.c |
typed variables and constructors |
tclTypePath.c |
path language: read, write, construction, path index object |
tclVarRef.c |
var links, including links to variables that are gone |
tclTypeDebug.tcl |
type debug: the stop hook, conditions, the Tk console, the proto-type report (built into tclTypeDebug.h) |
The main core hooks are in tclParse.c (tokens), tclCompile.c and tclCompCmdsSZ.c (compilation), tclExecute.c (instructions), tclVar.c (the contract), tclProc.c (typed arguments, typed lambdas) and tclCompExpr.c (is).
Examples. Besides small scripts, exemples/ holds complete demonstrations: signatures (signatures against TIPs 288, 457, 460, 479, 480; lambdas.tcl), bulletin (a buggy procedure, debugged, typed, then moved to C, in four steps), mise_au_point (type debug and the console), cproc (procedures with a C body, compiled at the first call), ffi (calling a shared library function from its typed signature, through a C stub, without libffi), tcllib_geometry (tcllib's math::geometry in Tcl, typed Tcl and C, its 210 tests passing in all three).
Rejected Alternatives
| alternative | why not |
|---|---|
| a new quoting rule for annotations | {x}word takes over a syntax error and needs none |
glued stacking {a}{b}$x |
ambiguous with {int}{300} |
| resolving every annotation where it is written | only the receiving command knows whether a word is a value or a variable name (lappend {list}M x, set {rect}Q(A, $k) ...); {T}$x, a variable alone, is the exception: it is resolved where it is written |
a field or variant name read in the constructor's context before the global types ({age}12) |
ambiguous with a global type of the same name ({elf}$v failed when elf was also a type); a label {/age} cannot collide |
the bare name/value form set {pt}a name Jean age 12 |
read two ways when n arguments match n fields; names are now written in the source |
| mixing field labels and positions | a disguised positional form |
an annotation that converts ({m}$a turning 1500 mm into 1.5) |
the same text did two things depending on metadata carried by the value (a conversion on a typed value, a plain note on a bare one); since v18h an annotation gives a type or fails, and type cast converts |
| an unknown name in a constructor kept as a note | its meaning depended on what had been declared when the command ran ({m}$c a note, then a type after type def m), and a typo went unnoticed; notes are written by note set |
| commands told the origin of a word (variable, command, literal) | set y $x, set y [set x] and set y 5 would no longer be interchangeable, and calls from C or {*} have no source; the origin stays a compiler's information |
| an untyped parameter resolving, or relaying, the caller's annotation | resolved, the procedure never sees the option (note get empty); relayed, every local set x $arg would interpret it; the relay is written: [annotated $v] |
a path that substitutes $ and [ |
data would be executed by the path parser |
(expr) as an index |
breaks the braces rule, clashes with path grouping, and changes Tcl 9.0 keys such as (1+1) |
path + field labels (set {rect}R(A) {/y}2 {/x}1) |
no proven need yet |
Open Issues
- Contracts in the reference implementation. The prototype still gives an untyped variable the contract of a typed value it receives (
set e [lindex $L 1]; set e hellofails). Aligning it with section 3 (no adoption, declaration in any writing command) is tested in a separate patch, with no regression in the Tcl test suite; a variable that does not exist yet does not receive a contract this way. ;and,mixed without braces are accepted and produce an anonymous field; the grammar says they should be refused.- Reading an inactive variant of a sum gives
unknown way to cast the value from S to stringinstead of naming the variant. - Unions (
|) and sums (,) could become one construction,|asserting disjointness. - Notes as trees (
a.(b.(c,d),e)), like paths. set $rwhere$ris an annotated value is taken as a constructor.- A general "no value" (
opt(T)exists only for binary links); notes per list element. - Cost of the hooks for unannotated code, to measure against stock Tcl.
- Binary representations (
type binary,chan binary, C codecs): separate TIP. - Typed signatures for TclOO methods; commands with two calling forms (
switch), which would need a union of signatures.
Copyright
This document has been placed in the public domain.