Appearance
TypeScript
Tolean translates pure TypeScript functions into plain Lean functions. This page describes the parser, the translator, the subset it accepts, how it models JS numbers, and what is proved and what is trusted. The README describes the parts that all languages share.
This graph shows the verification chain for TypeScript. It marks which links are proved, tested against a reference, or trusted.
Project proof obligations
The project chain manifest accepts an optional obligations list. Each entry has spec, proof and module fields. spec names a Lean definition of a proposition. proof names a theorem whose type is exactly that definition, and module names the module to import.
Build the proof module first, then run lake env tolean chain check with the path to the project chain manifest. The checker follows the theorem's dependencies and accepts only propext, Classical.choice and Quot.sound. Unlike a claim, an obligation cannot supply its own axiom allowlist. Proofs that depend on sorryAx fail this check.
For additional comparator shapes on bigint arrays, the translator emits a statement such as Out.«sort obligation at 2:10». The statement requires Eval.Consistent for the translated comparator. Put its proof in a separate module that imports the generated output, not the certificate.
In the project chain manifest, use the raw name without Lean's quotation marks:
json
{
"spec": "Out.sort obligation at 2:10",
"proof": "ProjectProof.squares",
"module": "Proof"
}Set "proofManifest": "tolean.chain.json" in tolean.json to use those proofs when project units request certificates. For an individual file, use tolean certify Input.ts Out Out OutCert.lean OutCert --proof-manifest tolean.chain.json. The certificate imports the proof module and passes its theorem to the sort link proof. The usual function certificate then follows through program_sound.
The generator automatically attempts a proof for literal-zero comparators. Other new shapes require a matching manifest entry. Generated statements, not the project's supplied proof list, determine which obligations the chain checker requires. The checker rejects proofs that use sorryAx, including indirect dependencies.
New comparator obligations currently require bigint elements and cannot capture generic types. Known key comparisons retain their existing support. @decreases obligations remain refused. See the decision.
The translator
Parsing
tolean/TypeScript/Syntax/ puts a span on every node. It reads:
- Declarations: functions, with optional parameters such as
x?: T, interfaces and type aliases, each of which may have type parameters such as<A, B>, enums whose members are strings, error classes, andconstandlet. Each of them may be exported, byexportbefore it or by an export list such asexport { a, type B }. An error class isclass Name extends Error { constructor(params) { super(message); } }, withreadonlyallowed before a parameter, or the same with no constructor. The parser refuses every other class: one that does not extendError, a field, a method, or any other statement in the constructor.
A function return annotation may be a predicate, as in shape is Circle. The parser preserves its parameter and target type, including on local declarations and local arrows. The interpreter ignores the annotation, as Node does after type stripping: it evaluates the body rather than trusting the claimed type. Translation accepts checked tag guards as described below.
- Statements:
constandletdeclarations, array destructuring such asconst [a, , b, ...rest] = xs, flat object destructuring such asconst { a, b: second } = value, expression statements,return,throw,ifandelse,for … ofwith a name or an array pattern beforeof, the countedfor,while,switch,trywith a boundcatch, blocks,break,continueand the empty statement. A countedfor, such asfor (let i = 0; i < n; i++), starts with aconstorletdeclaration or with nothing. The value of athrowmust start on the same line, because ECMA-262 allows no line break afterthrow. The translator accepts onlythrow new Error(message). Abreakat the top of aswitchclause ends theswitch, so it may stand outside a loop. The parser refuses acasetest that uses<or<<, because a:does not end its search for a>after one, and aswitchwith twodefaultclauses. - Local functions: a function declaration in a block of another function, as at the top of the module but without
export. Its body is a function of its own, so abreakor acontinuein it cannot leave a loop around the declaration. The parser refuses a function declaration as the body of anifor a loop without a block around it, as JavaScript does, and one in a block outside every function. Aconstin a block of a function whose value is an arrow function with its parameters in parentheses and a body in braces, such asconst g = (x: T): R => { … }, is a local function too. The parser gives it the same tree asfunction g(x: T): R { … }, because the model binds both where they stand. JavaScript hoists the declaration to the top of its block, but Tolean refuses a call before it, so the two mean the same wherever Tolean accepts them. The translator accepts some local functions; see The subset. - Expressions: names; number, bigint, string, boolean and
nullliterals; array and object literals, with shorthand andkey: valueproperties; parentheses, member access, indexing and calls; the unary operators!,-,+,~,typeofandvoid;++and--before or after; the binary operators, including??,**,inandinstanceof; the conditional operator; assignment, with every compound operator; arrow functions whose body is an expression, such asx => x + 1and(a: number, b) => a * b;e as constande satisfies T, which bind as<does, as they do intsc;new C<A, B>(args), whereCis a name; and a spread,...e, as an element of an array literal or an argument of a call or anew, such as[...xs, x]andf(...xs). - Types: keyword types such as
number,null, literal types, named types with type arguments, arrays, tuples such as[A, B]andreadonly [A, B], unions, parentheses and object types such as{ readonly n: bigint }. Object fields may use semicolons, commas or line breaks as separators. Fields may be optional, and an object type may be empty or nested.
The translator accepts less than the parser reads; see The TypeScript subset. Sometimes tsc and JavaScript read the same tokens in two different ways. When that happens, the parser refuses the code instead of choosing one reading. There are three such cases:
f < A, B > (x).tscreads type arguments, but JavaScript reads two comparisons. The parser acceptsa < b && c > dandx < n && n > 0, because a top-level expression operator before the closing>can rule out a list of types. The scan stops at&&,||,??,===,!==,==,!=,+,*,/,%and**. It does not stop at these tokens inside brackets, where a type can contain a computed property expression. It does not stop at-,&,|,.,!or?, which can occur in types. Nor does it stop at>>,>=,<<or<=, because TypeScript rescans>when it closes type arguments. It keeps refusing tokens that it cannot rule out this way. The refusal off(a < b, c > d)is a known gap tracked by #208, not an intended restriction. TypeScript 6.0.3 reads two comparisons there, so the parser should accept it without extra parentheses. The remaining work is a speculative type-list parse followed by TypeScript's follow-token test. Its round-trip proof needs a stronger relation between source tokens and printed tokens. The plan tracks that work.(a)followed by{.tscreads an arrow function that is missing its=>, but JavaScript reads(a); {.(a), then a line break, then=>.tscreads an arrow function, but ECMA-262 allows no line break before=>, so JavaScript refuses the code.
The parser refuses default parameter values. Remove the default and pass the value explicitly at each call.
Except as a local function in a const, the parser refuses an arrow function with a return type and one whose body is in braces. It also refuses one with an optional parameter: (a?: T) => a starts like the conditional (a ? …. The translator accepts an arrow function only as the callback of an array method, such as xs.map(x => x + 1n), and as a local function.
The parser reads new only before a name and its arguments in parentheses, such as new Map<string, bigint>(). It refuses new a.b(), new.target and new C without arguments. It also refuses type arguments that start on the line after the name, because it reads C<A> as a type, and a type ends at a line break before <. The translator accepts only new Map() and new Set().
A spread is not an expression on its own, so the parser refuses one anywhere else, such as (...xs). It also refuses a hole in an array literal, such as [a, , b]. The translator accepts a spread in an array literal and at the start of an object literal, and refuses one in a call for now.
The parser reads array destructuring in a const or let statement, such as const [a, , b, ...rest]: T = xs, and in the head of a for … of loop, such as for (const [k, v] of m). Each place of the pattern is a name or an empty place, which is a hole, and a rest element may come last. A statement needs a value after =, and it declares one pattern. The parser refuses destructuring after export, in the first part of a counted for and before the in of a for … in. It also refuses nested patterns and default values, and a pattern that is empty or that ends with a ,, such as [a, ] or [a, , ], although JavaScript allows both. So the last place is always a name or the rest element, and the printed pattern reads back as the same one.
Local declarations also accept flat object patterns, such as const { a, b: second } = value. Each property must have an identifier key, and each binding must be a name. A pattern may select only some fields or read the same field into several names. A trailing comma is allowed. The source must have an interface or an inline object type. The output evaluates it once, including when it is a function call, then binds the selected fields in the surrounding scope. Extracted mutable collections remain aliases, so the existing restrictions on mutation still apply. Interface field names and object-pattern bindings that are Lean keywords are quoted in the output. For example, a field or a binding named end becomes «end». Other declarations retain their existing name restrictions. Literal tag fields are not stored in the Lean structure and cannot be bound in an object pattern. They retain the restriction to tests of their union.
Object patterns do not support nesting, defaults, rest elements or computed keys. Empty patterns, exported patterns and patterns in loop heads are also refused. A source that reads one of the pattern's own binding names is refused because that binding is not initialized yet. Destructured parameters remain refused: name the parameter and read its fields in the body instead.
In the declaration at the start of a counted for, the parser refuses an in operator unless parentheses, braces, the arguments of a call or an index hold it. ECMA-262 reads such an in as the start of a for … in loop. It allows one inside [ … ], but tsc does not, so the parser refuses that too.
The interpreter runs a counted for of one shape: for (let i = k; i < b; i++), where the update may also be ++i or i += 1. The start k must be an integer literal, which may follow a -, but not -0. The body must not assign i, and it must not change anything that b reads, because JS reads b again before each run of the body. The interpreter runs the body as each value of i comes, so a body that returns early ends the loop at once. It gives no value for any other counted for, and none for a loop where i would pass Number.MAX_SAFE_INTEGER. The translator accepts the same shape, as the table of statements below shows.
as const and satisfies T have two more lookalikes, and the parser refuses both:
<,<<,?,|,&,[,(or.right after the type.tscmay read the token as a part of the type, as it readsx as const < ywith type arguments. Type stripping leaves blanks in place of the type, so after a line break JavaScript may read the next line as a part of the operand, as inx as constand then[0]on the next line.asorsatisfiesright after a name that starts a declaration intsc, such astypeordeclare. At the start of a statement,tscreadstype as constas a type alias.
The parser refuses every other type assertion, such as x as T, <T>x and the non-null assertion x!, because TypeScript does not check them.
The parser also refuses code that Tolean cannot represent exactly. Examples are lone surrogates, legacy octal literals, tagged templates and non-ASCII names.
The lexer reads a template literal as + on strings: `a${e}b` gives the tokens of ("a" + (e) + "b"), and `a` gives the string "a". When one operand of + is a string, + converts the other with ToString, as a template literal converts each substitution (ECMA-262 §13.2.8.6 and §13.15.3). The two can differ only on an object, whose ToPrimitive calls valueOf first, and the subset has + only on primitives. A line break in the text reads as \n, as the spec gives it. A template literal right after a name, ), ], }, > or ! could be a tagged template, such as f`a` , which calls f with the pieces. The lexer would read that as a call of f, so it refuses a template literal in those places. The printer never writes a template literal, so the parser's round trip covers the tokens that the lexer makes, and the lexer's proofs show that its template branches never run on printed text.
tests/typescript/check.ts checks the parser against tsc. To do this, tests/typescript/tscAst.ts prints the tree from tsc in the same S-expression form, and it refuses the node kinds that the Lean parser does not read. The check covers three kinds of input:
- For
corpus/parse/accept/*.ts, both parsers must accept the file, and the two trees must be equal, spans included. - For
corpus/parse/reject/*.ts, the Lean parser must refuse the file. The first line of each file gives the line, column and reason to expect. - Each run also makes 500 random programs, with line breaks and comments between tokens. For each one, the trees must be equal, or both parsers must refuse it, or the Lean parser must refuse one of the lookalikes above. The run prints its seed, so you can replay a failure.
Translation
tolean/TypeScript/Translate.lean translates the syntax tree. It does not use tsc, so it types the subset itself. It gives every expression the type that tsc would give it, with the same narrowing on null, and it refuses anything it cannot type exactly. That type checker is part of what we trust. The translator does not write text. It builds the Tolean IR, the Tolean intermediate representation: the Lean code that it writes, as Lean data, with types, expressions, bodies and declarations. tolean/IR.lean defines the part of the IR that every language shares and prints it as Lean text. tolean/TypeScript/IR.lean adds what only TypeScript needs: JavaScript numbers and null. So a theorem can state what the translator writes, which a proof of the translator needs. The decision record on the IR explains why it is a type of Tolean's own rather than Lean's Expr.
tolean/TypeScript/Proof/ proves the translator for every program that it accepts. tolean/TypeScript/IR/Eval.lean gives the IR a meaning: it evaluates the IR over the interpreter's values. The theorem program_sound in Proof/Module.lean states that when the translator accepts every file of a program, a function of the IR gives a value only when the interpreter gives the same value for the same call. program_sound_call states the same for a call that throws: a function of the IR throws a value only when the interpreter throws the same value. program_sound already covers generic functions because it relates the IR evaluator to the interpreter without inspecting Lean type parameters. A generic certificate adds codec laws only for the link to the printed Lean function. translate_sound is the case of one file. It holds for every input, every model of numbers and every amount of fuel. The theorem does not assume that the types the translator gives are right. It is about the IR, so a file without a certificate still trusts the printer link: the printed Lean computes what the evaluator gives for the IR, and the evaluator gives a value where the printed Lean does. The corpus tests the printer, and a certificate proves the link for its file.
tolean/TypeScript/Spec/Coverage.lean lists every theorem about the subset under the section of ECMA-262 that it is about, in the order of the spec, so it shows which sections have theorems of their own. The theorems about no section, such as those about the translator's monad or the parser, are in its extras. The build fails when a theorem is in no list. Spec/Coverage/ holds a check for each rule that the interpreter or the translator once broke, with one file for each chapter and one for the extras. A theorem states the rule for every input, and a #guard checks one input. Every heading about the spec has the form §<number> <title> {#<anchor>}, with the anchor of the section in the spec, so a script can read the headings and compare them.
tests/typescript/checkTranslate.ts checks the translator. No second translator checks its meaning, so these checks show that the output does not change and still compiles; certificates prove more for the files they cover.
corpus/translate/accept/*.ts: the translation must equal the committed.leanfile beside it, and Lean must compile it. Run the check with--updateto rewrite those files when a change to the output is meant, and review the diff. When the TypeScript translator innpm/that usedtscwas removed, every one of these files equalled its output.corpus/translate/reject/*.ts: the translator must refuse the file. A line// expect: <line>:<col> <part of the message>says where and why. These files state in executable form what the subset refuses.- In both, a line
// target: ES20xxtranslates for that edition. - Fuzz: 200 random typed programs per run, from a printed seed. When the translator accepts one, Lean must compile the output, and a second translation must give the same text.
Checked type guards
A function with a predicate annotation becomes a Bool function only when its body computes exactly the tag test for the claimed type:
ts
function isCircle(shape: Shape): shape is Circle {
return shape.kind === "circle";
}The parameter must be required and must be the function's only parameter. The body must return the strict comparison directly, or use that comparison in an if whose branches return true and false. The comparison may use === or !==, with the literal on either side. A named union of primitives can use typeof value === "string" instead. The translator checks that the true branch is exactly the annotated type. A constant result, a test of another parameter, and a test of only part of a member are refused.
In if (isCircle(shape)), where the argument is an identifier, both branches narrow as they do for an inline tag test. This also works for local guards and local arrows declared before the call. A chain of guard tests can separate three or more members. Calls in other expression positions remain ordinary boolean calls and do not narrow. Imported guards likewise remain boolean calls; their interfaces do not carry a body for the caller to check.
The interpreter and translator lower these tests to the existing tag branches. They retain each call in a fresh binding so that argument checking and call fuel remain in the model. In a chain of tag tests, these calls run before the match; checked guards only read their parameter's tag. The IR and its evaluator use their existing boolean functions, calls and tag matches. program_sound covers this lowering through the same statement proofs as inline tests. The native and WebAssembly translators use the same source. Destructuring is not yet accepted inside a try body.
Guard normalization also visits both blocks of a try statement. Inline typeof and null tests narrow in either block, and a checked guard call can narrow in the catch handler. The protected body still rejects calls.
Regular expressions
The translator accepts test on flagless regular expressions with a string argument. It also accepts the restricted first-match replacement below. It still refuses match with a regex argument. The parser accepts flagless literals that start with a non-capturing group, such as /(?:a|ab)/. Wrap a pattern in (?:...), or prefix it with (?:), to use that spelling. The unambiguous prefix keeps division distinct from a literal without weakening the parser's round-trip proof. Plain /a/ literals remain refused. Before a regex statement, end the preceding simple statement with a semicolon; do not rely on a line break to separate them.
The pattern parser in Syntax/RegExp.lean and matcher in Spec/RegExp.lean are tested against Node using generated patterns and UTF-16 inputs. Parser corpus tests also compare literal syntax with tsc and check source round trips. Translation corpus tests cover test, and interpreter tests compare its results with Node, including repeated calls and UTF-16 surrogate inputs.
The model uses ordered backtracking without flags. It includes character classes, alternatives, captures, greedy repetition and the input anchors. It proves termination with the remaining minimum and input length, rather than interpreting fuel exhaustion as failure to match. See the decision record for the intended source subset and the restrictions on future match support.
s.replace(/(?:pattern)/, "replacement") replaces the first match. The pattern may contain captures. The replacement must be a string literal without dollar signs, because substitution tokens and replacement callbacks are not modeled. Dynamic replacements and regex aliases in this call are refused. Flags, named groups and the other pattern restrictions above still apply. Empty matches insert the replacement at the first matching position.
Certificates
A certificate proves one file's translation, so that file no longer trusts the translator. tolean/TypeScript/Spec/Eval.lean is an interpreter for the subset: it runs the syntax tree that the parser returns, following ECMA-262. For each function, tolean certify writes a theorem that the interpreter and the translated Lean give the same result for every input:
lean
theorem raise_cert (g : _) (step : _) :
run program "raise" [(encGauge g), (Val.int step)] =
some (encGauge (sensor.Raise.raise g step)) := by
certify_tac [program, encGauge, sensor.Raise.raise]sh
tolean certify sensor/raise.ts sensor.Raise sensor.Raise sensor/RaiseCert.lean sensor.RaiseCert \
--manifest sensor/Raise.lean.chain.jsonCertificates are optional for now. tolean translate --certify writes the certificate next to the translation, as RaiseCert.lean beside Raise.lean, and records it in the manifest. Without --certify, translate writes only the translation. In a project file, "certify": true asks for the same.
The command does not need to be trusted. If it writes a wrong encoding or a wrong theorem, Lean refuses the file. The certificate also holds the characters of the source, and it proves that the parser gives its program for them: the kernel runs the parser on the characters and compares the trees. So a certified file trusts the parser and the interpreter, instead of the translator. With --manifest, the chain records this: the translator link becomes proved, and so does the parse.
Most functions of the subset can get a certificate. A generic function's theorem takes a Codec N T for each type parameter. A codec provides an encoding, a decoder, and proofs that decoding the encoding returns the input and that the encoding is neither null nor undefined. The last two conditions keep a type parameter's value distinct from the nullish value that may surround it. A generic interface gets an encoder, a decoder, and a codec constructor built from the codecs of its type parameters. A recursive interface remains refused by the certifier because its nested encoder and decoder need a reusable round-trip proof. A use of a generic interface is also refused when one of its type arguments is not a bare type parameter. The certifier has not yet specialized its field codecs for those arguments. A file with a function that calls itself has no certificate yet. Its recursive call depth depends on the argument, and the certifier has not proved that adding interpreter fuel preserves a successful result, so it cannot combine the per-call bounds. The translator accepts structural recursion only when Lean proves termination, and program_sound covers those definitions. Recursive tagged unions remain refused because the translator does not emit their member interfaces and union as one mutual type block. User-supplied @decreases measures, mutual recursion and while loops also remain refused because the translator has no checked termination obligation for them. A file with a function that can throw also has no certificate yet, because the certifier has no encoder for Except. A local function can get a certificate, including one that contains a loop or is called from a loop. This covers calls that return a value and calls that write back captured let variables. A call can do both when its final return names one of the captured variables that it changes. The loop invariant records the closure that each local call reads as well as the encoded data that the body uses. A number is a value of the abstract model JSNumber N in the interpreter, as it is in the translation, so each theorem holds for every N, real doubles among them, and assumes none of the number laws. A file that sorts is the exception. Its theorems take [SafeIntLaws N], because the order needs the signs of -1 and 1 as numbers. A function that directly returns a parameter sorted by number keys with the comparison shape gets a certificate too, in either direction. Sorting a copy, [...xs].sort(...), works as well. Its theorems also take [NumberOrderLaws N] and a hypothesis over the parameter, such as (f_sort_precondition : ∀ x ∈ xs, JSNumber.isNaN x.key = false). The key may be the number itself or a field of the element. This condition allows infinities and both signed zeros. For a.key - b.key or its reverse, the hypothesis is instead ∀ x ∈ xs, JSNumber.isFinite x.key = true, and the theorem also takes [SpecialValueLaws N]. The difference may overflow to infinity: the keys, not their differences, must be finite. The certificate proves consistency on that input list, not on every list. A function may directly return a call to such a function, with its own list parameter as the argument. Its theorems carry the same condition over that parameter. This works through a chain of calls, even when the argument changes name or position, and permits a spread copy of the parameter. For several keys, each number key has its own hypothesis. Number keys may mix with string and bigint keys, which need no input condition. A final difference key requires finite values even when earlier keys break the tie. The sorted list may also be a field of a parameter or a concatenation of spread copies of parameter lists, such as [...xs, ...ys]. Forwarding calls may pass these expressions too. The hypothesis quantifies over the resulting list. A spread may insert literal elements, as in [...xs, 0, 1]. Local bindings may alias these lists or concatenate them before returning the sort. The condition binds the same local names, so it still depends only on parameters. Lists that are not reachable from parameters remain refused. Calls may also occur in conditionals, in local initializers, or as the input of a later array method. Each call adds the callee's condition over its actual arguments. A condition is required even for a branch that the call does not take. Inside map, filter, some, every, find and findIndex, each sort condition quantifies over the elements of that callback's input. This works for nested maps, captured parameter lists and calls to functions that sort. The callback proof assumes the condition only for its current element. A for … of loop similarly carries key conditions in its environment invariant. The condition applies to the current input element and captured inputs, including in nested loops and loops with break or return. The result may accumulate sorted lists. Sorts of changing loop state or body-local lists remain refused because their conditions need a preservation proof. A call with sort conditions inside findLast, reduce or a map that reads the index remains refused. The callback of findLast sees a reversed list, and the other two see an index or an accumulator that an element condition does not describe. Sort expressions may likewise appear in conditionals, local initializers and as inputs of later array methods. Their list inputs may come from map, filter, slice, a conditional or a call. The precondition concerns the resulting keys, so a map that computes a difference must produce finite keys when the later sort uses a difference comparator. Other computed list shapes remain refused. Calls in record literals and spreads also pass their key conditions to callers. Calls inside nullable matches carry a condition for the selected branch only, including in map, filter and loop bodies. A direct sort, conditioned callback or loop under an enclosing nullable narrowing still needs scope propagation; a helper call inside the match is supported instead.
A certificate's theorems follow from translate_sound, so they do not unfold the interpreter. The certificate holds the IR that the translator gives, and the kernel checks that the translator gives that IR for the program. Then a link theorem for each function states that the printed definition computes what the evaluator gives for the IR, and decls_sound in tolean/TypeScript/Proof/Link.lean carries it to the interpreter. A loop gets a lemma of its own: the evaluator runs the loop as the printed List.foldl, for every environment whose variables have values of the right types. The lemma follows from runFold_foldl, which Tolean proves once: when one run of the body and one step of the fold agree, the loop and the fold agree. A loop with a break runs as the printed forIn instead, and its lemma follows from runFold_forIn in the same way, or from runFold_forInRet when a return can end it. tests/typescript/checkCertify.sh certifies each corpus file it can, and tests/chain/check.sh checks that a wrong translation breaks a certificate. Tolean also proves the parser's round trip. parseChars_reads in tolean/TypeScript/Syntax/RoundTripText.lean states that the parser reads the printed source of every module that it gives as the same module, apart from spans. The proof has these parts. Each compares trees apart from spans, and a well-formed tree is one that has the shape that the parser reads.
| What it states | Theorem | File in tolean/TypeScript/ |
|---|---|---|
| The parser reads the printed tokens of every well-formed type as that type, given fuel for how deep the type nests. | types_reads | Syntax/RoundTrip.lean |
| The same for each level of the expression parser, when the target edition has the operators that the expression uses. | exprs_read | Syntax/RoundTripExpr.lean |
| The same for statements, in a function or not and in a loop or not. | stmts_read | Syntax/RoundTripStmt.lean |
parseModule reads the tokens of the printed lines of every well-formed module, which the end of the file follows, as that module. | module_reads | Syntax/RoundTripDecl.lean |
| Every module that the parser gives is well formed, and each word that it prints is one that the lexer reads back. | parseTokens_wf | Syntax/ParseWF.lean |
The lexer reads the printed source as the tokens of the printed lines, with the line breaks that Laid states. | lexChars_render | Syntax/RoundTripLex.lean |
The printer puts a line break inside a line only before a (. | Module.breaksOK | Syntax/RoundTripText.lean |
Effects (planned)
Tolean refuses most calls to libraries with side effects today. The effects plan describes how the translators will share one mechanism for them. Each library declares its effects in a small file, and the declarations fix a trust boundary that a later proof of the library removes.
Names
A source name never hides a Lean name that the output uses. Before it translates a file, the translator collects every identifier in it. When the file declares a name that the output also uses, such as List, Option, some, none, decide, Int, Bool, JSString or JSNumber, the output writes the Lean name in full from the root, as _root_.List or _root_.Option.none. The source name stays as it is, so a claim refers to it by the name in the source. The number type parameter is N, or N1, N2 and so on when the file uses N. Both translators follow this rule, and corpus/translate/leanNames.ts checks it. A Lean keyword, such as def or where, is still refused as a name.
Imports
A file may import the exported functions, interfaces and type aliases of other files of the project:
ts
import { clamp, type Gauge } from "./lib/util.ts";Project imports follow compilerOptions.moduleResolution in the tsconfig.json next to tolean.json. Tolean accepts comments and trailing commas in that file. If there is no tsconfig, set the fallback in tolean.json:
json
{
"typescript": {
"sources": ["src/**/*.ts"],
"moduleResolution": "bundler"
}
}Mode names are case-insensitive. A tsconfig takes precedence over the fallback, including per-file overrides. If it has no moduleResolution, or the setting names another mode, imports still need .ts.
| Mode | Import | File that Tolean selects |
|---|---|---|
bundler | ./x | x.ts, then x/index.ts if the file is absent |
bundler, node16, nodenext | ./x.js | x.ts |
| Every mode | ./x.ts | x.ts |
The file wins when both x.ts and x/index.ts exist, as in TypeScript. Tolean checks all project files before it checks which ones are listed as sources. Omitting x.ts from the sources therefore refuses the import instead of selecting x/index.ts. The node modes use the ESM spelling. They do not accept extensionless imports even in a CommonJS project. Raw Node type stripping still needs .ts; use the matching TypeScript build or bundler when running code that uses the other spellings.
Tolean loads relative extends chains, including shared bases outside the directory that contains tolean.json. A base path is relative to the config that declares it, and may omit .json. An array of bases follows TypeScript 5's order: later bases override earlier ones, then the child overrides each inherited compiler option. A cycle or missing base is an error. Package names in extends and absolute paths remain refused. Each inherited config is recorded by its relative path and SHA-256 hash in the translation manifest. Workspace hosts must supply the base files too, using paths relative to the project root, such as ../../tsconfig.base.json. The workspace result reports these inputs in configInputs. This does not allow imports or source globs to reach outside the project.
Tolean checks the merged options before it resolves imports. It refuses moduleSuffixes and rootDirs, including inherited settings, because they can select a different relative import target. paths and baseUrl do not enable nonrelative imports. Other compiler options and source-selection settings do not change Tolean's project settings: tolean.json still lists the sources. The external config inputs decision explains this boundary.
- An import must name a relative path to a translated
.tsfile. Tolean refuses packages,.tsx, declaration files such as.d.ts, and other extensions. It does not search arbitrary extensions such as./x.custom. It also refuses a directory'spackage.jsonrather than guessing whether that file redirects the import. If an unsupported file would win beforeindex.ts, such asx.tsx, Tolean refuses the import. - Node reads a source as a URL, so Tolean refuses a source with
%,?,#or\, and one such as"./util.ts/."that names a directory there. The resolved file must be among the sources oftolean.json, and its edition may not be newer than the importing file's. - An interface or a type alias needs
type, either before its name or asimport type. Node's type stripping removes only imports that saytype, so without it the JavaScript would import a name that does not exist at run time. - Only named imports are supported. Tolean refuses a default or namespace import, an import with no names or for its side effects, and an import cycle.
import { clamp as limit } from "./x.ts"bindslimitin the file to the function or string enum thatx.tsexports asclamp, and the output names the original declaration. The new name must be free in the file. A type may not be renamed:import { type Range as Span }is refused, since the output names a type by its own declaration and a second name would need an alias of its own.- A type re-export, such as
export type { Point } from "./x.ts", may name an exported interface or type alias. The output imports the translated source module but adds no declaration. A consumer uses the original type's identity, even through several re-exporting files. The re-export does not bindPointlocally. Type re-exports of enums and tagged unions remain refused. - A value re-export, such as
export { clamp, Color } from "./x.ts", may name a function or a string enum that the source file exports, either itself or through its own re-exports. A file that imports the name gets the original declaration, so its output calls the function of the file that declares it. The re-exporting file's output adds no declaration. The re-export does not bind the name locally either, so that file may keep a private function of the same name. A module exports each name once, so the name may not also be exported by a declaration or by another export list of the file.export { clamp as limit } from "./x.ts"re-exportsclampunder the namelimit, which then counts as the name it exports. A type re-export may not be renamed. Tolean refusesexport *. The value re-exports decision explains the model, and the renamed imports decision the renames. - An export list, such as
export { clamp, type Range }, exports declarations of the file, asexportbefore each of them would. It may name only functions, interfaces and types that the file declares before the list and does not export already, and no name twice. An interface or a type needstype, and a function may not have it, because Node's type stripping removes exactly the names that saytype. The output does not change, because the names stay in scope.export { scale as resize }exports the functionscaleunder the nameresizetoo, even whenscaleis exported already, and an importer ofresizecallsscale. Only a function of the file may be renamed in an export list, and the new name may not be one that the file exports otherwise. Tolean refusesexport *. - A function or an interface may not be named
NaN,InfinityorNumber, because it would hide the global that the subset reads under that name. - A local may not have the name of a function that the file declares or imports, or of
NaN,InfinityorNumber. In JavaScript the local is in its temporal dead zone from the start of its block, so a use of the name before the local throws, where the subset would read the function or the global. A parameter or a local may not have the name of an interface of the file either, because Lean, unlike TypeScript, would read the type as the local. - No two files of a project may have namespaces that are equal or nested, such as
AandA.B. Insidenamespace A.B, Lean finds a plain name such asdecideinAbefore the root, so one file's declarations could change what another file's output means.
tolean translate translates the files of a project so that each file comes after the files it imports from. Each file becomes its own Lean module, with an import line for each file that it imports from. The module's name comes from the output's path, from the directory that moduleRoot names, or from the directory of tolean.json by default. Each file's manifest lists the files it imports from among its sources, with their resolved paths. The output writes a name from another file from the root, with that file's namespace, such as _root_.lib.Util.clamp, so that a local name cannot capture it. A file may read and build the fields of an interface that reaches it through another interface's fields, without importing it. A file that imports from a file that uses the number model uses it too, so that it has a number type to pass. The command for one file, tolean translate <file>, refuses an import, because it does not see the other files.
The project resolves imports before translation, without changing the source spans of the parsed program. The interpreter runs that resolved program of several files, and a call runs the function that its file declares or imports under that name. program_sound covers such programs. File selection remains a tested part of loading the project, not a new operation in the interpreter. A file with imports has no certificate yet. corpus/translate/projects/ holds projects that the translator must accept and compile, and projects that it must refuse.
The subset
The TypeScript translation is a shallow embedding, which means it maps TypeScript constructs straight to Lean constructs. That is sound only for code that cannot alias mutable state. For this reason, the subset lets a function change only the locals that it owns. Tolean rejects anything else and reports the file, the line and the reason. It never approximates.
An interface field needs a type, but it need not say readonly. Both x: T and x?: T translate as their readonly forms do, because Tolean refuses every write to a field. This includes compound assignments, increments and decrements, and writes through loop variables, callbacks and local functions. delete, destructuring assignment and calls such as Object.assign cannot bypass that rule. A nested interface or inline object type follows the same rule. The readonly mark on a constructor parameter of an error class is different: it declares a field, so Tolean still uses it there.
The translator supports a restricted slice of ordinary classes. Each class must have one constructor that assigns every required readonly field exactly once. Methods use static dispatch, so a receiver must have the class's exact declared or inferred type. Tolean refuses operations that could observe the JavaScript prototype, including instanceof, constructor identity and methods extracted through object destructuring. Object destructuring may read readonly fields from a class instance, but the destructured names have no class type and cannot call class methods. The existing class C extends Error subset is separate; its accepted form and limits are listed below. The class decision explains the ordinary-class lowering and its limits.
Inline object types work in aliases, parameters, return types, interface fields, array elements and local annotations. They also work as the members of a named tagged union:
typescript
export type Shape =
| { readonly kind: 'circle'; readonly r: number }
| { readonly kind: 'square'; readonly side: number };The translator gives each anonymous shape a generated Lean structure. Equivalent annotations in a module share that structure, even when they occur at different source positions. For example, this identity function keeps one type for its argument and result:
typescript
export function id(x: { readonly n: bigint }): { readonly n: bigint } {
return x;
}The comparison uses resolved field types, so aliases do not create a new shape. Field order and the readonly mark do not change its identity. Captured generic parameters become parameters of the generated structure. Their source scopes still determine which types they name. Generated names avoid source identifiers, including local names and field names.
Shapes exposed by source dependencies can be reused too. Unrelated project units do not change a file's generated names or introduce hidden dependencies. Two modules that independently define a shape can still have different Lean structures; use a type from a common dependency when passing values between them. There is no general structural coercion between generated types. A concrete annotation can reuse a generic shape already in scope when substituting its parameters makes every field agree.
The existing restrictions on named interfaces also apply here. A literal must write its fields in the order of the shape's first annotation, because JavaScript can observe property order. The translator reports that order when a literal differs. A named interface keeps its own type identity, even when its fields match an anonymous shape; width subtyping is not supported. Recursive anonymous shapes that refer to their enclosing declaration need a separate named interface. Generic tagged unions remain refused.
The claim is about each call's values, not the lifetime of a JavaScript object. Calls are synchronous, and the subset cannot call caller-supplied code that might change a field during a call. A caller may later change an object that a function returned, or an object held in an array or map. A later call that receives the changed object has different input values. A result describes the value when the call returns. It does not promise that a returned reference stays unchanged. The model does not represent object identity, getters or proxies. Callers must pass values that the model represents, as they must meet the other input preconditions.
ReadonlyArray<T>, Array<T> and T[] still have the same value model. Only an owned array may be pushed to, and the ownership checks forbid changing a collection that something else holds. Removing readonly from an interface field does not relax those checks, even when the field holds a collection. The parser still refuses readonly T[]; this change concerns interface fields, not new array type syntax.
| TypeScript | Lean |
|---|---|
bigint | Int (exact; literals are typed (n : Int)) |
number | an abstract N with [JSNumber N] (see Numbers) |
integer number literal, -x, + - * /, < <= > >=, === !== on number | JSNumber.ofSafeInt, neg, add, sub, mul, div, lt, le, eq |
Number.isSafeInteger(x) | (JSNumber.toSafeInt x).isSome |
Number.isNaN(x), Number.isFinite(x), Number.isInteger(x) | JSNumber.isNaN x, JSNumber.isFinite x, JSNumber.isInteger x. isInteger holds when x is finite and Math.trunc(x) is x, as ECMA-262 defines it. |
Math.floor(x), Math.ceil(x), Math.trunc(x), Math.round(x), Math.abs(x) on a number | JSNumber.floor x, ceil, trunc, round, abs |
a & b, a | b, a ^ b, ~a, a << b, a >> b and a >>> b on numbers | JSNumber.bitAnd a b and its relatives (tolean/TypeScript/Spec/Number.lean). JS converts each operand with ToInt32, or with ToUint32 for >>> and for a shift count, so x | 0 is the integer part of x modulo 2^32, as a signed 32-bit integer. The model has one new operation for them, JSNumber.toInt, the exact integer part of a finite number. Lean defines the rest. |
Object.is(a, b) on two numbers | JSNumber.sameValue a b: ===, except that NaN is the same as NaN, and +0 is not the same as -0 (SameValue). The model has one new operation for it, JSNumber.isNegZero. |
Object.is(a, b) on two bigints, booleans or strings | decide (a = b), as for === |
Number(b) on a bigint | JSNumber.ofInt (N := N) b: the double nearest to b, with ties to the one whose last bit is zero, and ±Infinity beyond the largest double. Tolean refuses Number(v) on other values, because the model has no ToNumber for them. |
Date | JSDate (tolean/TypeScript/Spec/Date.lean): the time value, as an Option Int of milliseconds since the start of 1970 in UTC, where none is an invalid date. The subset has no setters, so a date never changes, and a value stands for it. Tolean refuses === on dates, because JS compares them as objects. |
new Date(t) on a number | JSDate.ofNumber t: TimeClip of t, its integer part, or an invalid date when t is not finite or is more than 8.64 × 10^15 from zero |
d.getTime(), d.valueOf(), and the UTC getters d.getUTCFullYear(), getUTCMonth, getUTCDate, getUTCDay, getUTCHours, getUTCMinutes, getUTCSeconds and getUTCMilliseconds | JSDate.getTime (N := N) d and JSDate.getUTCFullYear (N := N) d and the others, which follow the calendar of ECMA-262 §21.4.1 on integers. Each is NaN for an invalid date. |
const x = d.toISOString() and return d.toISOString(), where d is a Date | if JSDate.isInvalid d then throw JSError.rangeError else …, with JSDate.toISOString d as the value. The text is the Date Time String Format in UTC, such as 2024-03-05T07:08:09.010Z. A year from 0 to 9999 has four digits, and any other year has a sign and six digits, such as -000001 or +010000. JS throws a RangeError for an invalid date, and the engine chooses its message, so JSError.rangeError carries none. The function returns Except. A call inside a larger expression or in a local function is refused. It is in ES2015. |
Date.UTC(year, month, …) with two to seven numbers | JSDate.utc (N := N) [year, month, …]: MakeDay, MakeTime and MakeDate, with the arithmetic of numbers where ECMA-262 uses it, so a large argument rounds as it does in JS. A year from 0 to 99 is a year of the 1900s. |
Date.parse(s) where s is a Date Time String Format literal | JSDate.parseFormat recognizes and parses its UTF-16 code units at translation time. The output is JSDate.number of the resulting time value, or none for NaN. Date-only forms use UTC and may omit the month and day. Date-time forms need a full date and an explicit Z or numeric offset. Expanded years, 24:00:00, and out-of-range fields are covered. This needs ES2016 or later. Other strings and non-literal arguments stay refused. |
Math.min(a, b, …), Math.max(a, b, …) on numbers | JSNumber.minimum (N := N) [a, b, …] and JSNumber.maximum. They fold Math.min of two numbers over the list, from Infinity, as ECMA-262 does, so Math.min() is Infinity. Tolean refuses a spread argument. |
NaN, Infinity, -Infinity | JSNumber.nan, posInf, negInf |
T | null, null | Option T, none |
f?: T | null, x?: T | null | An optional field or parameter has type JSNullish T, with JSNullish.undefined as its default. JSNullish T abbreviates Option (Option T), so null and undefined remain distinct. ?? checks both layers, and ?. skips a projection for either nullish value. |
x === null, x !== null | JSNullish.isNull x, or its negation |
x == null, x != null | JSNullish.isNullish x, or its negation |
x === undefined, x !== undefined | x.isNone, x.isSome |
x === null, x !== null | x.isNone, x.isSome |
x == null, x != null | the same as === and !==, because a value of T | null is never undefined |
x === null || e, x !== null && e | match x with | none => … | some x => e (TypeScript's narrowing) |
a ?? b on T | null, where b is a T | Option.getD a b |
a ?? b on T | null, where b may be null | Option.or a b |
boolean | Bool |
string, "abc" | JSString, JSString.ofString "abc". A JSString holds the UTF-16 code units of the string, as ECMA-262 defines a string, so a value can hold a lone surrogate, which a Lean String cannot. ofString is injective, so a claim can state a literal as a Lean String. |
T | undefined on a local or return value | Option T. A defined value becomes some, and undefined becomes none. A local may be initialized or assigned either value. The type may not also include null. A field must use f?: T instead, because a missing key and a key whose value is undefined share one Lean value. |
ReadonlyArray<T>, Array<T>, T[] | List T |
interface with typed, required fields, with or without readonly | structure |
An interface whose fields name the interface itself, such as readonly next: Node | null or readonly children: ReadonlyArray<Tree<T>> | The same structure. Lean reads it as a nested inductive type, so a value is a finite tree, as every value that the subset can build is. |
f?: T or readonly f?: T, an optional field | f : Option T := none. An object literal may leave the field out, or set it to a T. A read of a field that the object lacks gives undefined, which is none. s.f ?? d is Option.getD s.f d, and s.f === undefined is s.f.isNone. |
x?: T, an optional parameter | (x : Option T := none). A call may leave out the optional parameters, which come last, and then the output passes none for each. A call may also pass a T, or undefined, which is none too. x ?? d, x === undefined and x?.f work as they do on an optional field. |
if (x === undefined) or if (x !== undefined), with undefined on either side, where x is an optional parameter or a local with an optional value | match x with | none => … | some x => …, as for a test of null. The branch where x is defined reads it as a T. |
x !== undefined && e, x === undefined || e, and a conditional that tests x against undefined | A match on Option. The branch where x is defined reads it as a T. The test may put undefined first, or negate the comparison with !. Only the selected branch runs. Existing expressions that need no narrowing keep their output. |
p?.f, where p is a S | null or an optional field of type S | p.map (·.f), or p.bind (·.f) when f is optional. The value is undefined when p is null or undefined, so it has the type of an optional field: p?.f ?? d and p?.f === undefined work as they do on s.f. |
xs?.[k], where xs is a nullable or optional array and k is a nonnegative safe-integer literal | xs.bind (·[k]?). An absent receiver or an index past the end gives undefined. The element type must not be nullable or optional. |
xs?.[i], with any other number expression as the index | xs.bind (fun ys => JSNumber.elementAt? ys i). Negative, fractional and nonfinite indices give undefined, as they do for ordinary array indexing. Another optional access may follow, as in xs?.[i]?.value. |
pair?.[k], on a nullable or optional tuple | Bind the tuple, then read its projection. As for ordinary tuple indexing, k must be an in-range integer literal. The selected element may be optional but must not be nullable. |
record?.[key], on a nullable or optional Record<K, V> | Bind the record, then read the field selected by key. The key must have the Record's literal-union type K. V may be optional but must not be nullable. |
e as const and e satisfies T | e. Type stripping removes both, so the value is the value of e. Tolean types e in the context of T and checks that the value has the type T, as tsc does. The value keeps its own type, which can be wider than the type tsc gives it, because the output types a literal by its context, as it does without as const. |
p?.f.g, a chain of reads after ?. | p.map (·.f.g), or p.bind (·.f.g) when g is optional. The reads after ?. are a part of the same optional chain, so the whole chain is undefined when p is null or undefined. Each field before the last must be a required field of an interface type. |
type T = U, declared before its uses | abbrev T := U. The output writes U itself wherever the source names T, so the abbrev is only for claims. |
type T = 'a' | 'b', a union of string literals | inductive T with the constructors a and b, which derives DecidableEq. A literal becomes T.a where the context expects a T, and t === 'a' becomes t = T.a. The output writes every constructor in «», such as T.«open», because Lean reads some strings as keywords or modifiers. A claim can still write T.a. |
enum T { A = 'a', B = 'b' }, an enum whose members are strings | The same inductive T as for 'a' | 'b', with the constructors named after the strings, so T.A becomes T.«a». TypeScript compiles the enum to an object with one property for each member, and T.A reads it. The output has no such object, so only T.A reads a member, and a file that imports the enum without type may read its members too. |
type T = A | B, a union of interfaces with a tag field such as kind: 'circle' | inductive T with a constructor for each member, which holds the member's structure. The structure leaves the tag field out, because its value never changes. An object literal where a T is expected becomes the constructor of its tag. |
if (s.kind === 'circle'), with === or !== and the string on either side | match s with | T.circle s => … | …. TypeScript narrows s in each branch, and so does the output. A chain of such tests on the same value becomes one match. |
switch (s.kind) with a case 'circle': for each member, or a default: last, where every clause returns | The same match, with one arm for each case. The default, or the code after the switch when it has no default, becomes the arm for the members that no case names. |
The same switch, where every clause changes locals and ends in break, or throws | let (x, y) := match s with …, as for an if that changes locals. The last clause may leave out its break. Without a default, the arm for the members that no case names keeps the locals as they are. In a loop body, the match is the step of the List.foldl. |
The same switch, where the cases cover every member and a last default: { const x: never = s; … } checks it | The same match, without the default. TypeScript accepts the check only where no member is left, so the clause never runs. The statements after the check are not translated. In a switch whose clauses end in break, the last case needs its break, because without it the case would run into the default. |
The same switch with grouped labels, as in case 'circle': case 'square': return true; | One arm for each label, each with the body that the labels share. A case with no statements runs into the next clause, so it is not fallthrough. |
type T = string | bigint, a union of two or more of string, number, bigint and boolean | inductive T with a constructor for each member, which holds a value of its type, such as T.string (value : JSString). The constructor is named after what typeof gives for the value. A value of a member where a T is expected becomes that member's constructor. |
if (typeof x === 'string'), with === or !== and the string on either side, where x is a local of such a union | match x with | T.string x => … | …, which narrows x as a test of a tag does |
type R = Record<K, V> or Readonly<Record<K, V>>, where K is a literal union of strings | structure R with one field of type V for each string of K, in the order of K. A value has a property for each string, so an object literal must set every key, in that order, as for an interface. r.a and r['a'] read a field. |
r[k], where r is such a Record and k has the type K | match k with | K.a => r.a | …, which reads the field that k names |
function with typed parameters and return type | def |
function g(a: A): void { … }, or const g = (a: A): void => { … }, at the top of the body of a function f, which changes let locals of f, and a call g(a); as a statement | def f.g, before f. It takes the locals of f that its body names, then its own parameters, and it returns the locals that it changes, as a tuple when there are two or more. A call is let (x, y) := f.g x y a, which binds those locals again, so a call in a loop body changes the state of the loop. |
A local function that changes captured let variables and ends with return total, where total is one of those changed variables | The lifted function returns the captured state. A call binds that state again and reads total from it as the call's value. The tuple need not contain a second copy of the same value. The call can initialize a const or let, or be the whole value of a return. This also works in a loop and with a local arrow function. |
A local function that changes captured let variables and ends with return e, such as return total * 2n;, return before + total; where before is a body local, or return double(total); | The lifted body binds the value of e to a fresh name, g' for a local g, then returns the changed variables and that value as one tuple, so the body runs once. e can be any expression that a const initializer accepts there. A call binds the variables again and takes the last element as its value. The call can initialize a const or let, or be the whole value of a return. The body may not name g' itself, and may return earlier only in guards at its start (next row). |
A state-writing local function from the row above whose body starts with guards, if (c) return e; or if (c) { return e; } | Each guard becomes an if in the lifted body. Its first branch returns the captured variables, still unchanged, and the value of e. Its other branch holds the rest of the body. The interpreter runs a guard the same way, keeping the environment at the guard's return. |
A local function that calls an earlier sibling, which may itself call earlier siblings, as in a chain addFour → addTwice → add | The lifted definitions appear in callee-before-caller order. The IR passes the sibling closure and checks it at a call. The printed code passes () for that closure, since the call names the lifted definition directly. The caller must itself name each variable and each sibling that the callee captures, so a caller at the end of a chain names the siblings further down that its callee calls. A value-returning caller that changes captured state must write a captured variable or call a sibling as a statement, as in add(value); return total;, and obey the final-return rule above. The interpreter treats such a call statement as a change to captured state, so it keeps the sibling's writes. A caller whose only change comes from a value-returning sibling, such as const t = add(value);, stays refused. |
function g(a: A): T { … } or const g = (a: A): T => { … } in the same place, which changes no variable of f, called as the whole value of a const, a let or a return | def f.g that returns the T, and let v := f.g x a at the call |
A function that calls itself, where each call passes a part of one parameter, the same one in every call. A part is a field of it, a value that a test of null, undefined or a tag narrows it to, an element of an array in it, an element of a tuple in it, or a part of one of these. | The same def, followed by termination_by p for the parameter p, and decreasing_by all_goals tolean_decreasing. Each call passes a value that is smaller by sizeOf, and the tactic from tolean.TypeScript.Decreasing proves it, so Lean checks that the function ends. Each match in such a function names the equation of its value _h', which the tactic reads. Lean defines the function by well-founded recursion, so a claim unfolds it with unfold or simp, not with rfl or decide. |
throw new Error(m), where m is a string, as the last statement of a function, of a loop body, or of a branch | throw (JSError.mk m). A function that can throw returns Except JSError R, and each value that it returns is pure of the value. JSError, in tolean/TypeScript/Spec/Error.lean, holds the message, or is JSError.rangeError for a built-in RangeError. |
A terminal try { … } catch (e) { … } whose try body passes the read-only check | try … catch _ => … in Except. A returned value skips the handler. A thrown error selects the handler with the variables from entry to the try statement. |
e.name and e instanceof RangeError in a handler, where e is the catch binding | catch e => … with JSError.name e and JSError.isRangeError e. The name is "RangeError" for the error of a built-in operation and "Error" for the error of new Error(m). Tolean refuses every other use of e, including e.message, because the engine chooses the message of a RangeError. It refuses a handler that reads e in a file with error classes, and a declaration named RangeError. It needs ES2015. |
const x = f(a), let x = f(a) or return f(a), where f can throw | f a >>= fun x => …, which passes the error of the call on. So the function that holds the call can throw too. |
A call of f inside a larger expression, such as return f(a) + 1n, where JS evaluates the call whenever it evaluates the statement | f a >>= fun r0' => … before the statement, which reads r0' in place of the call. Each operand that JS evaluates before the call, such as x.count in x.count + f(a), moves out first, to a let of its own, so the output runs the same operations in the same order. A literal whose parts are all literals stays, because it reads nothing and runs nothing, and its type comes from its position. The interpreter runs the statements in this form too (Eval.Stmt.hoisted), so the translator translates the body the interpreter runs. |
A loop whose body can throw, by a throw or a call of a function that can, and that changes a local or returns | The same fold in the Except monad: List.foldlM, or forIn without Id.run, followed by >>= fun (x, y) => for the statements after the loop. Each run of the body ends in pure of its state, or throws. |
An if or a switch that changes locals, where a branch can throw | (if c then throw e else pure (x, y)) >>= fun (x, y) =>, so that the statements after it take the state from the branch that did not throw |
class C extends Error { constructor(readonly a: T, b: U) { super(m); } }, or the same with no constructor | A constructor C of Thrown, the inductive of the errors that the file's functions throw, with the message and the readonly parameters as fields. Thrown comes first in the file, with error (value : JSError) for throw new Error(m). Every function of the file that can throw then returns Except Thrown R. A parameter must have a primitive type. A readonly parameter may not be named message, name, stack, cause or __proto__, because it declares a field. The same restriction applies to separate readonly declarations. Plain parameters may use those names. A class with no constructor may be thrown without arguments and gets an empty message, while JavaScript uses the default message when an optional-message constructor is thrown without arguments, though the translator refuses optional constructor parameters. The message may not call a function, and the class must be declared before the functions that throw it. The class may not be named error. A decision record explains the type and the rules. |
class C extends Error { readonly line: number; constructor(message: string, line: number) { super(message); this.line = line; } } | The parser normalizes the declared field to a readonly constructor parameter. Each field needs one required same-name parameter with the same primitive type, and exactly one unconditional assignment after super(message). The normalized field order must match parameter properties followed by separate declarations. Assignments must follow declaration order so downlevel output preserves the same own-field order. Assignments from other names or expressions and optional fields remain refused. See the decision. |
this.name = "ParseError"; in an error constructor after super(message) | One unconditional string-literal assignment sets the error's own runtime name. The generated error constructor carries that string separately from its class tag. An omitted assignment leaves the inherited name "Error". The literal may be empty or differ from the class name. Before ES2022, assign the name after all separately declared fields so downlevel output preserves own-field order. Repeated, conditional, and computed name assignments remain refused. |
class C { readonly a: A; constructor(a: A) { this.a = a; } m(x: A): A { return this.a; } } | Before interpretation and translation, the class becomes an interface, an object-constructor function and a free function for each method. new C(a) calls the constructor. c.m(x) calls the free function with c as its first argument, but only when c has exactly the static type C. Ordinary fields require ES2022. The class decision record separates the proved parser and lowered-program theorems from the Node comparisons that test elaboration. |
throw new C(args), in the places where throw new Error(m) may stand | throw (Thrown.«C» m a), with the constructor's message written over the arguments, which first move to names unless they are literals, and the readonly arguments as the fields. The substitution stops at the parameters of an arrow function in the message. |
const x = e, let x = e | let x := e |
x = e, x += e, x -= e, x *= e on a let local | let x := … (shadowing) |
x ??= e on a let local of type T | null | let x := Option.or x e. JS evaluates e only when x is null. Lean evaluates it either way, but the result is the same, because the subset has no side effects. |
[a, b] with the element type from the context or the elements, such as return [a, b] or const xs: ReadonlyArray<T> = [] | ([a, b] : List T) |
[...xs, a, b, ...ys], where each spread is an array, a set, a map or a string | (xs ++ ([a, b] : List T) ++ ys), and [...xs] is xs. A spread iterates its value, as for … of does (§13.2.4.1). So a set gives JSSet.elems s and a map gives JSMap.entries m, each in the order of insertion. A string gives JSString.codePoints s, its code points as strings. |
const [a, b] = t, where t is a tuple | let (a, b) := t when the pattern names each element, and let (a, b) := (t.1, t.2.1) for a pattern with holes or with fewer names. The value is read once. |
const [a, , c, ...rest] = xs, where xs is an array, a set, a map or a string | let (a, c, rest) := ((xs[0]? : Option T), (xs[2]? : Option T), (List.drop 3 xs)). The pattern iterates xs, as for … of does (§8.6.3), so each name is optional, undefined past the end, as xs[k] is. The rest is a new array of the values after the places. A set gives JSSet.elems s, a map JSMap.entries m and a string JSString.codePoints s. |
for (const [k, v] of xs), a pattern in the head of a loop | The fold binds each element to the first name of the pattern, and the body starts with let (k, v) := k, which binds the names as const [k, v] = element does and hides that first binding. So for (const [k, v] of m) on a map names the key and the value of each entry. The body may not assign, increment or otherwise write to either binding. |
xs.entries(), where a loop, a spread or new Map iterates it | (JSNumber.entries (N := N) xs), the list of pairs of each index, a number, and its element (§23.1.3.4). So for (const [i, x] of xs.entries()) names both. On a map, m.entries() is JSMap.entries m, as a loop over the map is. |
[A, B] and readonly [A, B], a tuple of two elements or more | A × B. In JS a tuple is an array. |
[a, b] where the context expects a tuple, such as a return value | (a, b), with each element translated where its own type is expected |
t[0], an element of a tuple at an index that is a number literal | t.1, and t.2.1 or t.2.2 for the second or the last of three, as Lean nests the product to the right |
const xs: Array<T> = [...], then xs.push(e); xs read only in the return | let xs := xs ++ [e] |
Map<K, V> and ReadonlyMap<K, V>, where K is number, bigint, string, boolean or a literal union of strings | JSMap K V (tolean/TypeScript/Map.lean): the list of entries, in the order that each key was first set, as ECMA-262 keeps them (§24.1). A key is found with SameValueZero, which JSKey.same gives. On every key type but number it is =. On number it is JSNumber.sameValueZero, so a map has at most one NaN key, and 0 and -0 are the same key. A new key -0 is stored as 0 (§24.1.3.9), so a loop over the keys never sees -0. |
const m = new Map<K, V>(), or const m: Map<K, V> = new Map(), then m.set(k, v) and m.delete(k) | let m := (JSMap.empty : JSMap K V), then let m := JSMap.set m k v and let m := JSMap.delete m k. The function owns the map, as it owns an array that it pushes to. |
m.get(k), m.has(k) and m.size | JSMap.get? m k, JSMap.has m k and JSNumber.ofSafeInt (JSMap.size m). get gives undefined for a key that the map does not have, so its value has the type of an optional field: m.get(k) ?? d is Option.getD (JSMap.get? m k) d. |
Set<T> and ReadonlySet<T>, where T is a type that a map key may have | JSSet T (tolean/TypeScript/Map.lean): the list of elements, in the order that each was first added (§24.2). Elements compare as map keys do, and add(-0) stores 0 (§24.2.4.1). |
const s = new Set<T>(), then s.add(x) and s.delete(x); s.has(x) and s.size | JSSet.empty, JSSet.add, JSSet.delete, JSSet.has and JSNumber.ofSafeInt (JSSet.size s), as for a map |
new Map(items) and new Set(items), where items is an array, such as [['a', 1n]] or ['a'], a map or a set | JSMap.ofList and JSSet.ofList of the list that a loop over items visits. The constructor sets each [key, value], or adds each value, in order (§24.1.1.2), so a later entry for a key replaces an earlier one, and new Map(m) copies m. new Set(s) on a string adds each of its code points. |
for (const x of s) over a set, and for (const e of m) over a map | List.foldl over JSSet.elems s, or over JSMap.entries m, as over an array. A map gives each entry as the tuple [key, value], as JS does, so the body reads e[0] and e[1]. The loop may run over an owned map or set, if its body does not change it. |
for (const x of xs) { … } | List.foldl over the tuple of locals the body changes. The body may not assign, increment or otherwise write to x. JavaScript throws a TypeError for a write to that binding. The interpreter also gives no value when its scan finds a write to a same-named shadowed local or inside an uninvoked closure, even though Node returns normally. The scan checks names, not binding identity, so these cases stay refused to keep the interpreter and translator aligned. Tracking binding identity would change the interpreter environment relation and require changes to its statement proofs. |
if (c) continue; at the top of a loop body, or a branch of that if that ends in continue on every path | if c then (x, y) else …, where the rest of the body is the else branch, as after an if that returns. A test of null or of a tag narrows the local for the rest of the body. |
break in a for (const x of xs) loop, in the same places as continue | Id.run (forIn xs (x, y) (fun e (x, y) => …)). A break is ForInStep.done (x, y), which ends the loop, and the end of the body or a continue is ForInStep.yield (x, y). A loop without a break stays a List.foldl. |
return e in the same places, in a loop where the statements after it end in a return | match Id.run (forIn xs (none, x, y) (fun e (_, x, y) => …)) with, with the arms | (some r, _) => r and | (none, x, y) => … for the statements after the loop. The state starts with the value to return: a return e is ForInStep.done (some e, x, y), and the other step ends hold none. |
for (let i = k; i < b; i++), where the update may also be ++i or i += 1, the start k is an integer literal and b is a number | The fold of for (const i of …) over JSNumber.countUp k b, with continue, break and return in the same places. countUp gives k, then each integer after it that is less than b. It is empty when i would pass Number.MAX_SAFE_INTEGER, and the interpreter gives no value for such a loop. From a start such as 0, JS needs about 2⁵³ runs of the body to get there. |
xs.map(x => e), xs.filter(x => p) | List.map (fun (x : T) => e) xs, List.filter (fun (x : T) => p) xs |
xs.map((x, i) => e) | List.mapIdx (fun (i : Nat) (x : T) => let i := JSNumber.ofSafeInt i; e) xs. JS passes the index as a number, so the body reads i as a number. An array has fewer than 2^32 elements, so the index is always a safe integer. |
xs.some(x => p), xs.every(x => p) | List.any xs (fun (x : T) => p), List.all xs (fun (x : T) => p) |
xs.find(x => p) | List.find? (fun (x : T) => p) xs. The value is undefined when no element passes, so it has the type of an optional field: xs.find(p) ?? d, xs.find(p)?.f and xs.find(p) === undefined work as they do on s.f. |
xs.includes(x) on bigint, boolean, string or a literal union of strings | x ∈ xs. includes compares by SameValueZero, which is === on these types. It is in ES2016. |
xs.includes(x) on number | List.any xs (JSNumber.sameValueZero x). SameValueZero is ===, except that NaN is the same as NaN, so [NaN].includes(NaN) is true. |
xs.length | JSNumber.ofSafeInt (N := N) ((List.length xs : Nat) : Int), a number |
xs[k], where k is a number literal | (xs[k]? : Option T). The value is undefined when k is not an index of the array, so it has the type of an optional field: xs[0] ?? d, xs[0]?.f and xs[0] === undefined work as they do on s.f. Tolean gives xs[k] this type whatever noUncheckedIndexedAccess says, so code that uses it as a T is refused. |
xs[i], where i is any other number | JSNumber.elementAt? xs i: the element when i is a safe integer within the array, and none otherwise. xs[-1] and xs[0.5] are undefined, as in JS. |
xs.at(k), where k is an integer literal | (xs[k]? : Option T), or ((List.reverse xs)[-k - 1]? : Option T) when k is negative, which counts from the end. It is in ES2022. |
xs.at(i), where i is any other number | (JSNumber.atIndex? xs i). JS reads the index with ToIntegerOrInfinity (§7.1.5), which JSNumber.toIndexInt models with JSNumber.toInt: a fraction rounds toward zero, so xs.at(1.5) is xs.at(1), and NaN is 0. Infinity, -Infinity and every number past the safe integers give undefined, because they land outside the array. A number literal must be an integer, as every number literal in the subset must, so a fraction comes only from a variable or an expression. |
xs.slice(a, b), where a and b are integer literals or left out | List.drop and List.take, such as (List.drop 1 (List.take 3 xs)) for xs.slice(1, 3). A negative bound counts from the end, which the output reads on the reversed list: xs.slice(-2) is (List.reverse (List.take 2 (List.reverse xs))). A negative start with an end that is not negative counts back from the length: xs.slice(-2, 3) is (List.drop (List.length xs - 2) (List.take 3 xs)). |
xs.slice(a, b), where a bound is any other number | (JSNumber.sliceInt xs a' (some b')), where each bound that is a number becomes (JSNumber.toIndexInt a), and a literal stays an Int. xs.slice(i) is (JSNumber.sliceInt xs (JSNumber.toIndexInt i) none). A bound past the safe integers, such as Infinity, clamps to an end of the array, as in JS. As for at, a literal bound must be an integer. |
xs.findLast(x => p) | List.find? (fun (x : T) => p) (List.reverse xs), which the callback reads from the last element to the first, as in JS. It has the type of find, and it is in ES2023. |
xs.findIndex(x => p) | JSNumber.ofSafeInt (((List.findIdx? (fun (x : T) => p) xs).map Int.ofNat).getD (-1)): the index of the first element that passes, as a number, or -1 |
xs.reduce((acc, x) => e, init) | List.foldl (fun (acc : A) (x : T) => e) init xs, where A is the type of init. The body must give a value of that type. |
xs.toSorted((a, b) => e) and [...xs].sort((a, b) => e), where e compares keys | JSNumber.sortWith (fun (a b : T) => e) xs: the stable merge sort, where a comes after b only when e is greater than 0. The comparator must have the shape (a.k < b.k) ? -1 : (a.k > b.k) ? 1 : 0, where the key is the element or a field of it, and a bigint, a string or a number. The tests may come in either order, the signs may be reversed to sort from the greatest, and a comparison of the next key may take the place of the 0. The last comparison may also be a difference of number keys, a.t - b.t, or b.t - a.t to sort from the greatest. Such a comparator is consistent, so the order is the one that JS gives. On number keys that holds only when no key is NaN. A difference also needs every key to be finite: the spec compares each element with itself too, and Infinity - Infinity is NaN, so one infinite key is enough to break it. On other arrays the spec leaves the order to the engine, and the translation makes no claim. toSorted is in ES2023, and sort is stable from ES2019. A decision record explains the meaning. |
if that returns, if that changes locals, c ? a : b | if … then … else … |
+ - *, < <= > >=, === !==, && || ! | the same operators on Int, Bool, Prop |
a + b where one operand is a string and the other is a string, a number, a bigint or a boolean, and s += e on a string local | a ++ b on JSString. ToString converts the other operand first: JSString.ofInt n writes the decimal digits of a bigint, and JSString.ofBool b writes "true" or "false". A number becomes JSNumber.toStr x, an operation of the number model, as JSNumber.add is. The model leaves it abstract, and the law SafeIntLaws.toStr states that a safe integer gives its decimal digits, so "n=" + 3 is "n=3" in a proof. + is left-associative, so 1n + 2n + "!" is "3!". |
`Hello, ${name}! ${n}`, a template literal | The + chain that the lexer reads it as, such as ((JSString.ofString "Hello, " ++ name) ++ JSString.ofString "! ") ++ JSNumber.toStr n, with the conversions of +. A part that + refuses, such as an object or null, is refused here too. |
s.length | JSNumber.ofSafeInt (N := N) ((JSString.length s : Nat) : Int): the number of UTF-16 code units, so "😀".length is 2 |
s.startsWith(p), s.endsWith(p) and s.includes(p), where p is a string | JSString.startsWith s p, JSString.endsWith s p and JSString.includes s p, which compare code units. startsWith_iff, endsWith_iff and includes_iff state them as Lean's prefix, suffix and infix orders on the lists of code units. |
s.startsWith(p, k), s.endsWith(p, k), s.includes(p, k) and s.indexOf(p, k), where k is a number | JSString.startsWithFrom s p k, JSString.endsWithAt s p k, JSString.includesFrom s p k and JSString.indexOfFrom s p k. A non-literal number first becomes JSNumber.toIndexInt k. Each method clamps the position to the string, so a negative k is 0. For endsWith, k is the end of the part that must end with p. |
s.trim(), s.trimStart() and s.trimEnd() | JSString.trim s, JSString.trimStart s and JSString.trimEnd s. They remove the code points of WhiteSpace and LineTerminator, among them U+00A0, U+2028 and U+FEFF. Each of them is one code unit, so the model drops code units. trim needs ES2016 or later: ES2015 names Unicode 5.1, where U+180E is white space too. trimStart and trimEnd are in ES2019. |
s.split(sep), where sep is a string | JSString.split s sep, a List JSString: the pieces between the occurrences of sep. An empty separator gives each code unit as a string, so a surrogate pair gives two lone surrogates, as in JS. Tolean refuses a regular expression. |
s.split(sep, k), where k is a number | JSString.splitLimit s sep k: at most k pieces. A non-literal number first becomes JSNumber.toIndexInt k. ToUint32 takes the integer modulo 2^32, so -1 allows every piece and 0 gives none. NaN and either infinity give no pieces. |
s.at(k), where k is a number | JSString.at? s k, an Option JSString: the code unit at k as a string, or none for undefined. A non-literal number first becomes JSNumber.toIndexInt k. A negative k counts from the end. It is in ES2022. |
s.slice(), s.slice(a) and s.slice(a, b), where a and b are numbers | JSString.slice s a none and JSString.slice s a (some b): the code units from a up to b. A non-literal bound first becomes JSNumber.toIndexInt. A negative bound counts from the end, and each bound is clamped to the string. |
s.padStart(n), s.padStart(n, f), s.padEnd(n) and s.padEnd(n, f), where n is an integer literal | JSString.padStart s n f and JSString.padEnd s n f, with f as " " when the call leaves it out. The filler repeats and is cut to make n code units in all, and an empty filler adds nothing. Tolean refuses an n above 2^28 - 16, because V8 throws a RangeError for a longer string and the model would not. They are in ES2017. |
for (const c of s), [...s] and const [c] = s on a string | A loop over JSString.codePoints s, the code points of s, each as a string (§22.1.5). A surrogate pair is one string of two code units, so [..."😀"] has one element. A lone surrogate is a string of its own code unit, not U+FFFD. codePoints_units states that the code points hold the code units of s, in order. |
s.indexOf(p), where p is a string | JSNumber.ofSafeInt (N := N) (JSString.indexOf s p): the first index of p in code units, or -1. The empty string is at index 0. |
s.toUpperCase() and s.toLowerCase(), where Tolean can show that s is ASCII: a literal of ASCII text, or +, trim, slice or a case change of such strings | JSString.toUpperAscii s and JSString.toLowerAscii s, which change only a to z or A to Z. On other strings the result follows the Unicode version of the engine, which changes between Node releases, so Tolean refuses them. |
JSON.stringify(x), where x is a string, a number, a boolean, null, a member of a literal union or a Date, or an array, a tuple or a nullable value of them | JSString.json x, a function that Spec/String.lean declares but does not define. A proof cannot depend on the text, only on equal values giving equal texts, so every theorem also holds for the real JSON.stringify. Tolean refuses an object, because its text follows the order of its keys, which a caller chooses, so two objects with the same Lean value can give different texts. For the same reason it refuses a tuple that ends with a tuple, because Lean writes [A, [B, C]] and [A, B, C] both as A × B × C. The output writes the type of the argument, so JSON.stringify(null) is JSString.json (none : Option Empty). A date writes null when it is invalid and the text of toISOString otherwise (Date.prototype.toJSON), so its time value fixes the text. JSON.stringify of a type that holds a date is in ES2015. A bigint would make it throw, and undefined would give undefined. A certificate does not cover a file that calls it. |
a < b, a <= b, a > b and a >= b on strings | JSString.lt a b and JSString.le a b, with the operands swapped for > and >=. JS compares strings by their UTF-16 code units (IsLessThan, ECMA-262 §7.2.13), not by their code points, so "😀" < "\uFFFF" is true. JSString.lt_iff states that lt is Lean's order on the lists of code units. |
a / k, a % k on bigint, where k is a nonzero literal | Int.tdiv a k, Int.tmod a k (both truncate toward zero, as JS does) |
a ** k on bigint, where k is a bigint literal | a ^ (k : Nat). A literal is never negative, so this form never throws. |
const x = BigInt(n) and return BigInt(n), where n is a number | if (JSNumber.toBigInt? n).isNone then throw JSError.rangeError else …, with (JSNumber.toBigInt? n).getD 0 as the value. JSNumber.toBigInt? n is the integer that n is when Number.isInteger(n), exact however large n is, and none otherwise. JS throws a RangeError then, as for 0.5, NaN and Infinity. As for ** below, the call must be the whole value of the declaration or the return, and a local function may not hold it. Tolean refuses BigInt on a bigint or a string, and a declaration named BigInt. It is in ES2020. |
const x = a ** b and return a ** b on bigint, where b is not a literal | if b < 0 then let _ := a ^ (Int.toNat b); throw JSError.rangeError else …, with a ^ (Int.toNat b) as the value. JS throws a RangeError when b is negative, and its message is up to the engine, so JSError.rangeError carries none. The function returns Except. The ** must be the whole value of the declaration or the return, and a local function may not hold it. It is in ES2020. The decision record explains the model. |
a & b, a | b, a ^ b and ~a on bigint | JSBigInt.bitAnd a b, JSBigInt.bitOr a b, JSBigInt.bitXor a b and JSBigInt.bitNot a (tolean/TypeScript/Spec/BigInt.lean). JS applies them to the two's complement of each operand, with as many copies of the sign bit as it needs, so -6n & 3n is 2n. Lean has no such operations on Int, so the model defines them from the ones on Nat. |
a << n and a >> n on bigint | JSBigInt.shiftLeft a n and JSBigInt.shiftRight a n. a << n is a × 2^n. A negative n shifts the other way, and a right shift rounds down, so -5n >> 1n is -3n. Tolean refuses >>>, because JS throws a TypeError for it on bigints. An engine throws a RangeError when a bigint gets too large for it, as 1n << (2n ** 40n) does, and the model has no such limit, as for *. |
{ a, b: e } building a declared interface | structure instance |
{ ...a, f: e }, where a has an interface | { a with f := e }. The spread keeps the keys of a in their order, and each property after it sets a required field in its place, so the object keeps the declared order. { ...a } is a. |
| Call to a function declared earlier in the file | application |
interface Box<T> { readonly value: T }, where the type parameters have no constraint | structure Box (T : Type). Box<bigint> becomes Box Int, and a read of a field has the field's type with bigint for T. An object literal where a Box<bigint> is expected becomes ({ value := … } : (Box Int)). |
type Maybe<T> = T | null | abbrev Maybe (T : Type) := Option T. As for any alias, the output writes the type itself wherever the source names it, so Maybe<bigint> becomes Option Int. |
function f<T>(x: T): T, where the type parameters have no constraint | def f {T : Type} (x : T) : T. A call fixes each type parameter from the types of its arguments, and Lean infers the same types. An argument of T | null may be null, which leaves T to another argument. |
The absent values depend on the declared type:
| TypeScript declaration | Lean type | Null | Undefined | Value |
|---|---|---|---|---|
a: T | null | Option T | none | Not allowed | some v |
a?: T | Option T | Not allowed | none | some v |
a?: T | null | JSNullish T | JSNullish.null | JSNullish.undefined | JSNullish.value v |
The names in the last row are abbreviations, so simp and decide see the underlying options. A missing field and a present field holding undefined are still different objects in JavaScript. Tolean continues to refuse explicit undefined object fields and operations that observe whether the key exists.
An optional nullable field or parameter may have a payload that names a type parameter. A generic certificate requires a codec whose encoding is neither null nor undefined, so the payload cannot collide with either outer state. Concrete aliases are normalized first, so Maybe<bigint | null> has only one null state when Maybe<T> is T | null.
Tests of an optional nullable value preserve the same distinctions. === null matches only null, === undefined matches only undefined, and == null matches either. A loose non-null test narrows to T; a strict non-null test may still leave undefined.
Dictionaries with string keys
Use a Map<string, V> for a dictionary whose keys come from data. A Record<string, V> looks simpler, but a read from it can find a property that the object never set. Every plain object inherits the properties of Object.prototype, so a read with a missing key falls through to them:
ts
function count(counts: Record<string, number>, key: string): number {
return counts[key] ?? 0;
}
count({}, 'apple'); // 0
count({}, 'toString'); // the function Object.prototype.toString, not 0The ?? 0 fallback does not help, because the inherited function is not undefined. The result is not a number, so a Lean function that returns Nat or Float cannot describe it. Map.prototype.get reads only the entries of the map, so m.get(key) ?? 0 gives 0 for every missing key, including 'toString'. When data arrives as a plain object, the caller can convert it once with new Map(Object.entries(obj)) before it calls the translated code.
Tolean still accepts code that keeps a Record<string, V>, but it certifies a read only when it can show that the key is an own property. Guard the read with Object.hasOwn(record, key):
ts
function count(counts: Record<string, number>, key: string): number {
if (Object.hasOwn(counts, key)) {
return counts[key] ?? 0;
}
return 0;
}Object.hasOwn ignores inherited properties, so inside the guard the read finds the own property. An early return works too, and so does a guard bound to a local:
ts
function count(counts: Record<string, number>, key: string): number {
const has = Object.hasOwn(counts, key);
if (!has) {
return 0;
}
return counts[key] ?? 0;
}A guard must be in the same callback or loop body as the read.
The certificate generator refuses an unguarded read with a message that names three fixes: a Map, an Object.hasOwn guard, or a trusted alias.
A key that starts with a literal such as "item:" needs no guard, because no name of Object.prototype starts with that text:
ts
function count(counts: Record<string, number>, id: string): number {
return counts[`item:${id}`] ?? 0;
}The certificate for count has no premise. A prefix that starts such a name, such as `to${id}` or "__" + id, still needs a guard. The key must be written in the read itself, not bound to a local first. See the decision on string-keyed records.
Trusted Records
When you know that a Record never finds an inherited property, say so on its type alias with /** @tolean trusted */. Then reads need no guard:
ts
/** @tolean trusted */
type Counts = Readonly<Record<string, number>>;
function count(counts: Counts, key: string): number {
return counts[key] ?? 0;
}tolean translate prints note: assumes trusted Counts (own keys only), and the certificate of each function that takes a Counts repeats it. The proofs treat a Counts value as an object with no prototype. So the claim is true only for calls where that is true:
- the caller made the object with
Object.create(null), or - its keys can never be the name of an
Object.prototypemember, such as user IDs or SKUs in a fixed format.
Parsing with Zod or TypeBox does not make it true: the parsed object still inherits from Object.prototype. A trusted alias cannot be built with an object literal, and a plain Record<string, V> cannot pass for it. The annotation applies only to an alias of Record<string, V> or Readonly<Record<string, V>>; Tolean refuses it anywhere else. See the decision on trust annotations.
Try and catch
The first catch subset handles explicit errors without restoring changed locals. Both blocks must return or throw, and the try statement must be the last statement of the function or of a returning branch. For example:
typescript
export function recover(failed: boolean, value: bigint): bigint {
try {
if (failed) {
throw new Error("failed");
}
return value;
} catch (ignored) {
return 0n;
}
}The try body allows local declarations with initializers, blocks, if, return and throw new Error(message). Its expressions may be primitive literals, names, parentheses, logical negation and strict equality or inequality. A declaration or a return may also hold bigint a ** b, which throws a RangeError when b is negative. Translation still checks their types and bindings.
A handler may read its binding e only as e.name and as e instanceof RangeError. The handler can catch two kinds of error: the error of throw new Error(m) and the RangeError of **. So e.name is "Error" or "RangeError". TypeScript gives e the type unknown under useUnknownInCatchVariables, so a program that type-checks in strict mode tests e instanceof RangeError before it reads e.name. Tolean does not need that test.
Assignments and calls in the try body remain refused. Calls need an analysis of both captured state and built-in errors before a handler can safely resume with the entry environment. Arithmetic, property access, other constructors and nested try statements in the protected body also remain refused. In particular, an operation that the evaluator represents as no result is not converted into a catchable error.
finally, optional catch bindings, e.message, instanceof tests against other classes and rethrows of the caught value remain refused. The decision record describes the state and error representation work that these extensions need.
Certificates for results of type Except JSError R compare both returned values and thrown errors, which IR.errorVal encodes: an Error with its message, or a RangeError without one. They use the call evaluator instead of the value-only evaluator. Error-class unions still need a certificate encoder. Loops in functions with an Except result need exception-aware loop invariants, including loops whose early return slots carry that result.
Refused forms
Tolean rejects these, among others:
A
throwof anything but a supported error construction. It also rejects a call of a function that can throw where JS may not evaluate it, or evaluates it more than once: in a branch of?:, after&&,||or??, in the test or the update of a countedforloop, or in an arrow function. A call of an imported function that can throw must be the whole value of a declaration or areturn, because the hoisting decides which functions can throw from the file alone and does not follow imports yet. The same holds for a function of the file that can throw only through an imported function. When that file or this one declares error classes, the call is refused, because the two files throw values of two types.new C(args)for an error class anywhere but in athrow, and an error class with a parameter whose type is not primitive.Fractional or unsafe
numberliterals, such as0.5and2 ** 53. It also rejects%onnumber, because no law covers it yet, and the functions ofMathwhose results ECMA-262 leaves to the engine, such asMath.sin./and%onbigint, unless the divisor is a nonzero literal. JS throws an error when the divisor is0n, butInt.tdivreturns 0.tests/typescript/bigintDivision.test.tschecks on random pairs that JS/and%agree withInt.tdivandInt.tmod, andtests/typescript/bigintBitwise.test.tschecks the bitwise operators and**in the same way.**onnumber, because ECMA-262 lets the result differ between engines.new Date(),Date.now(), and a date from a string or from its local parts, such asnew Date(2024, 0, 1), because they read the clock, parse, or read the time zone of the host. The getters of local time, such asgetFullYear, and the setters stay refused too.d.toISOString()is accepted only as the whole value of a declaration or areturn, because it throws aRangeErrorfor an invalid date.JSON.stringifyof a date is accepted, because it never throws: an invalid date becomesnull.tests/typescript/date.test.tschecks the getters,Date.UTCand recognizedDate.parseliterals against Node on random arguments. One kind of argument differs: V8 givesNaNwhen the year passes ±1,000,000, even when the date argument brings the result back into range. ECMA-262 lets MakeDay call such a year out of range, and the model follows its arithmetic, as SpiderMonkey does.===on objects, because in JS it compares references. It also rejects===between nullable values.==and!=anywhere except in a test againstnull. Between two other values they convert their operands, as in0 == "", and the subset does not model that.A test with
nullwhose answer the type fixes, such asx === nullafterif (x === null) return …. The test does nothing, so the code means the same without it. Refusing it keeps every part of the program in the translation, which the proof of the translator relies on. For the same reason Tolean refusesa ?? bwhenacannot benull.A local of type
null, such aslet x = null. Lean would give it the typeOption Empty, which no other value has. Write the type instead, as inlet x: bigint | null = null.x ??= ewherexis aconst, or where its type does not includenull.The global
isNaNandisFinite. These convert their argument to a number first. UseNumber.isNaNandNumber.isFiniteinstead.Assignment to a parameter, a
constor a field, and a push onto an array that the function did not create. Acontinue, abreakor areturnmust end the loop body, or a branch of anifat the top of the body; code after theifmust then go in itselsebranch, if it has one. Areturnin a loop also needs the statements after the loop to end in areturn, so Tolean rejects it in a loop inside another loop or in a branch that changes locals. An assignment to aconstthrows aTypeError, so the interpreter gives no value for a block where a statement after aconstassigns it, and the translator refuses theconst.A read of an owned array anywhere except in the
returnvalue. If code kept an alias, stored the array in a field or looped over it, it would miss a later push. In Lean a push makes a new list, but in JS it changes the shared one. An array literal is safe anywhere else: in JS it makes a new array, and nothing may push to an array that the function does not own. The interpreter checks the same rule for arrays, maps and sets, and gives no value for a function that breaks it. Its check is on names, so Tolean also refuses a function that changes such a collection and has another variable of the same name in a different block. Rename one of them.An arrow function anywhere except as the callback of
map,filter,some,everyandfind, or as a local function in aconst, and a named function as a callback. A callback ofmapmay take the index as its second parameter. The other callbacks take one parameter, and no callback may take the array, which JS passes too. A later step will translate those. The body of a callback must not assign, and for every method butmapit must give a boolean. Tolean also refusesfindon an array of nullable values, because Lean'snonewould stand for bothnullandundefined.A spread anywhere but first in an object literal, a spread of a value that is not of an interface, and a property after a spread that sets an optional field or a tag field. JS appends a key that the spread did not copy, so the order of the keys would differ from the declared one.
A spread in a tuple literal or in the arguments of a call. A spread must also have the array's element type itself, so
[...xs, null]withxsofbigintis refused. Lean converts an element to the type of its place, but it does not convert the elements of a list.A rest element on a tuple, a pattern with more places than its tuple has elements, a pattern on an array of nullable values, and a pattern on the value of a call that can throw. Lean's
nonewould stand for bothnullandundefined, and a call that can throw needs aconstof its own first.includeson an array of objects or of nullable values, and its second argument, the index to start at. On objectsincludescompares references. Tolean also refuses a call of any other array method that takes no callback, such asindexOf.xs.entries()anywhere except where a loop, a spread ornew Mapiterates it, such as inconst it = xs.entries(). An iterator is used up by one pass, so a second loop overitwould visit nothing, and the subset has no model of that.new Set(xs.entries())is refused too, because each value is a tuple, and a set element must be a primitive. Tolean also refusess.entries()on a set.An index of an array of nullable values, and
aton one, because Lean'snonewould stand for bothnullandundefined. Tolean also refuses an index that is not a number, such asxs[0n], and an argument ofator a bound ofslicethat is not a number.slicetakes at most two arguments.reducewithout an initial value, which throws on an empty array, and a callback ofreducewhose value has another type than the initial value.sorton an array that the function did not make in the same expression, such asxs.sort(cmp)on a parameter, becausesortchanges the array that it sorts. Tolean also refusestoSortedandsortwithout a comparator, which compare the strings of the elements, a comparator of any other shape, and a sort of an array of nullable values.A map key or a set element of an interface type, which a map or a set compares by identity. Tolean also refuses
set,addanddeleteon a map or a set that the function did not make withconst m = new Map()orconst s = new Set(), and a read of such an owned map or set anywhere except throughget,hasandsizeor in the return value. It refuses anew Map()ornew Set()without its types,geton a map of nullable values, and every othernew. A declaration namedMaporSetwould hide the global, so Tolean refuses it too. It refuses a loop whose body changes the map or set that it runs over, because the JS loop would also visit the entries that the body adds. A file that uses a map or a set gets no certificate yet, because the certifier has no encoder for one;program_soundcovers it.A counted
forof any other shape, such asi <= n,i--ori += 2, with a start that is not an integer literal, such asaor0.5, or with a type other thannumberoni. Tolean also refuses one whose body assignsior changes something that the bound reads, because JS reads the bound again before each run of the body and the output reads it once. A certificate states a precondition for each counted loop:countUp?on the bound must give a value. The bound must read only function parameters. Aconstlocal bound remains refused. See the decision record.program_soundcovers the loop without this precondition.An array declared with
letand the typeArray<T>. An array that the function pushes to must be aconst; for a value, useReadonlyArray<T>. An empty[]needs a type from its context, and the elements of a literal need one type.A tuple of one element, an empty tuple, named, optional and rest elements, and a
,after the last element. Tolean also refusesreadonlybefore anything but a tuple, such asreadonly bigint[], andreadonly [A, B][], whichtscreads as a readonly array of tuples. An index of a tuple must be a number literal within the tuple. Tolean refuses an index of any value but an array, a tuple or aRecord.===on tuples is refused, because in JS it compares the arrays by reference.A type parameter with a constraint, a default or a modifier, and a
,after the last one. Tolean also refuses a type parameter of a function that no parameter's type names, because a call could not fix it. A generic type named with the wrong number of type arguments is refused, and so is a generic union orRecord: a union of string literals, primitive types or interfaces, and aRecord, become a type of their own, which takes no type parameters. A field may not have the name of a type parameter, because Lean would read the name as the field in the types of the fields after it. For the same reason, a field may not have the name of a type of the file, such as the interface itself, that the type of a later field names. A type parameter may not have the name of a type or function of the file, or of a local, because Lean would read the name as the other one.===on values of a type parameter is refused, because in JS it compares objects by reference.A call to a generic function whose arguments do not fix every type parameter, or fix one to
null, a nullable type or an optional field's type. The output givesT | nullthe typeOption T, soTmay not be nullable itself.A literal union that is not the whole of a type alias, such as
(s: 'a' | 'b'), because the output needs a name for its inductive type. Tolean also refuses a union of string literals and other types, a string that is not an ASCII name or that Lean declares for every inductive type, such as'rec', and a value of a literal union where astringis expected.A numeric enum, an enum member without a value, a
const enum, and an enum inside a function. Tolean also refuses an enum without members, two members with one name or one string, and a member named after a property ofObject.prototype, such as__proto__. In TypeScript a value of a string enum is one of its members, so Tolean refuses a string such as'a'where the enum is expected, and a member where astringis expected. It also refuses the enum's object as a value, and a local with the enum's name.A type guard whose body is not exactly a strict tag test of its one required parameter, or whose true branch is not exactly its annotated type. A guard that recognizes only circles with a positive radius does not make its false branch a square.
A field of a tagged union read before a test of its tag, a read of the tag field outside such a test, and a union of interfaces without a tag. Tolean also refuses a member, such as a
Circle, where the union is expected, except as an object literal. Where a test leaves more than one member, a further test of the same value must come first in the other branch, as in a chain ofif (s.kind === 'a') return …, so that Lean sees onematchthat covers every member.A
switchthat does not test the tag of a tagged union, and fallthrough from a clause with statements into the next: each clause must end inreturn, or each inbreakorthrow. A clause that ends inbreakmay not return, and may not break or continue before its end. A case with no statements is not fallthrough, because it only groups its label with the next clause, so Tolean accepts it. Tolean also refuses adefaultthat is not the last clause, and one that no member can reach unless it assigns the local tonever. It refuses adefaultthat assigns the local toneverwhile a member is left, a first clause that is adefault, a case that an earlier case already takes, an assignment to the local that theswitchtests, and code after aswitchwhose cases cover every member and return.A
constorletat the top of acaseclause, outside braces. The clauses share one scope, so two clauses may not declare the same name, and a clause that runs first cannot read an outer name that a later clause declares. Put the clause in braces:case 'a': { const n = 1n; return n; }.A union of primitive types that is not the whole of a type alias, such as
(x: string | bigint), because the output needs a name for its inductive type. A union of primitive types andnullneeds that name too: declaretype T = string | bigint, then writeT | null. Tolean also refusestypeofanywhere except in the test of anifon a local of such a union, or in a checked guard, against one of its members. So it refusestypeofon a union of interfaces, on a value that may benull, and as a value, as inreturn typeof x === 'string'in a function without a predicate annotation.A
Recordthat is not the whole of a type alias, such as(r: Record<K, V>), because the output needs a name for its structure.Record<string, V>is supported, including inline andReadonlyforms. To certify a dynamic lookup, use a directObject.hasOwn(record, key)guard around the read of that same record and key. The generated link theorem carries an explicit premise that the IR run succeeds. This excludes prototype lookups that the model cannot represent. Certification supports direct function-body guards and local guards inside array callbacks (includingreduce) and loops. Their helper proofs derive ownership from the local guard rather than an external success premise. A guard also covers its branch after other bindings. A negated guard that returns or continues covers the rest, andconst has = Object.hasOwn(r, k)makeshasa guard. Required certificates cover each form over number-valued and optional-valued records. A guard outside a callback or loop body does not cover reads inside it. A read whose key starts with a literal that starts no name ofObject.prototype, such asr[`item:${id}`], needs no guard and no premise. It also refuses other unguarded reads, even with a fallback. Its message names three fixes: use a Map, guard the read withObject.hasOwn, or mark the alias/** @tolean trusted */. See Dictionaries with string keys. Optional-valued Records flattenundefinedfrom a missing property and from an ownundefinedvalue to the same optional result. See the decision on string-keyed records. Tolean also refuses other keys that are not a literal union of strings, index signatures, and a key that Lean reserves, such as'def'. It refuses an index into anything but such aRecord, an index whose key does not have the typeK, and an index in a file that does not declare or importK, because the output names the constructors ofK. Code that needs keys of typestringcan use aMaponce Tolean translates it.An object literal whose fields are not in the order that the interface declares them. A JS object keeps its keys in the order the literal writes them, and a caller can see that order through
Object.keysorJSON.stringify. A Lean structure has no order, so the literal must use the declared one. Code in the subset can only read a field by name, so inside the subset the order never changes a result. That is why Tolean refusesJSON.stringifyon an object.A tag field that is optional, and an optional field with the name of a property of
Object.prototype, such astoString, because an object without the field has that property. Tolean also refusesundefinedas a value unless the context expects an optional value, such as a local or return value typedT | undefined, or the argument of an optional parameter. A literal must leave an optional field out rather than set it toundefined, or to the value of another optional field. JS distinguishes an object without the key from one whose key holdsundefined.JSNullishpreserves the field value but not key presence. An explicitT | null | undefinedunion also remains unsupported. Tolean refuses== nulland=== nullon a plain optional value, and== undefined.A required parameter after an optional one. Expression narrowing tests a local name directly. A test of a property access, and
'x' in obj, remain refused.?.where the value cannot benullorundefined, and optional indexing outside the array, tuple and Record cases above.Optional calls,
f?.(). NeitherSyntax.TypeExprnorTranslate.Tyhas a function type. No accepted parameter, field or variable declaration gives a possiblyundefinedvalue a callable type. A generic type parameter does not make its value callable, and a local function value cannot escape a direct call. There is therefore no accepted program for optional calls to apply to. In a chain such asa?.b.c, Tolean refuses a field before the last that may benullorundefined, because.on it throws.(a?.b).cis not a chain, because the parentheses end it: it reads.cofundefinedwhenaisnull, so Tolean refuses it.A local or a function named
undefined, which would hide the global the subset reads. Tolean also refuses a conditional that combines optional and nullable branches, such asb ? s.f : null. The translator does not yet insert the conversions between those branch types andJSNullish.A
__proto__: vkey in an object literal. It sets the object's prototype, not a field.A function that calls itself on anything but a part of one parameter, the same one in every call, and a call of a function that the file declares later. Without such a part, Lean could not see that the function ends.
A local function anywhere but at the top of the body of the function around it, such as in a loop, in a branch or in another local function. Tolean also refuses a local function that calls itself or the function around it, one that throws, and one without a return type. It refuses one that uses an array, a map or a set that the function around it owns. A state-writing local that returns a value must end with
return. It may return earlier only in guards at the start of its body, and only when its final return is not a changed captured variable, as inreturn total;. A return after any other statement, in a branch with anelse, or inside a loop or aswitchis refused. A sibling call is refused when the callee is declared later, or captures a variable or a sibling that the caller does not itself name. A value-returning sibling caller that changes state only through its calls is refused too. A call of a local function must be a statement of its own, or the whole value of aconst, aletor areturn. So the function never escapes, because no code can return it, store it or pass it on.A function value that escapes, ordinary classes outside the readonly static-dispatch slice above,
async, and exceptions other than the throws above.Imports other than the named imports of Imports.
The files in tests/typescript/corpus/translate/reject/ state in executable form what the translator refuses. To see what that does and does not guarantee, read What is proved and what is trusted.
Map borrows
A function may change Maps that its caller owns. The function must be declared earlier in the same file, or be imported from another file of the project, and contain only set, delete, forwarding calls and const declarations, followed by a final return when it returns a value. Their expressions may read values but call no other function. They may read a map with get and has, read fields such as p.id or m.size, and use operators and ?:. So the usual update m.set(k, (m.get(k) ?? 0n) + delta) is accepted. A branch may test the kind of a union, as in if (p.kind === 'shelf'), or a switch may do so. Each clause of the switch must end with break;, except the last, and a clause of a final switch in a void function may end with return;. A default clause must come last. A clause that declares a local must put it inside braces, as in case 'a': { const v = 1n; m.set(k, v); } break;. A last default that assigns the tested local to never, as in const unhandled: never = place;, checks that the cases cover every member of the union, as it does in an ordinary function. It never runs, and the output leaves it out. A void function that does not qualify fails translation at the statement that stops it, with the list of what a borrowing body may hold. The function reaches the end of its body, optionally through a terminal bare return;. The interpreter executes the checked update prefix before copying out the map, so that return does not discard the final parameter binding.
ts
function change(m: Map<bigint, bigint>, x: bigint): void {
m.set(1n, x);
m.delete(2n);
}
export function f(x: bigint): bigint {
const m = new Map<bigint, bigint>([[2n, 9n]]);
change(m, x);
return m.get(1n) ?? 0n;
}The Lean function change returns the changed map. Its caller writes let m := change m x, so later reads use that map. The interpreter gives the call the same meaning: it copies the argument into the parameter and copies the final parameter binding back. program_sound covers this translation.
The caller may not keep another name or a field that holds the map, or pass the same map in another argument. The call must be a statement at the top level of the caller's body. Its other arguments follow the ordinary expression subset and may not hold the borrowed map. A read-only Map parameter does not become a borrow.
The callee may forward its borrowed map to an earlier borrowing function in the same file. It must pass that map exactly once. For example, function forward(m: Map<bigint, bigint>, x: bigint): void { change(m, x); } passes the final map from change back through forward to its caller. A function forwards only to borrowing functions of its own file, so it may not forward its map to an imported one.
A file may import a borrowing function, also under another name or through a re-export, and call it as it calls its own. The file that declares the function decides which parameters it borrows, and the importing file reads that from the declaring file's interface. In Lean the call names the declaring file's definition, such as _root_.Lib.put m k. Each call rebinds the map, so updates before and after the forwarded call remain visible.
A function may change several Maps. Then every mutable Map parameter must change, and the Lean function returns a tuple of the final maps in parameter order:
ts
function move(a: Map<string, bigint>, b: Map<string, bigint>, k: string): void {
a.delete(k);
b.set(k, 1n);
}Here the caller writes let (a, b) := (move a b k). The caller must pass a different map for each changed parameter. A call such as move(a, a, k) fails translation, because the two parameters would share one map.
A borrowing function may also return a value. Its body is straight-line updates followed by one final return e;, where e does not mention the changed maps:
ts
function bump(m: Map<string, bigint>, k: string): bigint {
m.set(k, 1n);
return 1n;
}The Lean function returns the value first, then the changed maps, and the caller writes let (n, m) := bump m k. The value is bound under a fresh name, result unless the function already uses it. Such a call may only initialize a const or let declaration, as in const n = bump(m, k);. A call in any other position fails translation, as does a void borrow used as a value. An exported function may borrow its own Map parameter in this way.
A borrowing function may throw. It may call a function of the same file that borrows nothing, such as a check that throws on a bad argument, as a statement of its own. That call may not pass a borrowed map. A borrowing function may also forward its map to a borrowing function that throws:
ts
function check(x: bigint): bigint {
if (x < 0n) {
throw new Error("negative");
}
return x;
}
function put(m: Map<bigint, bigint>, x: bigint): void {
m.set(1n, x);
check(x);
m.set(2n, x);
}The Lean function put returns Except JSError (JSMap Int Int), and its caller writes (put m x) >>= fun m =>. A throw ends the caller with the same error. The interpreter does not copy the maps back after a throw. No caller can observe them, because the body of a try may not make a call. A borrowing function that returns a value may throw too. Its caller then writes (bump m k) >>= fun (n, m) =>. A function that borrows nothing must end with a return, so that no call can mistake it for a borrow.
A borrowing function may also change its maps in branches and loops, throw, and return early. An if may test a value that a returned value could be, or its negation with !. Its branches hold set, delete, throw, more such if statements, and for…of loops over an array that is not a borrowed map. A void function may return early with if (c) { …; return; } or if (c) return; at the top of its body:
ts
function put(m: Map<bigint, bigint>, ks: ReadonlyArray<bigint>, x: bigint): void {
if (x < 0n) {
throw new Error("negative");
}
if (m.has(x)) {
m.delete(x);
return;
}
for (const k of ks) {
m.set(k, x);
}
}The spec runs an early return as an else that holds the rest of the body. JavaScript does the same thing here, because the code before the return completes normally or throws.
A branch or a loop may also forward its map to another borrowing function, in a borrowing function and in its caller. The ownership check looks inside if statements, for…of loops and blocks for those calls. A forwarding call may pass computed values too, such as put(m, k, x + 1n).
A function that returns a value may return early too, with if (c) { …; return e; } or if (c) return e;. The spec turns each return e into an assignment to the function's result variable, and moves the rest of the body into an else, so every path that completes assigns the result last.
A loop in a borrowing function may break and continue. The output's forIn stops with ForInStep.done or goes on with ForInStep.yield, and the maps travel in its state either way.
A void function may also return; inside its final loop, when no statement follows that loop. The spec runs that return as a break, because stopping the loop ends the function either way. A return in a nested loop would stop only the nested loop as a break, so it stays refused.
Some cases remain refused. Any other return inside a loop is refused, and only for…of loops are accepted. Imported borrows remain refused, and borrowing functions receive no per-file certificate. Optional parameters and generic borrowing functions remain refused too. The certifier also refuses borrowing functions: its link proof does not yet describe the final map as the function's result.
Indexed access types
An indexed access type such as Shape['kind'] resolves to the type of that field. The receiver must resolve to a known interface or object type, which may be imported or named through a type alias. Nested access such as Envelope['shape']['kind'] repeats the lookup. Optional fields retain undefined in their type.
An anonymous literal union in an interface field remains refused because the translator needs a name for its Lean inductive type. Declare that union as a named type:
ts
export type Kind = 'circle' | 'square';
export interface Shape {
readonly kind: Kind;
readonly size: number;
}
export function hasKind(s: Shape, kind: Shape['kind']): boolean {
return s.kind === kind;
}Only a literal string key is supported. Unions of keys, keyof and numeric keys remain refused. A missing field is an error. An unconstrained generic receiver such as T['kind'], a union receiver, and a nullable or optional intermediate receiver are also refused because they do not resolve to one known structure. This feature concerns type annotations, not runtime array indexing. The decision record describes the static lookup and its proof coverage.
Indexed access to a single-literal tag field, such as interface Circle { readonly kind: 'circle' }, also remains refused. The translator stores that tag as field metadata rather than an ordinary value type, so it cannot safely reuse that representation for a parameter. Use a named literal-union type for the field instead.
Numbers
A JS number is an IEEE-754 double. Tolean does not map it to Lean's Float, because then the code would run in Lean, but you could not prove anything about it. Lean's Float is an opaque wrapper around C doubles. Its operations are extern functions that come with no lemmas, so even (1.0 : Float) + 1.0 = 2.0 has no proof without native_decide. You could prove only facts that hold for any type, such as "the result is one of the inputs".
Aeneas has the same problem with Rust's f64, and it does not support floats yet (AeneasVerif/aeneas#828). The discussion there shows two ways that things go wrong. First, float literals and arithmetic fail to translate. Second, code that only passes an f64 along translates to a Lean type F64 that the Aeneas library never defines. Because Lean's autoImplicit option is on by default, that name silently becomes a type variable. One proposed fix maps f64 to Lean's Float. With that fix the code runs, but you still cannot reason about the arithmetic.
Tolean takes a different approach. Every definition that uses number is generic over an abstract number type N, which has the operations of the JSNumber class in tolean/TypeScript/Spec/Number.lean. Proofs can use this at three levels:
Nothing assumed. A theorem that you prove for every
Nalso holds for real doubles. This level is enough for facts that do not depend on arithmetic.Safe integers.
toSafeInt : N → Option Intreturns the integer that a value is, whenNumber.isSafeIntegerholds for it.SafeIntLawsstates two facts about safe integers. JS arithmetic on them is exact as long as the result stays in range, and comparison on them agrees withInt. Division is exact when the divisor divides the dividend.Math.floorand its relatives leave a safe integer as it is, andMath.minandMath.maxagree withminandmaxonInt. A theorem that needs this takes[SafeIntLaws N]and hypotheses such astoSafeInt x = some i. Then it reasons overInt.NaNand±Infinity.isNaN,isFinite,nan,posInfandnegInfmodelNumber.isNaN,Number.isFinite,NaNand±Infinity.SpecialValueLawsstates how they behave.===is symmetric, and it is reflexive for every value exceptNaN, sox !== xtests forNaN.NaNfails every comparison and spreads through arithmetic and the functions ofMath.±Infinitybound every finite number, andInfinity - InfinityisNaN. Every finite number has an integer part,toInt, which is its truncation toward zero, andNaNand±Infinityhave none. SoJSNumber.toIndexInt, the index thatatandsliceread from a number, is what JS reads for every model that satisfies the laws. A theorem that needs these facts takes[SpecialValueLaws N].NumberOrderLawsstates the order laws for numbers that are notNaN. Both strict comparison and its negation are transitive, and JS equality holds exactly when neither value is less than the other. This treats positive and negative zero as equal. For finite operands, subtraction never givesNaN, and its sign agrees with their order, even when the difference overflows to an infinity. These laws are hypotheses, andjsNumberLaws.test.tschecks each one on the maintained Node lines. The certifier uses these laws for direct comparison and difference sorts of a list parameter, under the input hypotheses described above.
The laws are hypotheses, not Lean axioms. If one of them were false, the theorems that use it would not apply to JS. But Lean would stay consistent, and every other theorem would still stand.
Lean cannot check facts about the JS engine. Instead, tests/typescript/jsNumberLaws.test.ts checks each law against real doubles, including the range limits, ±0, subnormal numbers, NaN and ±Infinity. Each check records the exact Lean statement that it was written for, so nobody can change a law without also changing its check.
tolean/TypeScript/Spec/Lemmas/Number.lean contains facts that we proved from the laws, and any project can reuse them. Examples are reflexivity on safe integers and eq a a = !isNaN a. These facts assume nothing new, so they need no audit.
Versions
Each translation is for one target, which is the ECMAScript edition that the code runs on. Tolean translates the source as it runs, because type stripping keeps the syntax unchanged. This means the engine must support every feature that the code uses. It also means that the translation must assume the meaning that the target edition specifies.
sh
tolean translate --target ES2022 input.ts Output.lean My.NamespaceThe target can be any edition from ES2015 to ES2025. The default is ES2024, because that is what Node 22 supports, and Node 22 is the oldest release line that is still maintained. We add a new edition only after we review what it changed.
tolean/TypeScript/Edition.leanlists each JS feature that Tolean relies on. For each feature, it gives the first edition that specifies it and the ECMA-262 production or operation that defines it. It uses names instead of section numbers, because section numbers move between editions. The parser and both translators refuse a feature that is newer than the target, and they all give the same message:Feature Since **,**=ES2016 object spread ( { ...p })ES2018 bigint (literals, type, + - *, comparisons)ES2020 bigint /and%(BigInt::divide,BigInt::remainder)ES2020 bigint **and the bitwise operators (BigInt::exponentiate,BigInt::bitwiseANDand the others)ES2020 bigint **with an exponent that is not a literal, which throws aRangeError(BigInt::exponentiate, NativeErrorRangeError)ES2020 e.nameande instanceof RangeErroron a catch binding (Error.prototype.name,NativeError.prototype.name,InstanceofOperator)ES2015 BigInt(n)on a number (the BigInt constructor, NumberToBigInt)ES2020 d.toISOString()(Date.prototype.toISOString, the Date Time String Format)ES2015 JSON.stringifyof aDate(Date.prototype.toJSON)ES2015 ??ES2020 ?.ES2020 &&=,||=,??=ES2021 numeric separators ( 1_000)ES2021 The number laws hold in every edition. If a later edition changes how something behaves, we add a new feature for the new meaning. We never give one feature a second meaning.
Every generated file starts with the Tolean release and the target, for example
-- Generated by tolean 0.3.1 for ES2024 from x.ts.That way, the drift check notices when either one changes. A change to the meaning of a law is a major release. A new law, model or feature is a minor release.We test the laws on every engine listed in
enginesinflake.nix, which are Node 22 and Node 24. Runnix run .#test-engines. A law holds only for the engines that it passes on.
The npm package
npm/ is the tolean package on npm. It contains the tolean command, the translateSource and translateWorkspace functions, and the Lean runtime in lean/. All of them run the native tolean binary for the platform, which .github/workflows/release.yml builds with Lean's own toolchain for each platform that Lean supports. Each binary is its own package, such as @tolean/darwin-arm64, and npm installs only the one for the platform. To run another binary, such as one that Lake built, set TOLEAN_BINARY to its path. translateSource returns a promise, because it runs the binary as a child process. The package's README is this repository's README, which the npm build copies with each relative link made absolute.
sh
tolean <input.ts> <output.lean> <Lean.Namespace>Generated code that uses number imports tolean.TypeScript.Spec.Number. Loops that can return import tolean.Runtime.LoopResult. Both modules ship in the npm package's Lean runtime. The loop helper is language-neutral because every language that prints a returning fold uses the same carrier. To use it, require the runtime by path:
toml
[[require]]
name = "tolean"
path = "node_modules/tolean/lean"What is proved and what is trusted
| Step | What happens | Status | How it is checked |
|---|---|---|---|
| 1. Parse and type-check | Tolean's parser reads the source, and the translator types the subset itself | Trusted, tested | tests/typescript/check.ts compares the parser's syntax trees with tsc's, on the corpus and on random programs. It also prints each tree as source and requires the parser to read it as the same tree. parseChars_reads proves this second check for every tree that the parser gives. The proof shows that the parser and the printer agree, but not that the parser reads TypeScript as tsc does. The type checker is tested through the translation corpus. |
| 2. Translate | Tolean writes readable Lean definitions (the generated .lean files) | Proved up to the printer | program_sound proves the translation to the Tolean IR for every accepted program: when the IR's evaluator gives a value, the interpreter gives the same value. The printer link is trusted: that the printed Lean computes what the evaluator gives for the IR, and that the evaluator gives a value where the printed Lean does. No theorem can state it for every program, because the printed Lean is text that means something only after Lean compiles it. The golden files of the corpus, compiling random programs and the CI drift check test it, and a certificate proves the link, and so the whole step, for one file. |
| 3. Prove the claims | Hand-written proofs show that each claim in Spec/*.lean holds for the generated definitions | Proved | The Lean kernel, #audit_claims, lake build --wfail, and no sorry, admit, axiom or native_decide |
| 4. Assume JS number facts | SafeIntLaws, SpecialValueLaws and NumberOrderLaws in tolean/TypeScript/Spec/Number.lean | Trusted, tested | tests/typescript/jsNumberLaws.test.ts checks each law against real doubles. |
| 5. Run | Type stripping or a bundler makes the JavaScript that Node runs | Trusted | The subset uses only constructs that type stripping leaves unchanged, except enum. Type stripping refuses an enum, so code with one needs tsc, a bundler or Node's --experimental-transform-types. The interpreter reads an enum as the object that tsc makes for it. |
| 6. Inputs | The code that calls the verified functions passes inputs that meet the theorems' preconditions | Trusted | The callers are responsible for it. A function can check its own inputs instead, so that its claim has no precondition, and a plan lets tolean.json require that. |
So a theorem holds for the code that runs if steps 1, 4 and 5 are correct, the printer of step 2 is correct or the file has a certificate, and the inputs meet its preconditions. These goals are not built yet:
| Goal | Purpose | Today |
|---|---|---|
| The parser against the grammar | Prove that the parser reads TypeScript as the language's grammar does, so that step 1 stops being trusted. The round trip proves only that the parser and the printer agree. | Not started. tests/typescript/check.ts tests the parser against tsc. |
| The interpreter from a formal semantics | Derive eval from a formal semantics of ECMA-262, so that it stops being a trusted specification | Not started. tests/typescript/interpreter.test.ts tests it against Node. |
This page is docs/typescript/README.md at commit 5f1d031.
