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.
Notes. An annotation that no constructor has resolved is a note. It follows the value through copies, arguments, return values and list elements. Notes stack, from the oldest to the most recent.
set x {mm}5
set y {px}$x
note get $y ;# mm.px
Types. A variable constructor resolves annotations against the types the interpreter knows (section 2). The constructors are set {T}v ... and set v {T}$x, binding of proc arguments, lassign, foreach, lmap, dict for and dict map for their lists and dicts, lappend, lset, linsert, lreplace on a typed variable for the elements they receive, in expr the assignments x = v and x is T = v, and the explicit cast type {T}word. Where an annotation acts. 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 (set {int}$name 5 declares the variable named by $name). When that command is done, whatever is still pending expires: it becomes a note, metadata that no constructor resolves any more, even if the value was returned (concat, return), stored in a list or a variable, or if the type is defined later. So the error of a cast is always raised inside the command that holds the word, and an enclosing catch catches it: catch {concat {int}$s} r returns 0 (concat checks nothing), catch {type {int}$s} r returns 1.
Two stacks and unstacking. An annotated value carries at most one resolved type and a stack of pending notes; they are displayed as [email protected]. A constructor:
- takes the most recent note and tries to resolve it;
- continues while notes resolve; the first that does not stops the process and stays on the stack;
- checks that the unstacked types are consistent, else
contradictory annotations A and B; - casts the value to the most recent type;
- lets the variable's contract make the final check.
A note set before its type def is therefore resolved by the next constructor that sees it.
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 the notes, oldest first, joined by "."
note has VALUE NAME 1 if NAME is one of the notes, else 0
note delete VALUE ?NAME? the value without the note NAME, or without any note
note delete returns a new value; Tcl values stay immutable.
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: 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 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 a constructor's resolution, without a variable
type {T}WORD the same cast, written as an annotation (v16m)
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 cast, 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 variant VALUE the variant of a value of a sum or a union (v16w)
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.
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.
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. set v {T}$x and type cast T $x try, 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.
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 |
cast {T}$x in a constructor |
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). The form of the declaration says whether the value carries its variant. A sum (,) writes it: its value is variant payload (i 5, fahrenheit 50.0), or the literal alone; every typed variant has a name, which is its tag, and nothing is ever guessed (a bare value is refused). The value is thus enough by itself, through a string, a file or another interpreter, and two variants of the same form (units, {int}a, {int}b) are no problem; i 5 and s 5 are two different strings. A union (|) is the payload alone; its alternatives must be disjoint, which is checked when it is defined (type is {disjoint?}S gives the overlapping pairs), so the value always shows which one it is. A sum is built with a label (set {S}v {i:}5), in plain (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. $v(i) reads the payload (expr {$v(i) * 2}), $f(w) reads a part of the current payload, type variant $v gives the variant. Any value reads as a string (its text); a union reads as its alternative's type; a sum never does, so what it says (a unit, a kind) is not lost silently. opt(T) is {T}some, "none". 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 ...?.
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 | 0:end-1 |
( ) |
grouping | (A,B).x |
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). 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 ] ; (* list range: 0:end-1 *)
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).
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 |
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. - Variants of the same shape: without a tag, the first is taken silently.
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.
