ECMA-262 in Lean
1 / 15
← → step · Esc exit

Executing spec.html

Formalization's time has come

Architecture

spec.html SpecTec HTML bijection Lean 4 Engine Debugger

The Spec: Algorithms

spec.html §7.1.4 ToNumber ( arg )
<emu-clause id="sec-tonumber" type="abstract operation">
  <h1>ToNumber ( _arg_: an ECMAScript language value ):
      either a normal completion containing a Number or a throw completion</h1>
  <emu-alg>
    1. If _arg_ is a Number, return _arg_.
    1. If _arg_ is either a Symbol or a BigInt, throw a *TypeError* exception.
    1. If _arg_ is *undefined*, return *NaN*.
    1. If _arg_ is either *null* or *false*, return *+0*<sub>𝔽</sub>.
    1. If _arg_ is *true*, return *1*<sub>𝔽</sub>.
    1. If _arg_ is a String, return StringToNumber(_arg_).
    1. Assert: _arg_ is an Object.
    1. Let _primitiveValue_ be ? ToPrimitive(_arg_, ~number~).
    1. Assert: _primitiveValue_ is not an Object.
    1. Return ? ToNumber(_primitiveValue_).
  </emu-alg>
</emu-clause>
spec/spectec/clauses/S07.spectec
def @sec-tonumber "ToNumber" (kind ao
  params [arg : #"ECMAScript language value"]
  -> completion<Number> | #"throw completion") vars [arg, primitiveValue] {
  if arg is ty {Number} -> return arg
  if arg is ty {Symbol; BigInt} -> throw @ph-new-error([[TypeError]])
  if arg is val {undefined} -> return nan
  if arg is val {null; false} -> return num_f(+0)
  if arg is val {true} -> return num_f(1)
  if arg is ty {String} -> return @sec-stringtonumber(arg)
  assert arg is ty {Object}
  let primitiveValue = ? @sec-toprimitive(arg, ~number~)
  assert primitiveValue is not ty {Object}
  return ? @sec-tonumber(primitiveValue)
}

The Spec: Grammar Rules

spec.html §13.1 Identifiers
<emu-grammar type="definition">
  IdentifierReference[Yield, Await] :
    Identifier
    [~Yield] `yield`
    [~Await] `await`

  Identifier :
    IdentifierName but not ReservedWord
</emu-grammar>
spec/spectec/03-grammar-syntactic.spectec
rule syntactic |IdentifierReference| [Yield, Await] : {
  | |Identifier|
  | [~Yield] "yield"
  | [~Await] "await"
}

rule syntactic |Identifier| [] : {
  | |IdentifierName| butnot |ReservedWord|
}

The Spec: Tables

spec.html §6.2.4 Table 8 — Completion Record Fields (excerpt)
<emu-table id="table-completion-record-fields">
  <table>
    <tr><th>Field Name</th><th>Value</th><th>Meaning</th></tr>
    <!-- … [[Type]] … -->
    <tr>
      <td>[[Value]]</td>
      <td>any value except a Completion Record</td>
      <td>The value that was produced.</td>
    </tr>
    <!-- … [[Target]] … -->
  </table>
</emu-table>
spec/spectec/09-tables.spectec
table t"table-completion-record-fields" {
  kind fields   schema ("Completion Record", false)
  rows [
    …
    row [
      cell { field [[Value]] }
      cell {
        ty (pred(sat @ph-type-except(data sort #"Completion Record")))
      }
      cell { text "The value that was produced." }
    ]
    …
  ]
}

The Spec: Models

spec.html §5.2.6 Mathematical Operations & §6.1.6.1 The Number Type
“The Number type has exactly 18,437,736,874,454,810,627 (264 − 253 + 3) values, representing the double-precision floating point IEEE 754-2019 binary64 values… except that the distinct NaN values of the IEEE Standard are represented in ECMAScript as a single special NaN value… two other special values, +∞𝔽 and −∞𝔽… +0𝔽 and −0𝔽, and the finite non-zero values.”
How it translates Each specification sort (Math, Num, Str, Addr, Node, …) is an abstract carrier in syntax Model record, with a case view NumView(Math) and primitive operations — fixing no concrete representation.
spec/spectec/prose/01-model.spectec
--- Case view of IEEE 754-2019 binary64 Number (§6.1.6.1).
syntax NumView (Math : Type) {
  | nan | posInf | negInf | posZero | negZero | finite (m : Math)
}

--- Abstract sorts & primitive operations (excerpt).
syntax Model record {
  Math : Type;  Num : Type;  Str : Type;
  Addr : Type;  Node : Type; Heap : Type -> Type;

  numView : Num -> NumView(Math);  --- inspect binary64
  numOf   : Math -> Num;           --- 𝔽(x): roundTiesToEven
  numAdd  : Num -> Num -> Num;     --- IEEE 754 addition
  numNeg  : Num -> Num;            --- unary negation
}

The Spec: Relations

spec.html §29.6.6 happens-before

For a candidate execution execution, its happens-before Relation is the least Relation on Memory events that satisfies the following — eventA happens-before eventB if any of the following conditions are true:

  • eventA is-agent-order-before eventB in execution.
  • eventA synchronizes-with eventB in execution.
  • SharedDataBlockEventSet(execution) contains both eventA and eventB, eventA.[[Order]] is ~init~, and eventA and eventB have overlapping memory ranges.
  • There is an event eventC such that eventA happens-before eventC and eventC happens-before eventB in execution.
How it translates “The least Relation that satisfies…” becomes an inductive SpecTec relation, with one Horn rule (conclusion :- premises;) per prose bullet.
spec/spectec/prose/07-memory-model.spectec
--- happens-before (§29.6.6): least Relation under four rules.
relation HB (rbf : Rbf(E)) (hsw : Rel(E)) : Rel(E) {
  rule agent {a b : E} :
    HB(rbf, hsw, a, b) :- agentOrder(x, a, b);
  rule sync  {a b : E} :
    HB(rbf, hsw, a, b) :- SyncWith(x, rbf, hsw, a, b);
  rule init  {a b : E} :
    HB(rbf, hsw, a, b) :-
      inSdb(x, a), inSdb(x, b),
      x.order(a) = .init, rangesOverlapping(x, a, b);
  rule trans {a b c : E} :
    HB(rbf, hsw, a, b) :- HB(rbf, hsw, a, c), HB(rbf, hsw, c, b);
}

The Spec: Laws

spec.html §6.1.6.1.1 Number::unaryMinus & §4.2 Hosts and Implementations
§6.1.6.1.1 Number::unaryMinus ( number ): “1. If number is NaN, return NaN. 2. Return the negation of number; that is, compute a Number with the same magnitude but opposite sign.”
§4.2 Hosts and Implementations: “A host hook must conform to at least the following requirements: It must return either a normal completion or a throw completion.”
How it translates Each prose requirement becomes a law in a SpecTec laws block (148 model, 7 parser & 72 host laws), quoting the governing spec.html sentence verbatim (checked by law_quotes.py).
spec/spectec/prose/05-model-laws.spectec & 24-host-laws-hooks.spectec
laws Model.NumLaws (M : Model) {
  --- sec-numeric-types-number-unaryMinus:
  --- "Return the negation of number; same magnitude, opposite sign."
  law numNeg_view : forall a, M.numView(M.numNeg(a)) =
    match M.numView(a) with
    | .nan => .nan        | .posInf => .negInf   | .posZero => .negZero
    | .negInf => .posInf  | .negZero => .posZero | .finite(m) => .finite(M.neg(m))
    end;
}

laws Host.HookLaws (H : Host(M)) {
  --- sec-hosts-and-implementations:
  --- "It must return either a normal completion or a throw completion."
  law hookCompletion : forall c xs s r s',
    H.answers(c, xs, s, r, s') ->
      compType(r) = Known.eNormal \/ compType(r) = Known.eThrow;
}

Adding a proposal: Change the HTML

spec.html §22.1.3.32 String.prototype.trim — proposal-trim-chars
<emu-clause id="sec-string.prototype.trim" type="built-in function">
  <h1>String.prototype.trim ( <ins>[ _characters_ ]</ins> )</h1>
  <emu-alg>
    1. Let _thisValue_ be the *this* value.
    1. Return ? TrimString(_thisValue_, ~start+end~<ins>, _characters_</ins>).
  </emu-alg>
</emu-clause>

Adding a proposal: Generate the code

spec/spectec/clauses/S22.spectec
def @sec-string.prototype.trim "String.prototype.trim"
  (kind builtin params [])
  vars [#"this value", NewTarget, thisValue] {
  let thisValue = this_value
  return ? @sec-trimstring(thisValue, ~start+end~)
}
spec/spectec/clauses/S22.spectec
def @sec-string.prototype.trim "String.prototype.trim"
  (kind builtin params [[characters]])
  vars [#"this value", NewTarget, characters, thisValue] {
  let thisValue = this_value
  return ? @sec-trimstring(thisValue, ~start+end~, characters)
}

Adding a proposal: Debug!

proposal_trim_chars.js
const path = "/__ecma-262__/".trim("/_");
// → "ecma-262"

Varying levels of difficulty

Spec issues & errata

  • Contradictions & wrong results
    • Array.fromAsync() fulfills with undefined; CreateIntrinsics misaligns async
    • Timed-out Atomics.wait() returns "ok"; +0 * -5 yields +0; TLA using never disposes
  • Failing Assert:s on valid programs
    • Every await resumes AsyncBlockStart with ~empty~, failing its ~unused~ Assert:
    • /\p{Hex}/u, new Date(0).setHours(1e21) & diamond export * DAGs trip literal Assert:s
  • Missing grammar cases, type errors & §29 defects
    • Post-ASI /re/ lexing, new Function("o", "return o.#f") & return (f(x)) cover tail calls
    • "ab".split("") builds code units, not Strings; §29 RMW cycles, Races & block-aliasing bugs
  • In-flight proposal bugs
    • Missing BoundNames SDO row & [[DeferredNamespace]] slots in import defer
    • *undefined* vs. ~empty~ / ~unused~ mismatches in Immutable ArrayBuffers

What this can deliver

  • Invariants
    • §6.1.7.3 essential object invariants & module [[Status]] monotonicity
    • Proposal guarantees (e.g. immutable ArrayBuffer bytes never mutate)
  • Soundness
    • ! never throws, Assert:s never fail & slots/SDOs never miss a case
    • Editorial refactorings proved observably identical
    • Elided spec allocations & §29 reorderings proved unobservable
  • Generated JS reference VM
    • Spec-conformant executable engine
    • Verified accelerators
    • Full test262 coverage

Questions?