ECMA-262 formalized in SpecTec, bijective with spec.html, compiled and proved in Lean
How it works
The specification lives in SpecTec (spec/spectec/) in two parts: structured SpecTec for ECMA-262's algorithms, grammars, early errors and tables (bijective with spec.html), and prose SpecTec modules for its abstract sorts, grammar and §29 memory relations, and the 246 model, parser, memory-model and host laws that quote the English text. Everything else — the Lean specification semantics, the proved reference engine, and the WebAssembly debugger — is downstream of SpecTec.
The whole
spec.html and structured SpecTec are checked against each other by spectec-html with zero byte diffs; prose SpecTec states the abstract sorts, relations and quoted laws. lean/SpecTec (spectec) compiles SpecTec into Lean, where the concrete engine is proved to implement the specification and drives both the debugger and test262.The specification in SpecTec
SpecTec (spec/spectec/, 62 files) is the human-readable formal representation of ECMA-262 in this repository, expressing the specification directly in typed declarations:
- Declarations (
00-decls.spectec): Every specification clause (clause @sec-…, including named phrase helpers@ph-…), internal slot and Record field (field [[…]]), specification constant (enum ~…~), Record and object sort hierarchy (syntax Name defined { super […] record … }), internal method signature (method [[…]]), syntax-directed operation (sdo Name), and editorial notation primitive (extern def $Prim). - Grammars and early errors (
01..08-*.spectec): All six ECMA-262 grammars — numeric string, lexical, syntactic, RegExp, Annex B and JSON — written asgrammar <kind>andrule <kind> |Nonterminal|[Params] :: { | … }with parameter guards ([+Await],[~Yield]),but notexclusions,[lookahead …]restrictions and[no LineTerminator here], followed byearly_errorrules,09-tables.spectec, and the intrinsic realm definition in10-realm.spectec. - Clause algorithms (
clauses/*.spectec, 25 modules): Every abstract operation (kind ao), built-in function (kind builtin), syntax-directed row (kind sdo) and internal method (kind method) as a typeddef @sec-… "Name" (kind … params […] -> …) vars […] { … }block (1,627 definitions in all). Steps use structured control flow (let,set,if/else_if/else,repeat_while,for_each,perform,return,throw,assert), explicit?and!completion unwrapping, type tests (is ty {Object},is val {~empty~}), slot accesses (x[[Slot]]), and calls to@sec-…clauses or$Primprimitives.
Bidirectional bijections: spec.html ↔ SpecTec ↔ Lean
The specification's source, spec.html, is pinned at a revision of tc39/ecma262 (with any active proposals from spec/proposals.txt merged by scripts/spec_text.py (Applying a proposal shows one applied)). Three automated round-trips keep spec.html, SpecTec, and the downstream Lean representation locked together:
spec.html↔ SpecTec (spectec-html check,lean/SpecTec/Html): Using four small presentation tables inspec/html/(English call templates, grammar attributes, clause headers, and step patches),spectec-htmlrenders every SpecTec grammar block, algorithm, equation and early-error rule back into ecmarkup HTML and splices them intospec.htmlwith zero byte diffs.- SpecTec ↔ SpecTec (
spectec roundtrip): Every.spectecfile — structured and prose alike — is parsed into SpecTec's AST and pretty-printed back byte for byte. - SpecTec ↔ Lean (
spectec emit&ecma-print,lean/Tools/SpecPrint):lean/SpecTeccompilesspec/spectec/into gitignored Lean modules, andecma-printprints all 36 structured.spectecfiles back from those compiled definitions and verifies them byte for byte.
Symbolic names and sorted declarations
In SpecTec, everything is written by name (@sec-iscallable, [[Call]], ~start+end~, |IdentifierName|). When lean/SpecTec emits Lean code for the machine and proofs, it collects all declared and referenced names across each namespace in spec/spectec/, sorts them lexicographically (0..N-1), and generates symbolic constants in Ecma.Known. Because downstream Lean code references symbolic names rather than raw numbers, editing a clause or applying a proposal stays local to the changed SpecTec definitions.
Prose concepts in SpecTec: syntax, relation and laws
Algorithms and grammars are only half of ECMA-262: §5.1, §6, §9, §21 and §29 state in English prose what values are, how grammars derive parse trees, how shared memory behaves, and what a host environment may do. Those prose sections are formalized in 26 SpecTec modules under spec/spectec/prose/ (4,304 lines) using four declarations:
syntax(abstract sorts, records and variants):Ecma.Modeldeclares the abstract carriers and operations of every specification sort (mathematical values, IEEE 754 binary64 Numbers, BigInts, UTF-16 Strings, Symbols, Parse Nodes, Lists, Data Blocks, CharSets, Records, property tables and the store) without fixing any implementation;Val,CellandHostdefine runtime values, store cells and the host interface over anyModel.relation(inductive inference rules): Declarative specifications such as §5.1 grammar derivations (Grammar.Derives), the correspondence between abstract Parse Nodes and derivation trees (Model.NodeRel), and §29 candidate-execution orders (MemoryModel.HB) are written as Horn-style inference rules (rule name : Conclusion :- Premise1, Premise2;).laws(axiomatic requirements quotingspec.html):Model.Lawsand its companion blocks (148 laws: 116 core, 12 for Numbers, 9 for Data Blocks, 7 for Unicode, and 4 for Parse Node parents),Model.ParseLaws/Model.CoverLaws/Model.NodeLaws(7 laws for parsing, covers and Parse Nodes),MemoryModel.ValidWith(19 laws for §29 candidate executions and shared reads), andHost.WF(72 laws across 10 topics, constraining host hooks and choices over the host-call log) state what any conforming model, parser and host must satisfy. Everylawbegins with a--- sec-id:docstring quoting the governing sentence ofspec.htmland giving a one-lineReading:, checked againstspec.htmlbyscripts/law_quotes.py(seetimeoutAfter).def(pure specification helpers): Total helper functions overModelandStateused to state relations and laws cleanly, with no tactics, proofs orpartialrecursion.
Specification decisions and errata
Where ECMA-262 as written is contradictory, incomplete, or disagrees with every engine and test262, SpecTec resolves each ambiguity directly in spec/spectec/ with no command-line errata switches. Every such choice is documented in spec/DECISIONS.md, including 57 active specification errata and proposed normative changes (54 defects of the text and 3 proposed normative changes): 33 bake in the reading test262 requires, 13 bake in a proposed fix, and 11 keep the literal wording so that reaching a broken Assert: stops at the exact offending step. Spec issues & errata quotes each entry's sentences and alternative readings, tracks upstream issues and PRs, links to its long-form write-up, and verifies a demonstration program where one applies.
Downstream: the small-step machine and proved engine
Everything under lean/ is pure Lean 4, consuming the compiled SpecTec specification:
- Specification semantics (
lean/Ecma):lean/Ecma/Lowerexpands editorial macros such asIfAbruptRejectPromiseand linearizes SpecTec algorithm bodies while preserving step paths;Ecma.Machine.stepdefines one small-step transition over call frames for anyModelandHost(Machine.Runs); andEcma.Implementsstates what it means for an implementation to conform.lean/Ecmacontains zero theorems, tactics,partialdefs orunsafecode (scripts/quick_check.py). - Reference engine and proofs (
lean/Engine): Concrete carriers (exact rationals, IEEE 754 binary64, UTF-16 arrays, a chunked store), a proved parser over all six SpecTec grammars (Engine.Claims.parseLaws,Engine.Claims.coverLaws,Engine.Claims.nodeLaws), a concrete host with jobs, agents, modules and$262, and verified fast-path shortcuts (12,291 lines of implementation, 57,206 lines of proofs). It runs JavaScript programs and test262 asecma-run, and What is proved explainsEngine.implementsandEngine.run_sound. - Interactive step debugger (
lean/Debugger): Drives the specification machine forward and in reverse asecma-dbg(4,165 lines, native and WebAssembly compiled directly from Lean IR bywasm-emit), pausing on clauses, step paths, throws andAssert:stops. - SpecTec compiler & standalone tools (
lean/SpecTec,lean/Tools):spectecandspectec-html(15,245 lines, zeroEcmaimports) parse, round-trip, emit and splicespec/spectec/↔spec.html;lean/Tools(12,457 lines) providesecma-print(SpecTec ↔ Lean bijection),ecma-typecheck(static modular spec typechecker),test262-runner, andwasm-emit(directLean.IR→wasm32compiler).
One clause, end to end
§7.2.3 IsCallable is three steps in spec.html:
§7.2.3 IsCallable ( arg )
- If arg is not an Object, return false.
- If arg has a [[Call]] internal method, return true.
- Return false.
In SpecTec. Clause §7.2.3 lives in spec/spectec/clauses/S07.spectec as a five-line def:
--- spec/spectec/clauses/S07.spectecdef @sec-iscallable "IsCallable" (kind ao params [arg : #"ECMAScript language value"] -> Boolean) vars [arg] { if arg is not ty {Object} -> return false if arg sat $HasMethod([[Call]]) -> return true return false}
Every part of the clause is explicit and readable by name: @sec-iscallable identifies the clause (mapped to sorted ClauseId 1364 when emitting Lean), kind ao marks an abstract operation taking arg of sort #"ECMAScript language value" and returning Boolean, step 1 tests arg is not ty {Object}, and step 2 checks arg sat $HasMethod([[Call]]) before step 3 returns false. Running spectec-html renders those three steps back into spec.html's exact ecmarkup.
A step of the machine. Downstream, Lower compiles the body with its step numbers preserved. When EvaluateCall reaches IsCallable(func), the small-step machine pushes a frame for @sec-iscallable with arg bound to the callee; Ecma.Machine.step checks whether the callee is an Object in the store, inspects its [[Call]] internal method at step 2, and returns true or advances to step 3.
In the debugger. The example tests/run/iscallable.js calls both a function and an ordinary object: the debugger pauses at IsCallable step 2 for the function and step 3 for the object, displaying IsCallable above EvaluateCall in the spec stack alongside the value of arg.
Sizes
| Part | Files | Lines | Role |
|---|---|---|---|
spec/spectec/ (structured) | 36 | 55,936 | SpecTec declarations, grammars, early errors, tables & clause algorithms (bijective with spec.html) |
spec/spectec/prose/ | 26 | 4,304 | SpecTec prose modules: Model, Host, derivations, §29 memory & 246 quoted laws |
spec/html/*.txt | 4 | 19,907 | ecmarkup presentation templates & metadata for spectec-html |
lean/Ecma (hand-written) | 70 | 9,570 | downstream small-step machine, lowering & Implements contract (Gen/ is gitignored) |
lean/Engine (outside proofs) | 63 | 12,291 | concrete VM model, parser, host & shortcuts |
lean/Engine/Proofs | 85 | 57,206 | conformance & parser proofs (Engine.implements, Engine.run_sound, Engine.Claims.parseLaws, Engine.Claims.coverLaws) |
lean/Debugger | 10 | 4,165 | step debugger (ecma-dbg, native & Wasm) |
lean/SpecTec | 21 | 15,245 | standalone SpecTec compiler & spec.html bijection (spectec, spectec-html) |
lean/Tools | 20 | 12,457 | standalone tools (ecma-print, ecma-typecheck, test262-runner, wasm-emit) |
Lines are counted in this commit's tracked sources. Gitignored outputs (lean/Ecma/Gen: 108 modules, 42,287 lines; lean/Ecma/Grammar/Gen: 16 modules, 6,391 lines) are generated from spec/spectec/ by scripts/generate.py. Not counted: Unicode Character Database tables.