ECMA-262 in Lean

From spec.html to a specification in Lean, and to an engine that runs it

How it works

The specification is read in two ways. Its algorithms, tables, early errors and grammars are generated from spec.html as data, and a machine defined once runs that data. What the algorithms take for granted, the values and the host, is stated as laws that quote the text.

The whole

lean/Ecma: the specification layer spec.html tc39/ecma262 at b1eaed82f The overlay 27 files of readings 38 errata Generator in Rust lean/Ecma/Gen 169 modules: algorithms lean/Ecma/Grammar/Gen 16 modules: grammars Lower code to run The model the values 116 laws, quoted The machine one transition Machine.step The host 72 laws, quoted the errata's readings: a parameter of the machine The engine: lean/Engine a model and a host of its own, a parser, shortcuts theorem Engine.implements: it implements the specification Lean's 3 standard axioms trusted; 55 pins checked at run time implements The debugger: ecma-dbg the machine, paused at its steps test262 TC39's tests, run on ecma-run
spec.html is used unchanged; the overlay adds readings in the text's own notation. The generator writes the generated modules, which are never edited by hand. The machine, Lower, the model's and the host's laws are written by hand in lean/Ecma, every law quoting the sentence it reads, and nothing there fixes a model or a host. The engine is one model and host, proved to implement the specification; the debugger and test262 run it.

From the text to data

The specification's own source, spec.html, is pinned at a revision of tc39/ecma262 and used unchanged. What every generator, check and page reads is the text (spec/proposals.txt, scripts/spec_text.py): spec.html itself, or spec.html with the TC39 proposals that file names merged into it (Applying a proposal shows one applied). A generator written in Rust parses every algorithm step, algorithm body, equation, early-error rule and table into data, and writes that data as Lean modules: one module per clause in lean/Ecma/Gen, and the grammars in lean/Ecma/Grammar/Gen. These files are never edited by hand.

The generator checks itself: printing the data it parsed gives back the HTML's text, for every step, body, equation, early-error bullet and table. The Lean side has a printer of the same notation (Ecma.Print, in lean/Ecma/Notation/Print.lean), and scripts/bijection.py checks that every generated item prints back to spec.html or the overlay byte for byte.

The overlay

Some of the text is prose a machine cannot run as it stands: a phrase such as "the String value whose code units are …", or a step that says what to find rather than how. The overlay (spec/formal/*.emu, 27 files) gives each such phrase or step a reading, written in the specification's own algorithm notation, attached to the clause and step it reads. The generator reads the overlay with spec.html; a reading becomes part of the data beside the text it reads, and the text itself is kept.

Numbers that stay put

The generated data names what it refers to by number: a clause or algorithm, a syntax-directed operation, an erratum, a production, a nonterminal, a table, a sort, a phrase, a field. The numbers are kept in tables in the repository, 15 files under spec/formal (clause-ids.txt, enum-ids.txt, erratum-ids.txt, field-ids.txt, method-ids.txt, note-ids.txt, nt-ids.txt, param-ids.txt, phrase-ids.txt, prim-ids.txt, prod-ids.txt, reason-ids.txt, sdo-ids.txt, sort-ids.txt, table-ids.txt). The generators read them: an entry met before keeps its number, a new one takes the next unused number, and one the text no longer has keeps its number, marked retired. So a change to the text changes only the generated modules that hold the change: a new clause or production renumbers nothing else, and a hand-written proof that names an algorithm by its number still names the same algorithm after the text moves on.

What lean/Ecma may hold

The specification layer, lean/Ecma, holds three kinds of thing and nothing else:

  1. What is generated from the HTML: the algorithms, tables, early errors, grammars and the starting realm.
  2. What the notation means: the machine that runs an algorithm's steps, and the primitives of the notation (§5.2: Let, Set, If, Repeat, Assert, the ? and ! shorthands).
  3. Requirements that quote their sentence: the laws of the model and of the host. A law is never stricter than the sentence it reads where the text is deliberately permissive, and never vacuous. Where a law is stricter, it goes on a list of proposed normative changes.

lean/Ecma has 17,566 hand-written lines in 81 files outside the generated directories. It holds definitions and stated laws only: no theorems, no tactics, and no partial or unsafe definitions (scripts/quick_check.py checks this).

From data to a machine

The data is the text's structure, and it does not yet run. lean/Ecma/Lower turns it into the program the machine runs: macros such as IfAbruptRejectPromise are expanded into the steps they "mean the same thing as"; each phrase becomes a call of its reading; the few steps that say what to choose ("Let n, k, and s be integers such that …") become steps that compute the choice; and each algorithm is written as linear code with its step numbers kept, so that every step the machine takes can be named by its clause and step.

lean/Ecma/Machine is a small-step machine over that code. Its configurations are the frames of the calls in progress, each with its algorithm, its Parse Node, its variables and the step it is at. One transition (step) is defined once, for every model and host. A run is a sequence of transitions that ends (Machine.Runs).

The model and the host

The machine is stated over two parameters, and the specification layer fixes neither.

The model (Ecma.Model) gives each sort of the specification a carrier and its operations: mathematical values, Numbers, BigInts, Strings, Symbols, Parse Nodes, Lists, Data Blocks, CharSets, Records, property tables and the store. Its laws (Model.Laws, 116 laws, among them num, which holds the 12 laws of Numbers, and bytes, which holds the 9 laws of Data Blocks) say what the text assumes of them, for example that mathematical values are an ordered field and that Number arithmetic is IEEE 754-2019 binary64 with roundTiesToEven.

The host (Ecma.Host) answers every host-defined and implementation-defined operation, by clause, and every choice the text leaves to the implementation, by primitive. Every call of the host is logged, and its 72 laws (Host.WF) constrain what one call may answer given the state and the log before it: that a timeout job runs after at least its delay, that promise jobs run in the order they were scheduled, that Date.now answers a time value.

Each law's documentation names its clause, quotes the governing sentence, and gives a one-line reading. scripts/law_quotes.py checks every quotation against the pinned spec.html. The reading pages set each law with its sentence first: see timeoutAfter for an example.

Readings and errata

Where the text as written cannot be followed (an Assert that can fail, a case no step covers, a phrase that names a node the parse does not have), the overlay records an erratum: the text's place, and the readings that resolve it. There are 38 (spec/formal/errata.txt): 36 defects of the text and 2 proposed normative changes. An erratum's readings are the text as written (literal), the reading test262's tests require (test262), and a proposed fix (proposed). The default is per erratum: 21 read as test262 requires, 12 literally, 4 as proposed, and 1 whose resolution is not yet decided, which the machine reads as proposed until it is.

29 errata are switched in the specification at run time: ecma-run --reading literal reads every erratum literally, and --erratum Name=literal one of them; the proofs hold for every choice of readings, which are a parameter of the machine. 5 are switched only in the engine's parser (the specification's grammar has the test262 reading), and 4 have one reading. A program run under the literal text stops at the exact step where the text cannot be followed. Read literally, 3 errata stop nearly every program before it runs, so the debugger's build of the literal text keeps them, CreateIntrinsicsAsyncArgument, StringValueReservedWord and CoveredNodeParent, at their default reading. The errata page quotes each erratum's sentences and readings, and runs a program for each one that has one.

The engine

lean/Engine is one concrete model of the specification: exact mathematical values, binary64 Numbers, UTF-16 Strings, arrays for Lists and the store; a parser over the generated grammars; a host with jobs, agents, modules and test262's $262; and shortcuts for particular algorithms, each proved to agree with the algorithm's steps. It has 11,170 lines outside its proofs, and 20,321 lines of proofs.

The engine runs whole programs as ecma-run (a script, a module, or a bundle made by ecma-bundle), runs test262, and drives the step debugger ecma-dbg (3,586 lines), which pauses at the specification's steps as a program runs. What is proved says exactly what the proofs establish about it.

One clause, end to end

§7.2.3 IsCallable is three steps. This is spec.html's text:

§7.2.3 IsCallable ( arg )
  1. If arg is not an Object, return false.
  2. If arg has a [[Call]] internal method, return true.
  3. Return false.

The data. The generator writes the clause as one Lean value of type Alg, a definition of the module for §7.2 that nobody edits:

-- lean/Ecma/Gen/S7_2.lean, in namespace Ecma.Gen.S7_2/-- sec-iscallable (§7.2.3) -/def «IsCallable» : Alg := {  id := ⟨219, 0⟩  name := "IsCallable"  header := { kind := .ao, params := [{ x := 0, ty := (some (.sort "an" [] 14 "")), optional := false, rest := false }], ret := (some (.sort "a" [] 3 "")), recv := none, desc := [.text "It determines if _arg_ is a callable function with a [[Call]] internal method."] }  vars := #["arg"]  attrs := []  indent := 6  body := [(.mk [] (.if_ (.preds (.var 0) (.isTy true .or [(.sort "an" [] 6 "")]) []) (.inline (.ret (some (.val .false)))) [] none)), (.mk [] (.if_ (.preds (.var 0) (.phrase 43 [(.w 0), (.e (.fieldName 45))]) []) (.inline (.ret (some (.val .true)))) [] none)), (.mk [] (.ret (some (.val .false))))]  closures := #[] }

Each step is a term of the notation's syntax, and each number in it comes from a kept table: the algorithm's id ⟨219, 0⟩ is clause 219 of clause-ids.txt, sec-iscallable; sort 6 of sort-ids.txt is Object, so step 1's test reads "is not an Object"; step 2's condition is phrase 43 of phrase-ids.txt, has-method, applied to the variable arg and field 45 of field-ids.txt, [[Call]]: "has a [[Call]] internal method".

A step of the machine. Lower turns the body into the code the machine runs, with its step numbers kept. When EvaluateCall reaches "If IsCallable(func) is false", the machine pushes a frame for algorithm 219 with arg bound to the callee. Each transition, Ecma.Machine.step, advances the top frame by one step: at step 2 it evaluates the condition on the callee's object in the store and either returns true to EvaluateCall's frame or goes on to step 3, which returns false. Every configuration names its clause and step, which is what lets the engine's theorem compare the engine's transitions with these, one configuration at a time.

In the debugger. The example IsCallable, step by step calls a function and an ordinary object: the debugger pauses at IsCallable step 2 for the function and at step 3 for the object, with IsCallable over EvaluateCall in the spec stack, the step's text, and the value of arg.

Sizes

PartFilesLinesWritten by
lean/Ecma/Gen16948,079the generator
lean/Ecma/Grammar/Gen1610,014the generator
lean/Ecma, the rest8117,566hand
lean/Engine, outside its proofs6211,170hand
lean/Engine/Proofs7020,321hand
lean/Debugger103,586hand
spec/formal/*.emu, the overlay279,058hand

Lines are counted in this commit's sources. Not counted: lean/Ecma/Unicode/Gen and the Unicode library, which hold the Unicode Character Database's tables.