rule node {span : Nat -> Nat -> Nat times Nat} {n : M.Node} {nt : Grammar.NT} {id : Nat} {ps : List(Grammar.Param)} {i j : Nat} {kids : List(Grammar.Tree)} : Model.NodeRel(M, st, text, span, n, .node(nt, id, ps, i, j, kids)) :- M.nodeNt(n) = nt.ctorIdx, M.nodeProd(n) = id, forall p, p mem M.nodeArgs(n) <=> p mem ps, M.nodeStamp(n) = st, M.nodeSpan(n) = span(i, j), M.seqLen(M.nodeSource(n)) = M.ofNat(Grammar.slice(text, span(i, j).1, span(i, j).2).length), forall (k : Nat), M.seqGet(M.nodeSource(n), M.ofNat(k)) = Grammar.slice(text, span(i, j).1, span(i, j).2)[k]?.map(M.ofNat), M.seqLen(M.nodeKids(n)) = M.ofNat(kids.filter(fun _dot0 => !_dot0.isLeaf).length), forall k, M.seqGet(M.nodeKids(n), M.ofNat(k)).isSome = (k < kids.filter(fun _dot0 => !_dot0.isLeaf).length), forall k t c, kids.filter(fun _dot0 => !_dot0.isLeaf)[k]? = some(t) -> M.seqGet(M.nodeKids(n), M.ofNat(k)) = some(c) -> Model.NodeRel(M, st, text, span, c, t);Reading page · generated from spec/spectec/prose/06-node-rel.spectec, 04-derives.spectec, 03-strict-code.spectec
The parser's laws
What a model's parser must give, stated in SpecTec with its complete §5.1 / §11.2.2 / §12 derivation closure: a Parse Node related to a derivation of the source text under the grammar (relation Model.NodeRel, laws Model.ParseLaws), a covered node that reparses its cover's matched tokens (laws Model.CoverLaws), and the laws of a Parse Node's children and descendants (laws Model.NodeLaws). All three are proved of the engine (Engine.Claims.parseLaws, Engine.Claims.coverLaws, Engine.Claims.nodeLaws).
Parse Nodes, derivations and their laws
From spec/spectec/prose/06-node-rel.spectec
Model.NodeRel M src n t: the model's Parse Node n is the derivation tree t of Grammar.Derives (§5.1.2): the same nonterminal, production, parameters (as a set) and children (its nonterminals', a terminal giving none), and as source text the code points src i j of the input elements t spans. A token that is an instance of a lexical nonterminal is its lexical derivation, over the token's own code points.
Model.NodeRel
06-node-rel.spectec:19The model's Parse Node n is the derivation tree t of parser invocation st over the code points text (§5.1.2, sec-parsing); span i j is the span of text that input elements i to j occupy (§5.2.3, sec-algorithm-conventions-syntax-directed-operations: from the first's start to the last's end, the white space and comments between them included).
relation Model.NodeRel (M : Model) (st : Nat) (text : List(Nat)) : (Nat -> Nat -> Nat times Nat) -> M.Node -> Grammar.Tree -> Propa terminal (§5.1.2: its Parse Node has no children)
rule leaf {span : Nat -> Nat -> Nat times Nat} {n : M.Node} {i j : Nat} : Model.NodeRel(M, st, text, span, n, .leaf(i, j)) :- M.nodeStamp(n) = st, M.nodeSpan(n) = span(i, j), M.seqLen(M.nodeSource(n)) = M.ofNat(Grammar.slice(text, span(i, j).1, span(i, j).2).length), forall (k : Nat), M.seqGet(M.nodeSource(n), M.ofNat(k)) = Grammar.slice(text, span(i, j).1, span(i, j).2)[k]?.map(M.ofNat), M.seqLen(M.nodeKids(n)) = M.ofNat(0);input element k as an instance of a lexical nonterminal: its derivation t, over the element's code points (spans from the element's start)
rule lex {span : Nat -> Nat -> Nat times Nat} {n : M.Node} {k : Nat} {t : Grammar.Tree} : Model.NodeRel(M, st, text, span, n, .lex(k, t)) :- Model.NodeRel(M, st, text, fun i j => (span(k, k + 1).1 + i, span(k, k + 1).1 + j), n, t);Auxiliary definitions (2): Grammar.tokenSpan, Grammar.tokenText
Grammar.tokenSpan
06-node-rel.spectec:30The span of tokens i to j of toks in the source text: from the start of the first real token's input element to the end of the last's (a virtual ; has none).
def Grammar.tokenSpan (els : List(Grammar.Element)) (toks : List(Grammar.Token)) (i j : Nat) : Nat times Nat := let es := els.filter(fun _dot0 => _dot0.isToken) in let a := toks.take(i).countP(fun _dot0 => _dot0.virt.isNone) in let b := toks.take(j).countP(fun _dot0 => _dot0.virt.isNone) in let start := es[a]?.map(fun _dot0 => _dot0.i).getD(es.getLast?.map(fun _dot0 => _dot0.j).getD(0)) in if a < b then (start, es[b - 1]?.map(fun _dot0 => _dot0.j).getD(start)) else (start, start)Grammar.tokenText
06-node-rel.spectec:33The code points of src that tokens i to j of toks span.
def Grammar.tokenText (src : List(Nat)) (els : List(Grammar.Element)) (toks : List(Grammar.Token)) (i j : Nat) : List(Nat) := Grammar.slice(src, Grammar.tokenSpan(els, toks, i, j).1, Grammar.tokenSpan(els, toks, i, j).2)GrammarCtx
06-node-rel.spectec:38What a model's parse is stated against (§5.1, sec-syntactic-and-lexical-grammars): the grammar data, the context, the code point grammars' primitives, and whether its source text is strict mode code from outside (§11.2.2, sec-strict-mode-code: eval code of a direct eval contained in strict mode code).
syntax GrammarCtx recordAuxiliary definitions (10): GrammarCtx.at, Grammar.Tree.height, Grammar.Tree.view, Grammar.StrictCode, …
GrammarCtx.at
06-node-rel.spectec:47The context of a parser invocation under pc: Annex B's grammar, the Module goal (B.1.1) and strict mode code from outside as pc says.
def GrammarCtx.at (G : GrammarCtx) (pc : ParseCx) : GrammarCtx := { G with cx := ctor(pc.module, pc.annexB), strict := pc.strict }Grammar.Tree.height
06-node-rel.spectec:50One more than the depth of the tree.
def Grammar.Tree.height : Grammar.Tree -> Nat | .node(_, _, _, _, _, kids) => kids.attach.map(fun ctor(k, _) => k.height).foldl(max, 0) + 1 | _ => 1end
Grammar.Tree.view
06-node-rel.spectec:58The tree's Parse Nodes as §11.2.2 reads them (Grammar.NodeView), text i j the code points the span i to j matches: a token that is an instance of a lexical nonterminal is one node, its own derivation not read.
def Grammar.Tree.view (text : Nat -> Nat -> List(Nat)) : Grammar.NodeView(Grammar.Tree) { isA t n := t.nt? == some(n); kids | .node(_, _, _, _, _, kids) => kids.filter(fun _dot0 => !_dot0.isLeaf) | _ => [] end; span := Grammar.Tree.span; textIs t cs := text(t.span.1, t.span.2) == cs; height := Grammar.Tree.height;}
Grammar.StrictCode
06-node-rel.spectec:72§11.2.2 ("Code is interpreted as strict mode code in the following situations"): the source text t matches is strict mode code by the tree it is in, up being its ancestors nearest first (Grammar.strictCode).
def Grammar.StrictCode (text : Nat -> Nat -> List(Nat)) (up : List(Grammar.Tree)) (t : Grammar.Tree) : Prop := Grammar.strictCode(Grammar.Tree.view(text), up, t) = trueGrammarCtx.StrictIn
06-node-rel.spectec:76§11.2.2 in a parse of src scanned as els and toks: the source text the node t (its ancestors up) matches is strict mode code, from outside or by the tree (Grammar.StrictCode).
def GrammarCtx.StrictIn (G : GrammarCtx) (src : List(Nat)) (els : List(Grammar.Element)) (toks : List(Grammar.Token)) (up : List(Grammar.Tree)) (t : Grammar.Tree) : Prop := G.strict = true \/ Grammar.StrictCode(Grammar.tokenText(src, els, toks), up, t)ParamsOf
06-node-rel.spectec:79The grammar parameters a goal symbol's arguments switch on.
def ParamsOf (args : List(ParamId times Bool)) (ps : List(Grammar.Param)) : Prop := forall p, p mem ps <=> (p.ctorIdx, true) mem argsGrammarCtx.ParseIs
06-node-rel.spectec:85§5.1.2, §11.1.6: t is a parse of the code points src with goal goal, and the model's Parse Node n of parser invocation st is it: by ParsesText's steps for the syntactic grammar (its tokens named, a node's source the span of its input elements, white space and comments included), by ParsesCode for a code point grammar. B.1's productions modify those grammars (GL.overlays) and are no grammar a goal is parsed in (spec.html:53976, 54038).
def GrammarCtx.ParseIs (G : GrammarCtx) (M : Model) (st : Nat) (goal : Grammar.NT) (ps : List(Grammar.Param)) (src : List(Nat)) (n : M.Node) (t : Grammar.Tree) : Prop := if G.gl.rulesOf(.syntactic).any(fun _dot0 => _dot0.lhs == goal) then exists els toks, Grammar.Scans(G.gl, G.cx, G.P, src, els) /\ Grammar.GoalsAt(goal, els, toks, t) /\ toks.filter(fun _dot0 => _dot0.virt.isNone) = Grammar.tokensOf(src, els) /\ toks.all(fun k => k.virt.isNone || !k.lt) = true /\ Grammar.ASIOk(G.gl, G.cx, G.P, goal, ps, src, els, toks) /\ Grammar.Sentence(G.gl, G.cx, G.P, goal, ps, toks, t) /\ Grammar.ForHeadersExplicit(toks, t) /\ Grammar.NonStrictOk(G.gl, G.StrictIn(src, els, toks), [], t) /\ Model.NodeRel(M, st, src, Grammar.tokenSpan(els, toks), n, t) else exists g mem Grammar.codeGrammars, G.gl.rulesOf(g).any(fun _dot0 => _dot0.lhs == goal) /\ Grammar.ParsesCode(G.gl, G.cx, G.P, g, goal, ps, src, t) /\ Model.NodeRel(M, st, src, fun i j => (i, j), n, t)GrammarCtx.Parses
06-node-rel.spectec:89§5.1.2, §11.1.6: t is a parse of the code points src with goal goal: ParseIs without the model's Parse Node.
def GrammarCtx.Parses (G : GrammarCtx) (goal : Grammar.NT) (ps : List(Grammar.Param)) (src : List(Nat)) (t : Grammar.Tree) : Prop := if G.gl.rulesOf(.syntactic).any(fun _dot0 => _dot0.lhs == goal) then exists els toks, Grammar.Scans(G.gl, G.cx, G.P, src, els) /\ Grammar.GoalsAt(goal, els, toks, t) /\ toks.filter(fun _dot0 => _dot0.virt.isNone) = Grammar.tokensOf(src, els) /\ toks.all(fun k => k.virt.isNone || !k.lt) = true /\ Grammar.ASIOk(G.gl, G.cx, G.P, goal, ps, src, els, toks) /\ Grammar.Sentence(G.gl, G.cx, G.P, goal, ps, toks, t) /\ Grammar.ForHeadersExplicit(toks, t) /\ Grammar.NonStrictOk(G.gl, G.StrictIn(src, els, toks), [], t) else exists g mem Grammar.codeGrammars, G.gl.rulesOf(g).any(fun _dot0 => _dot0.lhs == goal) /\ Grammar.ParsesCode(G.gl, G.cx, G.P, g, goal, ps, src, t)GrammarCtx.CoverIs
06-node-rel.spectec:93§5.1.5: t is a reparse of the sequence of tokens originally matched over src (including any virtual semicolons §12.10 inserted inside that span) with goal goal, and n is its Parse Node at st.
def GrammarCtx.CoverIs (G : GrammarCtx) (M : Model) (st : Nat) (goal : Grammar.NT) (ps : List(Grammar.Param)) (src : List(Nat)) (n : M.Node) (t : Grammar.Tree) : Prop := if G.gl.rulesOf(.syntactic).any(fun _dot0 => _dot0.lhs == goal) then exists els toks, Grammar.Scans(G.gl, G.cx, G.P, src, els) /\ Grammar.GoalsAt(goal, els, toks, t) /\ toks.filter(fun _dot0 => _dot0.virt.isNone) = Grammar.tokensOf(src, els) /\ toks.all(fun k => k.virt.isNone || !k.lt) = true /\ Grammar.Sentence(G.gl, G.cx, G.P, goal, ps, toks, t) /\ Grammar.ForHeadersExplicit(toks, t) /\ Grammar.NonStrictOk(G.gl, G.StrictIn(src, els, toks), [], t) /\ Model.NodeRel(M, st, src, Grammar.tokenSpan(els, toks), n, t) else exists g mem Grammar.codeGrammars, G.gl.rulesOf(g).any(fun _dot0 => _dot0.lhs == goal) /\ Grammar.ParsesCode(G.gl, G.cx, G.P, g, goal, ps, src, t) /\ Model.NodeRel(M, st, src, fun i j => (i, j), n, t)Model.seqOfNats
06-node-rel.spectec:96The code points of a List as the model's sequence.
def Model.seqOfNats (M : Model) (src : List(Nat)) : M.Seq(M.Math) := src.foldl(fun s c => M.seqPush(s, M.ofNat(c)), M.seqNil)Model.ParseLaws
06-node-rel.spectec:101Model.parse's laws (§5.1.2, sec-parsing; §11.1.6, sec-parsetext), stated and never assumed, per invocation context: a Parse Node it gives is a parse under the grammar in that context, its nodes carrying the invocation's stamp, and where it gives none no tree is a parse (GrammarCtx.Parses).
Proved of the engine's model, for the specification's grammar under the engine's readings: Engine.Claims.parseLaws. Not a field of Implements.
laws Model.ParseLaws (M : Model) (G : GrammarCtx)2 laws
If the parse succeeded and no early errors were found, return the Parse Node (an instance of goalSymbol) at the root of the parse tree resulting from the parse.
5.1.2 Parsing sec-parsingWhen a parse is successful, it constructs a parse tree, a rooted tree structure in which each node is a Parse Node.
A Parse Node the model's parse gives is the root of a parse of the code points with the goal, under the grammar and the invocation's context, its nodes carrying the invocation's stamp (GrammarCtx.ParseIs).
soundSpecTec
law sound : forall pc st src (goal : Grammar.NT) args ps n, ParamsOf(args, ps) -> M.parse(pc, st, M.seqOfNats(src), goal.ctorIdx, args) = some(some(n)) -> (exists t, G.at(pc).ParseIs(M, st, goal, ps, src, n, t));An input stream of terminal symbols can be parsed using a goal symbol when it is matched by that goal symbol with no terminal symbols left over.
Where the model's parse gives no Parse Node, no tree is a parse of the code points with the goal under the grammar and the invocation's context (GrammarCtx.Parses).
completeSpecTec
law complete : forall pc st src (goal : Grammar.NT) args ps, ParamsOf(args, ps) -> M.parse(pc, st, M.seqOfNats(src), goal.ctorIdx, args) = some(none) -> (forall t, not G.at(pc).Parses(goal, ps, src, t));Model.Parsed
06-node-rel.spectec:117The Parse Nodes of parser invocations in context pc (§5.1.2, sec-parsing; §5.1.5, sec-syntactic-grammar): a parse's result, the covered node the model gives from such a node (Model.cover), and their descendants.
relation Model.Parsed (M : Model) (pc : ParseCx) : M.Node -> Proprule parse {st : Nat} {src : M.Seq(M.Math)} {goal : NtId} {args : List(ParamId times Bool)} {n : M.Node} : Model.Parsed(M, pc, n) :- M.parse(pc, st, src, goal, args) = some(some(n));rule cover {st : Nat} {n : M.Node} {k : NtId} {args : List(ParamId times Bool)} {r : M.Node} : Model.Parsed(M, pc, r) :- Model.Parsed(M, pc, n), M.cover(pc, st, n, k, args) = some(r);rule desc {n d : M.Node} : Model.Parsed(M, pc, d) :- Model.Parsed(M, pc, n), d mem seqList(M.nodeDescendants(n));Model.CoverLaws
06-node-rel.spectec:128Model.cover's law (§5.1.5, sec-syntactic-grammar: "P must cover K"), stated and never assumed, per invocation context: the node it gives from a Parse Node n of parser invocations in that context, with a goal and arguments, is a parse of n's source text with that goal under the grammar in that context, its nodes carrying the new invocation's stamp: what ParseLaws.sound says of Model.parse's node for that text. Nothing is said of a node no parser invocation made, nor of one made in another context.
Proved of the engine's model, for the specification's grammar under the engine's readings: Engine.Claims.coverLaws. Not a field of Implements.
laws Model.CoverLaws (M : Model) (G : GrammarCtx)1 laws
The sequence of tokens originally matched by p is parsed again using n as the goal symbol. If n takes grammatical parameters, then they are set to the same values used when p was originally parsed.
The covered node the model gives from a Parse Node n of a parse in this context is a reparse of n's matched tokens with the goal and the arguments, its nodes carrying the new invocation's stamp (GrammarCtx.CoverIs).
soundSpecTec
law sound : forall pc st n (goal : Grammar.NT) args ps src r, Model.Parsed(M, pc, n) -> ParamsOf(args, ps) -> M.nodeSource(n) = M.seqOfNats(src) -> M.cover(pc, st, n, goal.ctorIdx, args) = some(r) -> (exists t, G.at(pc).CoverIs(M, st, goal, ps, src, r, t));Auxiliary definitions (4): Grammar.occsOf, Grammar.prodAt, Grammar.occsAt, Grammar.fillOccs
Grammar.occsOf
06-node-rel.spectec:140The nonterminal occurrences of a right-hand side in written order, with its optional symbols' presences m: each with whether it is present.
def occsOf : List(Item) -> List(Bool) -> List(NT times Bool) | [], _ => [] | .sym(.nt(n, _), true) :: is, b :: bs => (n, b) :: occsOf(is, bs) | .sym(.t(_), true) :: is, _ :: bs => occsOf(is, bs) | .sym(.nt(n, _), false) :: is, bs => (n, true) :: occsOf(is, bs) | .butNot(.nt(n, _), _) :: is, bs => (n, true) :: occsOf(is, bs) | _ :: is, bs => occsOf(is, bs)end
Grammar.prodAt
06-node-rel.spectec:150The right-hand side with production id id (GL.byId).
def prodAt (gl : GL) (id : Nat) : Option(Prod) := gl.byId.toList[id]?.joinGrammar.occsAt
06-node-rel.spectec:153The nonterminal occurrences of production id's right-hand side, with their presences.
def occsAt (gl : GL) (id : Nat) : List(NT times Bool) := prodAt(gl, id).bind(fun p => p.altOf.map(fun a => occsOf(a.rhs, p.mask))).getD([])Grammar.fillOccs
06-node-rel.spectec:156The written occurrences, each with its child: a present one takes the next of kids.
def fillOccs {N : Type} : List(NT times Bool) -> List(N) -> List(Nat times Option(N)) | [], _ => [] | (n, true) :: os, k :: ks => (n.ctorIdx, some(k)) :: fillOccs(os, ks) | (n, _) :: os, ks => (n.ctorIdx, none) :: fillOccs(os, ks)end
Model.NodeLaws
06-node-rel.spectec:167The laws of nodeChild and nodeDescendants (§5.1.2, sec-parsing), over the grammar G: a written occurrence's child is the next child with its nonterminal; in a parse and in a covered node the model gives, the absent ones are the production's absent optional symbols; the descendants are the children's pre-order flattening.
Proved of the engine's model, for the specification's grammar under the engine's readings: Engine.Claims.nodeLaws. Not a field of Implements.
laws Model.NodeLaws (M : Model) (G : GrammarCtx)4 laws
Moreover, it has zero or more children, one for each symbol on the production's right-hand side: each child is a Parse Node that is an instance of the corresponding symbol.
The written occurrences of nt, first to last, have as children the node's children whose nonterminal is nt, in order.
child_kidsSpecTec
law child_kids : forall n nt, exists (os : List(Option(M.Node))), (forall k, M.nodeChild(n, nt, k) = os[k]?) /\ os.filterMap(id) = seqList(M.nodeKids(n)).filter(fun _dot0 => M.nodeNt(_dot0) == nt);"the X of" a node of a parse is the child of the k-th written occurrence of nt in its production, none where that occurrence is an absent optional symbol.
child_parseSpecTec
law child_parse : forall pc st src goal args n d nt k, M.parse(pc, st, M.seqOfNats(src), goal, args) = some(some(n)) -> d = n \/ d mem seqList(M.nodeDescendants(n)) -> M.nodeChild(d, nt, k) = Grammar.fillOccs(Grammar.occsAt(G.gl, M.nodeProd(d)), seqList(M.nodeKids(d))).filter(fun _dot0 => _dot0.1 == nt).map(fun _dot0 => _dot0.2)[k]?;The same in a covered node the model gives (Model.cover) and its descendants, whatever the cover.
child_coverSpecTec
law child_cover : forall pc st c goal args n d nt k, M.cover(pc, st, c, goal, args) = some(n) -> d = n \/ d mem seqList(M.nodeDescendants(n)) -> M.nodeChild(d, nt, k) = Grammar.fillOccs(Grammar.occsAt(G.gl, M.nodeProd(d)), seqList(M.nodeKids(d))).filter(fun _dot0 => _dot0.1 == nt).map(fun _dot0 => _dot0.2)[k]?;No early error rules are applied to p or any of its descendants.
A node's descendants are its children, each followed by its own descendants (pre-order).
descendantsSpecTec
law descendants : forall n, seqList(M.nodeDescendants(n)) = seqList(M.nodeKids(n)).flatMap(fun c => c :: seqList(M.nodeDescendants(c)));Grammar derivations, lexical scanning and ASI (§5.1, §12)
From spec/spectec/prose/04-derives.spectec
Derives is §5.1's derivation relation over GL's notation (Grammar.Core, read through Grammar.Notation), for each grammar and goal symbol, with parameters and guards (§5.1.6), optional symbols (one right-hand side per presence mask, so a node's production is a GL production id), lookahead, [no LineTerminator here], but not and [empty]. Its terminals come from an Alphabet: code points for the lexical, RegExp and numeric string grammars, tokens for the syntactic grammar. The descriptive phrases, <USP> and the [> but only if …] conditions are the alphabet's (b) primitives.
but not and the lookahead ∉ N are negative. Derives is therefore the limit of strata: stratum k + 1 reads the exclusions in stratum k, and a derivation is one at every stratum from some on, which is §5.1's relation for a grammar whose exclusions are stratified, as GL's are.
The rest of §5.1.3, §5.1.5, §11 and §12 is stated over it: scanning source text into input elements (Scans), the tokens and their line terminators, the choice of lexical goal at the parse's position (GoalsAt), automatic semicolon insertion (ASIOk), and chain productions (chainNt).
Derivations
Grammar.Tree
04-derives.spectec:33A Parse Node in a derivation tree (§5.1.2, sec-parsing): a nonterminal instance with its production id, its parameters and its span of the input; a leaf (a terminal or a phrase) and its span; or input element k as an instance of another grammar's nonterminal, with that grammar's derivation t over the element's code points.
syntax TreeAuxiliary definitions (5): Grammar.Tree.has, Grammar.Tree.isLeaf, Grammar.Tree.nt?, Grammar.Tree.span, …
Grammar.Tree.has
04-derives.spectec:40A node of nonterminal n spanning i to j is in the tree.
def Tree.has (n : NT) (i j : Nat) : Tree -> Bool | .node(m, _, _, a, b, kids) => m == n && a == i && b == j || kids.attach.any(fun ctor(k, _) => k.has(n, i, j)) | .leaf(..) => false | .lex(_, t) => t.has(n, i, j)end
Grammar.Tree.isLeaf
04-derives.spectec:47A terminal's tree: no Parse Node child of its parent.
def Tree.isLeaf : Tree -> Bool | .leaf(..) => true | _ => falseend
Grammar.Tree.nt?
04-derives.spectec:53The nonterminal of a derivation tree node (§5.1.2, sec-parsing); none for a terminal leaf.
def Tree.nt? : Tree -> Option(NT) | .node(n, ..) => some(n) | .leaf(..) => none | .lex(_, t) => t.nt?end
Grammar.Tree.span
04-derives.spectec:60The input span (i, j) matched by a derivation tree node (§5.1.2, sec-parsing).
def Tree.span : Tree -> Nat times Nat | .leaf(i, j) => (i, j) | .lex(k, _) => (k, k + 1) | .node(_, _, _, i, j, _) => (i, j)end
Grammar.slice
04-derives.spectec:67The elements i to j of the input.
def slice {T : Type} (inp : List(T)) (i j : Nat) : List(T) := inp.drop(i).take(j - i)Grammar.Alphabet
04-derives.spectec:70A grammar's terminal interface (§5.1.6, sec-grammar-notation).
syntax Alphabet (T : Type) recordterminal x, at item k of right-hand side s, matches these input elements
term : Src -> Nat -> Terminal -> List(T) -> Prop;(b) a descriptive phrase's class
phrase : Phrase -> List(T) -> Prop;(b) a [> but only if …] condition on the node derived for the item before it, in the whole input
cond : Phrase -> List(T) -> Tree -> Prop;this input element is an instance of a nonterminal this grammar does not define, derived as t over its code points
leaf : NT -> T -> Tree -> Prop;no line terminator before the input element at this position
noLT : List(T) -> Nat -> Prop;the position a lookahead reads from this one: past the elements §12.10 inserted
look : List(T) -> Nat -> Nat := fun _ j => j;Auxiliary definitions (4): Grammar.StartsWith, Grammar.LookOk, Grammar.Excluded, Grammar.CondOk
Grammar.StartsWith
04-derives.spectec:91The input from j starts with the lookahead sequence, each item read from A.look.
def StartsWith (s : Src) : List(LookItem) -> Nat -> Prop | [], _ => True | .t(x) :: rest, j => exists h, A.look(inp, j) < h /\ h <= inp.length /\ A.term(s, 0, x, slice(inp, A.look(inp, j), h)) /\ StartsWith(s, rest, h) | .noLT :: rest, j => A.noLT(inp, A.look(inp, j)) /\ StartsWith(s, rest, j)end
Grammar.LookOk
04-derives.spectec:98A lookahead restriction holds at j; ∉ N reads N in neg.
def LookOk (s : Src) : Lookahead -> Nat -> Prop | .eq(q), j => StartsWith(A, inp, s, q, j) | .ne(q), j => not StartsWith(A, inp, s, q, j) | .mem(qs), j => exists q mem qs, StartsWith(A, inp, s, q, j) | .notMem(qs), j => forall q mem qs, not StartsWith(A, inp, s, q, j) | .notMemNT(n), j => not exists h, neg(n, [], j, h)end
Grammar.Excluded
04-derives.spectec:107The input i to h is an excluded symbol (in neg for a nonterminal).
def Excluded (s : Src) (k : Nat) (ps : List(Param)) (i h : Nat) : Exclusion -> Prop | .sym(y) => match y with | .t(x) => A.term(s, k, x, slice(inp, i, h)) | .nt(n, args) => neg(n, applyArgs(ps, args), i, h) end | .oneOf(ys, _) => exists y mem ys, match y with | .t(x) => A.term(s, k, x, slice(inp, i, h)) | .nt(n, args) => neg(n, applyArgs(ps, args), i, h) endend
Grammar.CondOk
04-derives.spectec:119The condition after an item, if any, holds of its node.
def CondOk (is : List(Item)) (t : Tree) : Prop := match is with | .onlyIf(c) :: _ => A.cond(c, inp, t) | _ => Trueend
Grammar.Step
04-derives.spectec:129One stratum (§5.1.6, sec-grammar-notation): nonterminal n with parameters ps derives the input i to j as node t, the exclusions read in neg.
relation Step : NT -> List(Param) -> Nat -> Nat -> Tree -> Proprule node {n ps i j m kids id} (s : Src) : Step(n, ps, i, j, .node(n, id, ps, i, j, kids)) :- s mem gl.alts(cx, g, n), s.alt.guard.all(Guard.holds(ps)), gl.prodId(s, m) = some(id), Seq(s, ps, 0, s.alt.rhs, i, j, m, kids);rule lex {n ps i t} {e : T} : Step(n, ps, i, i + 1, .lex(i, t)) :- gl.alts(cx, g, n) = [], inp[i]? = some(e), A.leaf(n, e, t);Grammar.Seq
04-derives.spectec:136Items k on of right-hand side s derive the input i to j (§5.1.6, sec-grammar-notation), with the optional symbols' presences m and the nodes ts.
relation Seq : Src -> List(Param) -> Nat -> List(Item) -> Nat -> Nat -> List(Bool) -> List(Tree) -> Proprule nil {s ps k i} : Seq(s, ps, k, [], i, i, [], []);rule absent {s ps k x is i j m ts} : Seq(s, ps, k, .sym(x, true) :: is, i, j, false :: m, ts) :- Seq(s, ps, k + 1, is, i, j, m, ts);rule term {s ps k x o is i h j m ts} : Seq(s, ps, k, .sym(.t(x), o) :: is, i, j, if o then true :: m else m, .leaf(i, h) :: ts) :- A.term(s, k, x, slice(inp, i, h)), Seq(s, ps, k + 1, is, h, j, m, ts);rule nt {s ps k n args o is i h j m t ts} : Seq(s, ps, k, .sym(.nt(n, args), o) :: is, i, j, if o then true :: m else m, t :: ts) :- Step(n, applyArgs(ps, args), i, h, t), CondOk(A, inp, is, t), Seq(s, ps, k + 1, is, h, j, m, ts);rule butNotT {s ps k x ex is i h j m ts} : Seq(s, ps, k, .butNot(.t(x), ex) :: is, i, j, m, .leaf(i, h) :: ts) :- A.term(s, k, x, slice(inp, i, h)), not Excluded(A, neg, inp, s, k, ps, i, h, ex), Seq(s, ps, k + 1, is, h, j, m, ts);rule butNotN {s ps k n args ex is i h j m t ts} : Seq(s, ps, k, .butNot(.nt(n, args), ex) :: is, i, j, m, t :: ts) :- Step(n, applyArgs(ps, args), i, h, t), not Excluded(A, neg, inp, s, k, ps, i, h, ex), Seq(s, ps, k + 1, is, h, j, m, ts);rule phrase {s ps k p is i h j m ts} : Seq(s, ps, k, .phrase(p) :: is, i, j, m, .leaf(i, h) :: ts) :- A.phrase(p, slice(inp, i, h)), Seq(s, ps, k + 1, is, h, j, m, ts);rule look {s ps k l is i j m ts} : Seq(s, ps, k, .lookahead(l) :: is, i, j, m, ts) :- LookOk(A, neg, inp, s, l, i), Seq(s, ps, k + 1, is, i, j, m, ts);rule noLT {s ps k is i j m ts} : Seq(s, ps, k, .noLT :: is, i, j, m, ts) :- A.noLT(inp, i), Seq(s, ps, k + 1, is, i, j, m, ts);rule empty {s ps k is i j m ts} : Seq(s, ps, k, .empty :: is, i, j, m, ts) :- Seq(s, ps, k + 1, is, i, j, m, ts);rule onlyIf {s ps k c is i j m ts} : Seq(s, ps, k, .onlyIf(c) :: is, i, j, m, ts) :- Seq(s, ps, k + 1, is, i, j, m, ts);Auxiliary definitions (2): Grammar.DerivesAt, Grammar.Derives
Grammar.DerivesAt
04-derives.spectec:153Stratum k of the derivation relation.
def DerivesAt (gl : GL) (cx : Ctx) (g : GrammarId) {T : Type} (A : Alphabet(T)) (inp : List(T)) : Nat -> NT -> List(Param) -> Nat -> Nat -> Tree -> Prop | 0 => fun _ _ _ _ _ => False | k + 1 => Step(A, fun n ps i j => exists t, DerivesAt(gl, cx, g, A, inp, k, n, ps, i, j, t), inp, gl, cx, g)end
Grammar.Derives
04-derives.spectec:161§5.1: in grammar g and context cx, n with parameters ps derives the input i to j as t: at every stratum from some on.
def Derives (gl : GL) (cx : Ctx) (g : GrammarId) {T : Type} (A : Alphabet(T)) (inp : List(T)) (n : NT) (ps : List(Param)) (i j : Nat) (t : Tree) : Prop := exists K, forall k, K <= k -> DerivesAt(gl, cx, g, A, inp, k, n, ps, i, j, t)Code points: the lexical, RegExp and numeric string grammars
Grammar.CodePrims
04-derives.spectec:168The (b) primitives of the code point grammars (§5.1.6, sec-grammar-notation): the descriptive phrases' classes, <USP> (§12.2, sec-white-space), and the [> but only if …] conditions (each reads a static semantics of the node before it, which the Ecma program supplies).
syntax CodePrims recordAuxiliary definitions (2): Grammar.codeAlphabet, Grammar.lineTerminators
Grammar.codeAlphabet
04-derives.spectec:176The terminal alphabet of the code-point grammars (§5.1.6, sec-grammar-notation; §12, sec-ecmascript-language-lexical-grammar).
def codeAlphabet (P : CodePrims) : Alphabet(Nat) { term _ _ x w := match x with | .text(s, _) => w = s.toList.map(Char.toNat) | .cp(n) => match n.codePoint with | some(v) => w = [v] | none => exists c, w = [c] /\ P.usp(c) end end; phrase p w := exists c, w = [c] /\ P.phrase(p, c); cond := P.cond; leaf _ _ _ := False; noLT _ _ := True;}
Grammar.lineTerminators
04-derives.spectec:191§12.3: the line terminator code points.
def lineTerminators : List(Nat) := ([.LF, .CR, .LS, .PS] : List(CodePointName)).filterMap(CodePointName.codePoint)Source text, input elements and tokens (§5.1.3, §11, §12)
Grammar.Element
04-derives.spectec:197An input element (§5.1.3, sec-lexical-and-regexp-grammars; §12, sec-ecmascript-language-lexical-grammar): its span of the source text, the lexical goal it was read with, and its derivation.
syntax Element recordAuxiliary definitions (4): Grammar.Element.kind, Grammar.Element.isToken, Grammar.Element.breaks, Grammar.Scans
Grammar.Element.kind
04-derives.spectec:206What the element is an instance of, under its goal (WhiteSpace, Comment, CommonToken, …).
def Element.kind (e : Element) : Option(NT) := match e.tree with | .node(_, _, _, _, _, [k]) => k.nt? | _ => noneend
Grammar.Element.isToken
04-derives.spectec:213§5.1.3: white space, line terminators and comments are not tokens; B.1.1's HTMLCloseComment is a comment.
def Element.isToken (e : Element) : Bool := ![NT.WhiteSpace, .LineTerminator, .Comment, .HashbangComment, .HTMLCloseComment].any(fun _dot0 => some(_dot0) == e.kind)Grammar.Element.breaks
04-derives.spectec:218§12.4, B.1.1: a line terminator, or a comment that contains a line terminator code point (a MultiLineComment with one, a SingleLineHTMLCloseComment), is a LineTerminator for the syntactic grammar.
def Element.breaks (src : List(Nat)) (e : Element) : Bool := e.kind == some(.LineTerminator) || e.kind == some(.Comment) && slice(src, e.i, e.j).any(lineTerminators.contains)Grammar.Scans
04-derives.spectec:225§12: the source text is scanned left to right into the input elements els, each the longest sequence of code points its lexical goal derives; §12.9.3: the code point after a NumericLiteral is not an IdentifierStart or a DecimalDigit.
def Scans (src : List(Nat)) (els : List(Element)) : Prop := els.zipIdx.all(fun (e, k) => e.i == (if k == 0 then 0 else els[k - 1]?.map(fun _dot0 => _dot0.j).getD(0))) = true /\ els.getLast?.map(fun _dot0 => _dot0.j).getD(0) = src.length /\ forall e mem els, e.i < e.j /\ Derives(gl, cx, .lexical, codeAlphabet(P), src, e.goal, [], e.i, e.j, e.tree) /\ (forall h, e.j < h -> h <= src.length -> not exists t, Derives(gl, cx, .lexical, codeAlphabet(P), src, e.goal, [], e.i, h, t)) /\ (e.tree.has(.NumericLiteral, e.i, e.j) = true -> e.j < src.length -> (forall n mem [NT.IdentifierStart, NT.DecimalDigit], not exists t, Derives(gl, cx, .lexical, codeAlphabet(P), src, n, [], e.j, e.j + 1, t)))Grammar.Why
04-derives.spectec:229Why §12.10 (sec-automatic-semicolon-insertion) inserted a virtual semicolon: rule 1 (an offending token after a line terminator, or }), rule 1's ) of a do-while, rule 2, rule 3 (sec-rules-of-automatic-semicolon-insertion).
syntax Whyderiving [Repr, BEq, Inhabited]
Grammar.Token
04-derives.spectec:239A token of the syntactic grammar (§5.1.5, sec-syntactic-grammar; §12.10, sec-automatic-semicolon-insertion): its code points, whether a line terminator precedes it, and, for a virtual semicolon, why it was inserted.
syntax Token recordAuxiliary definitions (10): Grammar.tokensOf, Grammar.pastVirt, Grammar.tokenAlphabet, Grammar.Sentence, …
Grammar.tokensOf
04-derives.spectec:246The tokens of scanned input elements.
def tokensOf (src : List(Nat)) (els : List(Element)) : List(Token) := els.zipIdx.filter(fun _dot0 => _dot0.1.isToken).map(fun (e, k) => let before := els.take(k).reverse.takeWhile(fun _dot0 => !_dot0.isToken) in ctor(slice(src, e.i, e.j), before.any(fun _dot0 => _dot0.breaks(src)), none))Grammar.pastVirt
04-derives.spectec:249The first position from j that holds no virtual semicolon.
def pastVirt (toks : List(Token)) (j : Nat) : Nat := j + toks.drop(j).takeWhile(fun _dot0 => _dot0.virt.isSome).lengthGrammar.tokenAlphabet
04-derives.spectec:256The syntactic grammar's alphabet: a terminal is a token of its text; a virtual semicolon only where §12.10 lets one stand (Gen.semis's class of that ;); a lexical nonterminal is a real token whose text it derives, the token's Parse Node being that derivation; a lookahead reads the source's tokens, past the virtual semicolons (§5.1.6's "input token sequence").
SpecTec, 18 lines
def tokenAlphabet : Alphabet(Token) { term s k x w := match x, w with | .text(str, _), [tok] => tok.text = str.toList.map(Char.toNat) /\ match tok.virt with | none => True | some(why) => exists c, gl.ctorOf(s) = some(c) /\ exists cls, (c, k, cls) mem gl.semis /\ match cls with | .insertable | .forHeaderIfDeclaration => why != .paren | .doWhile => True | .emptyStatement | .forHeader => False end end | _, _ => False end; phrase _ _ := False; cond _ _ _ := False; leaf n tok t := tok.virt = none /\ Derives(gl, cx, .lexical, codeAlphabet(P), tok.text, n, [], 0, tok.text.length, t); noLT toks i := forall tok, toks[i]? = some(tok) -> tok.lt = false; look := pastVirt;}
Grammar.Sentence
04-derives.spectec:276A token sequence the goal derives.
def Sentence (goal : NT) (ps : List(Param)) (toks : List(Token)) (t : Tree) : Prop := Derives(gl, cx, .syntactic, tokenAlphabet(gl, cx, P), toks, goal, ps, 0, toks.length, t)Grammar.ForHeadersExplicit
04-derives.spectec:280§12.10's overriding condition at the ; that ends the LexicalDeclaration of for ( LexicalDeclaration …: it is the header's first, never virtual.
def ForHeadersExplicit (toks : List(Token)) : Tree -> Prop | .leaf(..) | .lex(..) => True | .node(n, _, _, _, _, kids) => (n == .ForStatement -> (forall d mem kids, d.nt? = some(.LexicalDeclaration) -> (forall tok, toks[d.span.2 - 1]? = some(tok) -> tok.virt = none))) /\ all(kids)endwhere { all : List(Tree) -> Prop | [] => True | d :: ds => ForHeadersExplicit(toks, d) /\ all(ds) end}
Grammar.NonStrictOk
04-derives.spectec:294B.3.3, B.3.5 ("only applies when parsing non-strict code"): no node of such a production lies in strict mode code. strict ancestors node is §11.2.2's "is strict mode code" (StrictCode, with strictness from outside the parse).
def NonStrictOk (L : GL) (strict : List(Tree) -> Tree -> Prop) : List(Tree) -> Tree -> Prop | _, .leaf(..) | _, .lex(..) => True | up, t@(.node(_, id, _, _, _, kids)) => (id mem L.sloppyIds -> not strict(up, t)) /\ all(t :: up, kids)endwhere { all (up : List(Tree)) : List(Tree) -> Prop | [] => True | d :: ds => NonStrictOk(L, strict, up, d) /\ all(up, ds) end}
Grammar.lexicalGoalOf
04-derives.spectec:306The lexical goal a lexical nonterminal is read under (§12).
def lexicalGoalOf (n : NT) : NT := if n == .RegularExpressionLiteral then .InputElementRegExp else if n == .TemplateMiddle || n == .TemplateTail then .InputElementTemplateTail else .InputElementDivGrammar.Tree.goalAt
04-derives.spectec:310The lexical goal the token at position idx of a syntactic derivation is read under: a lexical nonterminal's own goal (lexicalGoalOf), a terminal's InputElementDiv.
def Tree.goalAt (idx : Nat) : Tree -> Option(NT) | .leaf(i, j) => if i <= idx && idx < j then some(.InputElementDiv) else none | .lex(k, lt) => if k == idx then lt.nt?.map(lexicalGoalOf) else none | .node(_, _, _, _, _, kids) => inKids(kids)endwhere { inKids : List(Tree) -> Option(NT) | [] => none | d :: ds => match d.goalAt(idx) with | some(g) => some(g) | none => inKids(ds) end end}
Grammar.realIdx
04-derives.spectec:326The index in toks of the n-th real token.
def realIdx : Nat -> List(Token) -> Nat | _, [] => 0 | 0, tok :: toks => if tok.virt.isNone then 0 else 1 + realIdx(0, toks) | n + 1, tok :: toks => 1 + realIdx(if tok.virt.isNone then n else n + 1, toks)end
Grammar.GoalsAt
04-derives.spectec:335§12: the first input element of a Script or Module is read under InputElementHashbangOrRegExp, trivia after that under InputElementDiv, and each token under the lexical goal its node in t implies (Tree.goalAt, after any inserted ; before it).
def GoalsAt (goal : NT) (els : List(Element)) (toks : List(Token)) (t : Tree) : Prop := forall k e, els[k]? = some(e) -> (if k == 0 && (goal == .Script || goal == .Module) then e.goal = .InputElementHashbangOrRegExp else if !e.isToken then e.goal = .InputElementDiv else t.goalAt(realIdx(els.take(k).filter(Element.isToken).length, toks)) = some(e.goal))§12.10: left-to-right automatic semicolon insertion
Auxiliary definition: Grammar.TriviaElem
Grammar.TriviaElem
04-derives.spectec:340One maximal non-token input element from i to j (first: whether the goal is Script or Module).
def TriviaElem (src : List(Nat)) (first : Bool) (i j : Nat) (e : Element) : Prop := i < j /\ j <= src.length /\ e.i = i /\ e.j = j /\ !e.isToken /\ let g := if first && i == 0 then .InputElementHashbangOrRegExp else .InputElementDiv in e.goal = g /\ Derives(gl, cx, .lexical, codeAlphabet(P), src, e.goal, [], i, j, e.tree) /\ forall h, j < h -> h <= src.length -> not exists t, Derives(gl, cx, .lexical, codeAlphabet(P), src, e.goal, [], i, h, t)Grammar.Trivia
04-derives.spectec:344The trivia from i ends at k with line-terminator flag lt (§5.1.3, sec-lexical-and-regexp-grammars; §12.2, sec-white-space; §12.4, sec-comments): maximal non-token elements until none starts at k.
relation Trivia (src : List(Nat)) (first : Bool) : Nat -> Nat -> Bool -> Proprule stop {i} : Trivia(src, first, i, i, false) :- not exists j e, TriviaElem(gl, cx, P, src, first, i, j, e);rule step {i m k lt} (e : Element) : Trivia(src, first, i, k, e.breaks(src) || lt) :- TriviaElem(gl, cx, P, src, first, i, m, e), Trivia(src, first, m, k, lt);Auxiliary definitions (15): Grammar.ScanTok, Grammar.vsPending, Grammar.vsParen, Grammar.noCross, …
Grammar.ScanTok
04-derives.spectec:351The next token from p under lexical goal lg (first: Script or Module): after trivia to a with lt, the maximal element a to b is a token passing §12.9.3's follow rule.
def ScanTok (src : List(Nat)) (first : Bool) (lg : NT) (p a b : Nat) (lt : Bool) (tree : Tree) : Prop := Trivia(gl, cx, P, src, first, p, a, lt) /\ a < b /\ b <= src.length /\ let g := if first && a == 0 then .InputElementHashbangOrRegExp else lg in Element.isToken(ctor(a, b, g, tree)) = true /\ Derives(gl, cx, .lexical, codeAlphabet(P), src, g, [], a, b, tree) /\ (forall h, b < h -> h <= src.length -> not exists t, Derives(gl, cx, .lexical, codeAlphabet(P), src, g, [], a, h, t)) /\ (tree.has(.NumericLiteral, a, b) = true -> b < src.length -> (forall n mem [NT.IdentifierStart, NT.DecimalDigit], not exists t, Derives(gl, cx, .lexical, codeAlphabet(P), src, n, [], b, b + 1, t)))Grammar.vsPending
04-derives.spectec:354A virtual ; in vs waits at boundary s (2 * p).
def vsPending (vs : List(Nat times Bool)) (s : Nat) : Bool := s % 2 == 0 && vs.any(fun (p, _) => p == s / 2)Grammar.vsParen
04-derives.spectec:357Whether the virtual ; at p was inserted after ) (do-while).
def vsParen (vs : List(Nat times Bool)) (p : Nat) : Bool := vs.any(fun (q, b) => q == p && b)Grammar.noCross
04-derives.spectec:360No virtual ; of vs lies strictly between p and q.
def noCross (vs : List(Nat times Bool)) (p q : Nat) : Bool := vs.all(fun (v, _) => !(p < v && v < q))Grammar.semiAllowed
04-derives.spectec:363§12.10: a virtual ; (paren: after )) may stand at item k of s.
def semiAllowed (s : Src) (k : Nat) (paren : Bool) : Prop := exists c cls, gl.ctorOf(s) = some(c) /\ (c, k, cls) mem gl.semis /\ match cls with | .insertable | .forHeaderIfDeclaration => paren = false | .doWhile => True | .emptyStatement | .forHeader => Falseend
Grammar.forKeep
04-derives.spectec:370§12.10: the ; ending a for header's LexicalDeclaration is never virtual.
def forKeep (lhs n : NT) (j : Nat) : Bool := !(lhs == .ForStatement && n == .LexicalDeclaration && j % 2 == 1)Grammar.SynTerm
04-derives.spectec:373Terminal x at item k of s matches from boundary i to j under virtual semicolons vs.
def SynTerm (src : List(Nat)) (first : Bool) (vs : List(Nat times Bool)) (s : Src) (k : Nat) (x : Terminal) (i j : Nat) : Prop := match x with | .text(str, _) => if vsPending(vs, i) then str = ";" /\ semiAllowed(gl, s, k, vsParen(vs, i / 2)) /\ j = i + 1 else exists a b lt tr, ScanTok(gl, cx, P, src, first, .InputElementDiv, i / 2, a, b, lt, tr) /\ noCross(vs, i / 2, b) = true /\ slice(src, a, b) = str.toList.map(Char.toNat) /\ j = 2 * b | .cp(_) => Falseend
Grammar.SynLeaf
04-derives.spectec:379Lexical nonterminal n matches one token from boundary i to j under virtual semicolons vs.
def SynLeaf (src : List(Nat)) (first : Bool) (vs : List(Nat times Bool)) (n : NT) (i j : Nat) : Prop := vsPending(vs, i) = false /\ exists a b lt tr t, ScanTok(gl, cx, P, src, first, lexicalGoalOf(n), i / 2, a, b, lt, tr) /\ noCross(vs, i / 2, b) = true /\ Derives(gl, cx, .lexical, codeAlphabet(P), slice(src, a, b), n, [], 0, b - a, t) /\ j = 2 * bGrammar.SynNoLT
04-derives.spectec:382No line terminator precedes the token at boundary i (a virtual ; has none).
def SynNoLT (src : List(Nat)) (first : Bool) (vs : List(Nat times Bool)) (i : Nat) : Prop := vsPending(vs, i) = true \/ exists k lt, Trivia(gl, cx, P, src, first, i / 2, k, lt) /\ (src.length <= k \/ lt = false)Grammar.SynLook
04-derives.spectec:385The boundary a lookahead reads from i: past a waiting virtual ;.
def SynLook (vs : List(Nat times Bool)) (i : Nat) : Nat := if vsPending(vs, i) then i + 1 else iGrammar.SynStarts
04-derives.spectec:388The source tokens from boundary i start with the lookahead sequence.
def SynStarts (src : List(Nat)) (first : Bool) (vs : List(Nat times Bool)) : List(LookItem) -> Nat -> Prop | [], _ => True | .noLT :: rest, i => SynNoLT(gl, cx, P, src, first, vs, SynLook(vs, i)) /\ SynStarts(src, first, vs, rest, i) | .t(.text(str, _)) :: rest, i => exists a b lt tr, ScanTok(gl, cx, P, src, first, .InputElementDiv, SynLook(vs, i) / 2, a, b, lt, tr) /\ noCross(vs, SynLook(vs, i) / 2, b) = true /\ slice(src, a, b) = str.toList.map(Char.toNat) /\ SynStarts(src, first, vs, rest, 2 * b) | .t(.cp(_)) :: _, _ => Falseend
Grammar.SynLookOk
04-derives.spectec:396A syntactic lookahead restriction holds at boundary i.
def SynLookOk (src : List(Nat)) (first : Bool) (vs : List(Nat times Bool)) : Lookahead -> Nat -> Prop | .eq(q), i => SynStarts(gl, cx, P, src, first, vs, q, i) | .ne(q), i => not SynStarts(gl, cx, P, src, first, vs, q, i) | .mem(qs), i => exists q mem qs, SynStarts(gl, cx, P, src, first, vs, q, i) | .notMem(qs), i => forall q mem qs, not SynStarts(gl, cx, P, src, first, vs, q, i) | .notMemNT(_), _ => Trueend
Grammar.SynSymEx
04-derives.spectec:405One symbol of a syntactic but not exclusion holds over boundaries i to h.
def SynSymEx (src : List(Nat)) (first : Bool) (vs : List(Nat times Bool)) (s : Src) (k : Nat) (i h : Nat) : Sym -> Prop | .t(x) => SynTerm(gl, cx, P, src, first, vs, s, k, x, i, h) | .nt(n, _) => gl.alts(cx, .syntactic, n) = [] /\ SynLeaf(gl, cx, P, src, first, vs, n, i, h)end
Grammar.SynExcluded
04-derives.spectec:411A syntactic but not exclusion holds over boundaries i to h.
def SynExcluded (src : List(Nat)) (first : Bool) (vs : List(Nat times Bool)) (s : Src) (k : Nat) (i h : Nat) : Exclusion -> Prop | .sym(y) => SynSymEx(gl, cx, P, src, first, vs, s, k, i, h, y) | .oneOf(ys, _) => exists y mem ys, SynSymEx(gl, cx, P, src, first, vs, s, k, i, h, y)end
Grammar.noCondAfter
04-derives.spectec:417No [> but only if …] condition immediately follows this item.
def noCondAfter : List(Item) -> Bool | .onlyIf(_) :: _ => false | _ => trueend
Grammar.SynDerives
04-derives.spectec:428Syntactic nonterminal n with ps derives boundaries i to j under virtual semicolons vs (§5.1.5, sec-syntactic-grammar; §12.10, sec-automatic-semicolon-insertion).
relation SynDerives : NT -> List(Param) -> Nat -> Nat -> Proprule node {n ps i j} (s : Src) : SynDerives(n, ps, i, j) :- s mem gl.alts(cx, .syntactic, n), s.alt.guard.all(Guard.holds(ps)) = true, SynSeq(s, ps, 0, s.alt.rhs, i, j);Grammar.SynSeq
04-derives.spectec:434Right-hand side items from index k of s derive boundaries i to j under vs (§5.1.5, sec-syntactic-grammar; §12.10, sec-automatic-semicolon-insertion).
relation SynSeq : Src -> List(Param) -> Nat -> List(Item) -> Nat -> Nat -> Proprule nil {s ps k i} : SynSeq(s, ps, k, [], i, i);rule absent {s ps k x is i j} : SynSeq(s, ps, k, .sym(x, true) :: is, i, j) :- SynSeq(s, ps, k + 1, is, i, j);rule term {s ps k x o is i h j} : SynSeq(s, ps, k, .sym(.t(x), o) :: is, i, j) :- SynTerm(gl, cx, P, src, first, vs, s, k, x, i, h), SynSeq(s, ps, k + 1, is, h, j);rule nt {s ps k n args o is i h j} : SynSeq(s, ps, k, .sym(.nt(n, args), o) :: is, i, j) :- gl.alts(cx, .syntactic, n) <> [], SynDerives(n, applyArgs(ps, args), i, h), forKeep(s.rule.lhs, n, h) = true, noCondAfter(is) = true, SynSeq(s, ps, k + 1, is, h, j);rule leaf {s ps k n args o is i h j} : SynSeq(s, ps, k, .sym(.nt(n, args), o) :: is, i, j) :- gl.alts(cx, .syntactic, n) = [], SynLeaf(gl, cx, P, src, first, vs, n, i, h), forKeep(s.rule.lhs, n, h) = true, noCondAfter(is) = true, SynSeq(s, ps, k + 1, is, h, j);rule butNotT {s ps k x ex is i h j} : SynSeq(s, ps, k, .butNot(.t(x), ex) :: is, i, j) :- SynTerm(gl, cx, P, src, first, vs, s, k, x, i, h), not SynExcluded(gl, cx, P, src, first, vs, s, k, i, h, ex), SynSeq(s, ps, k + 1, is, h, j);rule butNotN {s ps k n args ex is i h j} : SynSeq(s, ps, k, .butNot(.nt(n, args), ex) :: is, i, j) :- gl.alts(cx, .syntactic, n) <> [], SynDerives(n, applyArgs(ps, args), i, h), not SynExcluded(gl, cx, P, src, first, vs, s, k, i, h, ex), SynSeq(s, ps, k + 1, is, h, j);rule butNotLeaf {s ps k n args ex is i h j} : SynSeq(s, ps, k, .butNot(.nt(n, args), ex) :: is, i, j) :- gl.alts(cx, .syntactic, n) = [], SynLeaf(gl, cx, P, src, first, vs, n, i, h), not SynExcluded(gl, cx, P, src, first, vs, s, k, i, h, ex), SynSeq(s, ps, k + 1, is, h, j);rule look {s ps k l is i j} : SynSeq(s, ps, k, .lookahead(l) :: is, i, j) :- SynLookOk(gl, cx, P, src, first, vs, l, i), SynSeq(s, ps, k + 1, is, i, j);rule noLT {s ps k is i j} : SynSeq(s, ps, k, .noLT :: is, i, j) :- SynNoLT(gl, cx, P, src, first, vs, i), SynSeq(s, ps, k + 1, is, i, j);rule empty {s ps k is i j} : SynSeq(s, ps, k, .empty :: is, i, j) :- SynSeq(s, ps, k + 1, is, i, j);rule onlyIf {s ps k c is i j} : SynSeq(s, ps, k, .onlyIf(c) :: is, i, j) :- SynSeq(s, ps, k + 1, is, i, j);Grammar.SynOpen
04-derives.spectec:455Nonterminal n with ps is opened at boundary i when parsing left to right from (goal, goalPs, 0) (§12.10, sec-automatic-semicolon-insertion).
relation SynOpen : NT -> List(Param) -> Nat -> Proprule root : SynOpen(goal, goalPs, 0);rule nt {s ps k n args o is i} : SynOpen(n, applyArgs(ps, args), i) :- SynPrefix(s, ps, k, .sym(.nt(n, args), o) :: is, i), gl.alts(cx, .syntactic, n) <> [];rule butNotN {s ps k n args ex is i} : SynOpen(n, applyArgs(ps, args), i) :- SynPrefix(s, ps, k, .butNot(.nt(n, args), ex) :: is, i), gl.alts(cx, .syntactic, n) <> [];Grammar.SynPrefix
04-derives.spectec:463Item k on of s is reached at boundary i when parsing left to right from (goal, goalPs, 0) (§12.10, sec-automatic-semicolon-insertion).
relation SynPrefix : Src -> List(Param) -> Nat -> List(Item) -> Nat -> Proprule enter {n ps i} (s : Src) : SynPrefix(s, ps, 0, s.alt.rhs, i) :- SynOpen(n, ps, i), s mem gl.alts(cx, .syntactic, n), s.alt.guard.all(Guard.holds(ps)) = true;rule absent {s ps k x is i} : SynPrefix(s, ps, k + 1, is, i) :- SynPrefix(s, ps, k, .sym(x, true) :: is, i);rule term {s ps k x o is i h} : SynPrefix(s, ps, k + 1, is, h) :- SynPrefix(s, ps, k, .sym(.t(x), o) :: is, i), SynTerm(gl, cx, P, src, first, vs, s, k, x, i, h);rule nt {s ps k n args o is i h} : SynPrefix(s, ps, k + 1, is, h) :- SynPrefix(s, ps, k, .sym(.nt(n, args), o) :: is, i), gl.alts(cx, .syntactic, n) <> [], SynDerives(gl, cx, P, src, first, vs, n, applyArgs(ps, args), i, h), forKeep(s.rule.lhs, n, h) = true, noCondAfter(is) = true;rule leaf {s ps k n args o is i h} : SynPrefix(s, ps, k + 1, is, h) :- SynPrefix(s, ps, k, .sym(.nt(n, args), o) :: is, i), gl.alts(cx, .syntactic, n) = [], SynLeaf(gl, cx, P, src, first, vs, n, i, h), forKeep(s.rule.lhs, n, h) = true, noCondAfter(is) = true;rule butNotT {s ps k x ex is i h} : SynPrefix(s, ps, k + 1, is, h) :- SynPrefix(s, ps, k, .butNot(.t(x), ex) :: is, i), SynTerm(gl, cx, P, src, first, vs, s, k, x, i, h), not SynExcluded(gl, cx, P, src, first, vs, s, k, i, h, ex);rule butNotN {s ps k n args ex is i h} : SynPrefix(s, ps, k + 1, is, h) :- SynPrefix(s, ps, k, .butNot(.nt(n, args), ex) :: is, i), gl.alts(cx, .syntactic, n) <> [], SynDerives(gl, cx, P, src, first, vs, n, applyArgs(ps, args), i, h), not SynExcluded(gl, cx, P, src, first, vs, s, k, i, h, ex);rule butNotLeaf {s ps k n args ex is i h} : SynPrefix(s, ps, k + 1, is, h) :- SynPrefix(s, ps, k, .butNot(.nt(n, args), ex) :: is, i), gl.alts(cx, .syntactic, n) = [], SynLeaf(gl, cx, P, src, first, vs, n, i, h), not SynExcluded(gl, cx, P, src, first, vs, s, k, i, h, ex);rule look {s ps k l is i} : SynPrefix(s, ps, k + 1, is, i) :- SynPrefix(s, ps, k, .lookahead(l) :: is, i), SynLookOk(gl, cx, P, src, first, vs, l, i);rule noLT {s ps k is i} : SynPrefix(s, ps, k + 1, is, i) :- SynPrefix(s, ps, k, .noLT :: is, i), SynNoLT(gl, cx, P, src, first, vs, i);rule empty {s ps k is i} : SynPrefix(s, ps, k + 1, is, i) :- SynPrefix(s, ps, k, .empty :: is, i);rule onlyIf {s ps k c is i} : SynPrefix(s, ps, k + 1, is, i) :- SynPrefix(s, ps, k, .onlyIf(c) :: is, i);Grammar.SynHit
04-derives.spectec:481Boundary h is reached by a match when parsing left to right from (goal, goalPs, 0) (§12.10, sec-automatic-semicolon-insertion).
relation SynHit : Nat -> Proprule zero : SynHit(0);rule term {s ps k x o is i h} : SynHit(h) :- SynPrefix(gl, cx, P, src, first, vs, goal, goalPs, s, ps, k, .sym(.t(x), o) :: is, i), SynTerm(gl, cx, P, src, first, vs, s, k, x, i, h);rule nt {s ps k n args o is i h} : SynHit(h) :- SynPrefix(gl, cx, P, src, first, vs, goal, goalPs, s, ps, k, .sym(.nt(n, args), o) :: is, i), gl.alts(cx, .syntactic, n) <> [], SynDerives(gl, cx, P, src, first, vs, n, applyArgs(ps, args), i, h), forKeep(s.rule.lhs, n, h) = true, noCondAfter(is) = true;rule leaf {s ps k n args o is i h} : SynHit(h) :- SynPrefix(gl, cx, P, src, first, vs, goal, goalPs, s, ps, k, .sym(.nt(n, args), o) :: is, i), gl.alts(cx, .syntactic, n) = [], SynLeaf(gl, cx, P, src, first, vs, n, i, h), forKeep(s.rule.lhs, n, h) = true, noCondAfter(is) = true;rule butNotT {s ps k x ex is i h} : SynHit(h) :- SynPrefix(gl, cx, P, src, first, vs, goal, goalPs, s, ps, k, .butNot(.t(x), ex) :: is, i), SynTerm(gl, cx, P, src, first, vs, s, k, x, i, h), not SynExcluded(gl, cx, P, src, first, vs, s, k, i, h, ex);rule butNotN {s ps k n args ex is i h} : SynHit(h) :- SynPrefix(gl, cx, P, src, first, vs, goal, goalPs, s, ps, k, .butNot(.nt(n, args), ex) :: is, i), gl.alts(cx, .syntactic, n) <> [], SynDerives(gl, cx, P, src, first, vs, n, applyArgs(ps, args), i, h), not SynExcluded(gl, cx, P, src, first, vs, s, k, i, h, ex);rule butNotLeaf {s ps k n args ex is i h} : SynHit(h) :- SynPrefix(gl, cx, P, src, first, vs, goal, goalPs, s, ps, k, .butNot(.nt(n, args), ex) :: is, i), gl.alts(cx, .syntactic, n) = [], SynLeaf(gl, cx, P, src, first, vs, n, i, h), not SynExcluded(gl, cx, P, src, first, vs, s, k, i, h, ex);Auxiliary definitions (2): Grammar.SynDone, Grammar.NextASI
Grammar.SynDone
04-derives.spectec:493A derivation of (goal, ps) spans the source text under virtual semicolons vs, none left after it.
def SynDone (src : List(Nat)) (first : Bool) (vs : List(Nat times Bool)) (goal : NT) (ps : List(Param)) : Prop := exists e k lt, SynDerives(gl, cx, P, src, first, vs, goal, ps, 0, e) /\ Trivia(gl, cx, P, src, first, e / 2, k, lt) /\ src.length <= k /\ vsPending(vs, e) = false /\ vs.all(fun (p, _) => p <= e / 2) = trueGrammar.NextASI
04-derives.spectec:498§12.10: when no derivation spans the source text under vs, the next virtual ; goes at the furthest boundary reached (f = 2 * p), at end of input or before an offending token after a line terminator, }, or ) (for do-while).
def NextASI (src : List(Nat)) (first : Bool) (vs : List(Nat times Bool)) (goal : NT) (ps : List(Param)) (p : Nat) (paren : Bool) : Prop := not SynDone(gl, cx, P, src, first, vs, goal, ps) /\ exists f, SynHit(gl, cx, P, src, first, vs, goal, ps, f) /\ (forall h, SynHit(gl, cx, P, src, first, vs, goal, ps, h) -> h <= f) /\ f % 2 = 0 /\ p = f / 2 /\ vs.all(fun (q, _) => q != p) = true /\ ((exists k lt, Trivia(gl, cx, P, src, first, p, k, lt) /\ src.length <= k /\ paren = false) \/ exists a b lt tr, ScanTok(gl, cx, P, src, first, .InputElementDiv, p, a, b, lt, tr) /\ if lt || slice(src, a, b) == "}".toList.map(Char.toNat) then paren = false else 0 < p /\ src[p - 1]? = some(0x29) /\ paren = true)Grammar.ValidASI
04-derives.spectec:501The virtual semicolons §12.10 (sec-automatic-semicolon-insertion) inserts left to right from empty.
relation ValidASI (src : List(Nat)) (first : Bool) (goal : NT) (ps : List(Param)) : List(Nat times Bool) -> PropAuxiliary definitions (3): Grammar.tokPos, Grammar.toksMatchASI, Grammar.ASIOk
Grammar.tokPos
04-derives.spectec:507The code point after the last real token before index k of toks (0 before the first).
def tokPos (els : List(Element)) (toks : List(Token)) (k : Nat) : Nat := let es := els.filter(Element.isToken) in let r := toks.take(k).countP(fun tok => tok.virt.isNone) in if r == 0 then 0 else es[r - 1]?.map(fun e => e.j).getD(0)Grammar.toksMatchASI
04-derives.spectec:510The virtual semicolons of toks are vs at their token boundaries, none adjacent.
def toksMatchASI (els : List(Element)) (toks : List(Token)) (vs : List(Nat times Bool)) : Prop := (forall k t1 t2, toks[k]? = some(t1) -> toks[k + 1]? = some(t2) -> t1.virt = none \/ t2.virt = none) /\ (forall k tok why, toks[k]? = some(tok) -> tok.virt = some(why) -> (let w := if vsParen(vs, tokPos(els, toks, k)) then .paren else if k + 1 == toks.length then .eof else .offending in why = w /\ (tokPos(els, toks, k), vsParen(vs, tokPos(els, toks, k))) mem vs)) /\ forall p paren, (p, paren) mem vs -> (exists k tok, toks[k]? = some(tok) /\ tok.virt.isSome = true /\ tokPos(els, toks, k) = p)Grammar.ASIOk
04-derives.spectec:513§12.10: the virtual semicolons of toks are a sequence ValidASI inserts left to right.
def ASIOk (goal : NT) (ps : List(Param)) (src : List(Nat)) (els : List(Element)) (toks : List(Token)) : Prop := exists vs, ValidASI(gl, cx, P, src, goal == .Script || goal == .Module, goal, ps, vs) /\ toksMatchASI(els, toks, vs)B.1.2: ordered alternatives and the group-number condition
Auxiliary definitions (7): Grammar.Tree.Commits, Grammar.Committed, Grammar.CodePrims.withGroup, Grammar.Tree.countProds, …
Grammar.Tree.Commits
04-derives.spectec:520B.1.2's "each alternative is considered only if previous production alternatives do not match", as commitment: a node of a nonterminal B.1.2 restates (GL.orderedNts) at i uses an alternative only if no earlier alternative of it derives (in D) any span from i.
def Tree.Commits (g : GrammarId) (D : NT -> List(Param) -> Nat -> Nat -> Tree -> Prop) : Tree -> Prop | .leaf(..) => True | .lex(_, t) => t.Commits(g, D) | .node(n, id, ps, i, _, kids) => (n mem gl.orderedNts(cx, g) -> (forall h id' kids' k k', D(n, ps, i, h, .node(n, id', ps, i, h, kids')) -> gl.altPos(cx, g, n, id) = some(k) -> gl.altPos(cx, g, n, id') = some(k') -> k <= k')) /\ all(kids)endwhere { all : List(Tree) -> Prop | [] => True | d :: ds => d.Commits(g, D) /\ all(ds) end}
Grammar.Committed
04-derives.spectec:534A parse of the whole input with B.1.2's ordered alternatives: a derivation whose every node commits (Tree.Commits), an earlier alternative's match read in Derives.
def Committed (g : GrammarId) (goal : NT) (ps : List(Param)) (src : List(Nat)) (t : Tree) : Prop := Derives(gl, cx, g, codeAlphabet(P), src, goal, ps, 0, src.length, t) /\ t.Commits(gl, cx, g, Derives(gl, cx, g, codeAlphabet(P), src))Grammar.CodePrims.withGroup
04-derives.spectec:537The primitives with c as B.1.2's group-number condition.
def CodePrims.withGroup (P : CodePrims) (c : List(Nat) -> Tree -> Prop) : CodePrims := { P with cond := fun p => match p with | .groupNumberAtMostCount => c | p => P.cond(p)end }
Grammar.Tree.countProds
04-derives.spectec:543The nodes of a tree whose production is one of ids, the tree's own included.
def Tree.countProds (ids : List(Nat)) : Tree -> Nat | .leaf(..) => 0 | .lex(_, t) => t.countProds(ids) | .node(_, id, _, _, _, kids) => (if ids.contains(id) then 1 else 0) + kids.attach.map(fun ctor(k, _) => k.countProds(ids)).sumend
Grammar.decimalMV
04-derives.spectec:550§22.2.1.5 CapturingGroupNumber: the MV of a DecimalEscape's code points, decimal digits.
def decimalMV (cs : List(Nat)) : Nat := cs.foldl(fun a c => 10 * a + (c - 0x30), 0)Grammar.groupCond
04-derives.spectec:562B.1.2's condition of AtomEscape :: DecimalEscape, stratified: the CapturingGroupNumber of the DecimalEscape t is at most CountLeftCapturingParensWithin (§22.2.1.2, B.1.2.2) of a committed parse of the input as Pattern[~UnicodeMode, ~UnicodeSetsMode, ~NamedCaptureGroups] with the condition true ("the Pattern containing DecimalEscape" being the tree the condition selects).
def groupCond (inp : List(Nat)) (t : Tree) : Prop := exists T, Committed(gl, cx, P.withGroup(fun _ _ => True), .regExp, .Pattern, [], inp, T) /\ decimalMV(slice(inp, t.span.1, t.span.2)) <= T.countProds(gl.capturingIds)Grammar.ParsesCode
04-derives.spectec:567A code point grammar's goal (RegExp's Pattern, the numeric string grammar's) parses the text as t; with B.1.2's ordered alternatives, a committed parse, its group-number condition groupCond.
def ParsesCode (g : GrammarId) (goal : NT) (ps : List(Param)) (src : List(Nat)) (t : Tree) : Prop := if gl.ordered(cx, g) then Committed(gl, cx, P.withGroup(groupCond(gl, cx, P)), g, goal, ps, src, t) else Derives(gl, cx, g, codeAlphabet(P), src, goal, ps, 0, src.length, t)Strict mode code (§11.2.2)
From spec/spectec/prose/03-strict-code.spectec
strictCode V up t: the source text the Parse Node t matches is strict mode code by the tree it is in, up being t's ancestors, nearest first (sec-strict-mode-code). Module code, a ClassDeclaration or ClassExpression, global or eval code or a parsed function body whose Directive Prologue contains a Use Strict Directive (prologueStrict, sec-directive-prologues-and-the-use-strict-directive), and function code by its own Directive Prologue or the code containing its function form. A function form's node and a method's ClassElementName are the containing code. Strictness from outside the parse (eval code of a direct eval contained in strict mode code) is the parse context's, not the tree's.
One definition, read through a view of a tree's Parse Nodes (NodeView): the parse relation reads it over its derivation trees (Grammar.StrictCode, for NonStrictOk), the machine over the model's Parse Nodes (the primitives StrictModeCode and HasUseStrictDirective, Ecma.Prims.Nodes).
Grammar.NodeView
03-strict-code.spectec:24What §11.2.1 (sec-directive-prologues-and-the-use-strict-directive) and §11.2.2 (sec-strict-mode-code) read of a tree's Parse Nodes: a node's nonterminal, its children that are Parse Nodes of nonterminals (left to right), the span of source text it matched, whether that source text is a given sequence of code points, and a bound on the depth of the tree below it (more than each child's: the walks below go no deeper).
syntax NodeView (N : Type) recordAuxiliary definitions (14): Grammar.functionForms, Grammar.classForms, Grammar.bodyPath, Grammar.bodyGoals, …
Grammar.functionForms
03-strict-code.spectec:33§11.2.2's function forms, each with function code of its own.
def functionForms : List(NT) := [.FunctionDeclaration, .FunctionExpression, .GeneratorDeclaration, .GeneratorExpression, .AsyncFunctionDeclaration, .AsyncFunctionExpression, .AsyncGeneratorDeclaration, .AsyncGeneratorExpression, .MethodDefinition, .ArrowFunction, .AsyncArrowFunction]Grammar.classForms
03-strict-code.spectec:36The forms all parts of which are strict mode code.
def classForms : List(NT) := [.ClassDeclaration, .ClassExpression]Grammar.bodyPath
03-strict-code.spectec:39The nonterminals from a function form down to its FunctionBody.
def bodyPath : List(NT) := [.FunctionBody, .GeneratorBody, .AsyncFunctionBody, .AsyncGeneratorBody, .ConciseBody, .AsyncConciseBody, .GeneratorMethod, .AsyncMethod, .AsyncGeneratorMethod]Grammar.bodyGoals
03-strict-code.spectec:42The goals of a parse whose code is a function's body (CreateDynamicFunction's).
def bodyGoals : List(NT) := [.FunctionBody, .GeneratorBody, .AsyncFunctionBody, .AsyncGeneratorBody]Grammar.useStrictTexts
03-strict-code.spectec:45The code points of a Use Strict Directive's StringLiteral: "use strict" and 'use strict'.
def useStrictTexts : List(List(Nat)) := ["\"use strict\"", "'use strict'"].map(fun s => s.toList.map(Char.toNat))Grammar.NodeView.isIn
03-strict-code.spectec:50The node is an instance of one of the nonterminals.
def NodeView.isIn (ns : List(NT)) (t : N) : Bool := ns.any(V.isA(t))Grammar.oneNode
03-strict-code.spectec:54A node of m spans sp within t, t included, each node on the way spanning it too, within depth d.
def oneNode (m : NT) (sp : Nat times Nat) : Nat -> N -> Bool | 0, _ => false | d + 1, t => V.span(t) == sp && (V.isA(t, m) || V.kids(t).any(oneNode(m, sp, d)))end
Grammar.directive
03-strict-code.spectec:62§11.2.1: the StatementListItem item is a directive, an ExpressionStatement whose Expression is one StringLiteral token: some u, u whether it is a Use Strict Directive (its StringLiteral exactly "use strict" or 'use strict'); none for another item.
def directive (d : Nat) (item : N) : Option(Bool) := match V.kids(item) with | [s] => if !V.isA(s, .Statement) then none else match V.kids(s) with | [es] => if !V.isA(es, .ExpressionStatement) then none else match V.kids(es) with | [e] => if V.isA(e, .Expression) && oneNode(V, .StringLiteral, V.span(e), d, e) then some(useStrictTexts.any(V.textIs(e))) else none | _ => none end | _ => none end | _ => noneend
Grammar.prologueScan
03-strict-code.spectec:76The StatementListItems of t that are within no other, in source text order, read until one decides: some true at a Use Strict Directive, some false at an item that is no directive; none where each is a directive and none a Use Strict Directive. Within depth d.
def prologueScan : Nat -> N -> Option(Bool) | 0, _ => some(false) | d + 1, t => if V.isA(t, .StatementListItem) then match directive(V, d, t) with | some(true) => some(true) | some(false) => none | none => some(false) end else V.kids(t).findSome?(prologueScan(d))end
Grammar.prologueStrict
03-strict-code.spectec:87§11.2.1: the Directive Prologue of body, the longest initial sequence of its StatementListItems that are directives, contains a Use Strict Directive.
def prologueStrict (body : N) : Bool := prologueScan(V, V.height(body), body) == some(true)Grammar.bodyOf
03-strict-code.spectec:91The FunctionBody of a function form or of a body goal's root (none for a concise body), within depth d.
def bodyOf : Nat -> N -> Option(N) | 0, _ => none | d + 1, t => if V.isA(t, .FunctionBody) then some(t) else V.kids(t).findSome?(fun k => if V.isIn(bodyPath, k) then bodyOf(d, k) else none)end
Grammar.bodyStrict
03-strict-code.spectec:97The function form f's body begins with a Directive Prologue that contains a Use Strict Directive.
def bodyStrict (f : N) : Bool := bodyOf(V, V.height(f), f).any(prologueStrict(V))Grammar.strictDown
03-strict-code.spectec:102Down the path from a node to t, s the strictness of the code containing the path's first: a class form's parts are strict; below a function form its function code is, by its body or s, but for a method's ClassElementName, which is the code containing the method.
def strictDown (s : Bool) : List(N) -> Bool | [] => s | [t] => s || V.isIn(classForms, t) | f :: rest => if V.isIn(classForms, f) then true else if V.isIn(functionForms, f) then if V.isA(f, .MethodDefinition) && rest.takeWhile(fun _dot0 => !V.isIn(functionForms ++ classForms, _dot0)).any(fun _dot0 => V.isA(_dot0, .ClassElementName)) then strictDown(s, rest) else strictDown(s || bodyStrict(V, f), rest) else strictDown(s, rest)end
Grammar.strictCode
03-strict-code.spectec:112§11.2.2 ("Code is interpreted as strict mode code in the following situations"), by the tree: the source text t matches is strict mode code, up being its ancestors nearest first: by the code of the root (the goal: a Module, a Script's global or eval code, a parsed function body) and the forms from it down to t.
def strictCode (up : List(N)) (t : N) : Bool := match up.reverse ++ [t] with | [] => false | root :: path => let top := if V.isA(root, .Module) then true else if V.isA(root, .Script) then prologueStrict(V, root) else V.isIn(bodyGoals, root) && bodyStrict(V, root) in strictDown(V, top, root :: path)end
Grammar notation (§5.1.6)
From lean/Ecma/Grammar/Gen/Symbols.lean
Generated by lean/SpecTec from spec/spectec/. Do not edit.
Grammar.Param
Symbols.lean:14Grammar parameters (§5.1.6, sec-grammar-notation), sorted alphabetically from spec/spectec/.
inductive Param where| Await| Default| Extended| In| NamedCaptureGroups| Pattern| Return| Sep| Tagged| UnicodeMode| UnicodeSetsMode| Using| YieldGrammar.NT
Symbols.lean:46Grammar nonterminals (§5.1, sec-syntactic-and-lexical-grammars; Annex A, sec-grammar-summary), sorted alphabetically from spec/spectec/.
inductive NT where426 constructors
| ASCIISign| AdditiveExpression| Alternative| ArgumentList| Arguments| ArrayAssignmentPattern| ArrayBindingPattern| ArrayLiteral| ArrowFormalParameters| ArrowFunction| ArrowParameters| AsciiLetter| Assertion| AssignmentElement| AssignmentElementList| AssignmentElisionElement| AssignmentExpression| AssignmentOperator| AssignmentPattern| AssignmentProperty| AssignmentPropertyList| AssignmentRestElement| AssignmentRestProperty| AsyncArrowBindingIdentifier| AsyncArrowFunction| AsyncArrowHead| AsyncConciseBody| AsyncFunctionBody| AsyncFunctionDeclaration| AsyncFunctionExpression| AsyncGeneratorBody| AsyncGeneratorDeclaration| AsyncGeneratorExpression| AsyncGeneratorMethod| AsyncMethod| Atom| AtomEscape| AttributeKey| AwaitExpression| AwaitUsingDeclaration| AwaitUsingDeclarationHead| BigIntLiteralSuffix| BinaryDigit| BinaryDigits| BinaryIntegerLiteral| BindingElement| BindingElementList| BindingElisionElement| BindingIdentifier| BindingList| BindingPattern| BindingProperty| BindingPropertyList| BindingRestElement| BindingRestProperty| BitwiseANDExpression| BitwiseORExpression| BitwiseXORExpression| Block| BlockStatement| BooleanLiteral| BreakStatement| BreakableStatement| CallExpression| CallMemberExpression| CaseBlock| CaseClause| CaseClauses| Catch| CatchParameter| CharacterClass| CharacterClassEscape| CharacterEscape| CharacterEscapeSequence| ClassAtom| ClassAtomNoDash| ClassBody| ClassContents| ClassControlLetter| ClassDeclaration| ClassElement| ClassElementList| ClassElementName| ClassEscape| ClassExpression| ClassHeritage| ClassIntersection| ClassSetCharacter| ClassSetExpression| ClassSetOperand| ClassSetRange| ClassSetReservedDoublePunctuator| ClassSetReservedPunctuator| ClassSetSyntaxCharacter| ClassStaticBlock| ClassStaticBlockBody| ClassStaticBlockStatementList| ClassString| ClassStringDisjunction| ClassStringDisjunctionContents| ClassSubtraction| ClassTail| ClassUnion| CoalesceExpression| CoalesceExpressionHead| CodePoint| Comment| CommonToken| ComputedPropertyName| ConciseBody| ConditionalExpression| ContinueStatement| ControlEscape| CoverAwaitExpressionAndAwaitUsingDeclarationHead| CoverCallExpressionAndAsyncArrowHead| CoverInitializedName| CoverParenthesizedExpressionAndArrowParameterList| DebuggerStatement| DecimalBigIntegerLiteral| DecimalDigit| DecimalDigits| DecimalEscape| DecimalIntegerLiteral| DecimalLiteral| Declaration| DefaultClause| DestructuringAssignmentTarget| Disjunction| DivPunctuator| DoWhileStatement| DoubleStringCharacter| DoubleStringCharacters| ElementList| Elision| EmptyStatement| EqualityExpression| EscapeCharacter| EscapeSequence| ExponentIndicator| ExponentPart| ExponentiationExpression| ExportDeclaration| ExportFromClause| ExportSpecifier| ExportsList| Expression| ExpressionBody| ExpressionStatement| ExtendedAtom| ExtendedPatternCharacter| FieldDefinition| Finally| FirstCommentLine| ForBinding| ForDeclaration| ForInOfStatement| ForStatement| FormalParameter| FormalParameterList| FormalParameters| FourToSeven| FromClause| FunctionBody| FunctionDeclaration| FunctionExpression| FunctionRestParameter| FunctionStatementList| GeneratorBody| GeneratorDeclaration| GeneratorExpression| GeneratorMethod| GroupName| GroupSpecifier| HTMLCloseComment| HashbangComment| Hex4Digits| HexDigit| HexDigits| HexEscapeSequence| HexIntegerLiteral| HexLeadSurrogate| HexNonSurrogate| HexTrailSurrogate| HoistableDeclaration| Hour| HourSubcomponents| Identifier| IdentifierName| IdentifierPart| IdentifierPartChar| IdentifierReference| IdentifierStart| IdentifierStartChar| IdentityEscape| IfStatement| ImportCall| ImportClause| ImportDeclaration| ImportMeta| ImportSpecifier| ImportedBinding| ImportedDefaultBinding| ImportsList| Initializer| InputElementDiv| InputElementHashbangOrRegExp| InputElementRegExp| InputElementRegExpOrTemplateTail| InputElementTemplateTail| InvalidBracedQuantifier| IterationStatement| JSONArray| JSONCodePoint| JSONControlCharacter| JSONDigit| JSONDigits| JSONElement| JSONElements| JSONEscape| JSONExponent| JSONExponentIndicator| JSONFraction| JSONHexDigit| JSONInteger| JSONMember| JSONMembers| JSONNonZeroDigit| JSONNumber| JSONObject| JSONSign| JSONSingleEscapeCharacter| JSONString| JSONStringCharacter| JSONStringCharacters| JSONText| JSONValue| JSONWhiteSpace| JSONWhiteSpaceCharacter| LabelIdentifier| LabelledItem| LabelledStatement| LeftHandSideExpression| LegacyOctalEscapeSequence| LegacyOctalIntegerLiteral| LegacyOctalLikeDecimalDigits| LetOrConst| LexicalBinding| LexicalDeclaration| LineContinuation| LineTerminator| LineTerminatorSequence| Literal| LiteralPropertyName| LogicalANDExpression| LogicalORExpression| LoneUnicodePropertyNameOrValue| MemberExpression| MetaProperty| MethodDefinition| MinuteSecond| Module| ModuleBody| ModuleExportName| ModuleItem| ModuleItemList| ModuleSpecifier| MultiLineComment| MultiLineCommentChars| MultiLineNotAsteriskChar| MultiLineNotForwardSlashOrAsteriskChar| MultiplicativeExpression| MultiplicativeOperator| NameSpaceImport| NamedExports| NamedImports| NativeFunction| NativeFunctionAccessor| NestedClass| NewExpression| NewTarget| NoSubstitutionTemplate| NonDecimalIntegerLiteral| NonEmptyClassString| NonEscapeCharacter| NonOctalDecimalEscapeSequence| NonOctalDecimalIntegerLiteral| NonOctalDigit| NonZeroDigit| NonZeroOctalDigit| NonemptyClassRanges| NonemptyClassRangesNoDash| NotCodePoint| NotEscapeSequence| NullLiteral| NumericLiteral| NumericLiteralSeparator| ObjectAssignmentPattern| ObjectBindingPattern| ObjectLiteral| OctalDigit| OctalDigits| OctalIntegerLiteral| OptionalChain| OptionalChainingPunctuator| OptionalExpression| OtherPunctuator| ParenthesizedExpression| Pattern| PatternCharacter| PostAsteriskCommentChars| PrimaryExpression| PrivateIdentifier| PropertyDefinition| PropertyDefinitionList| PropertyName| PropertySetParameterList| Punctuator| QuantifiableAssertion| Quantifier| QuantifierPrefix| RegExpIdentifierName| RegExpIdentifierPart| RegExpIdentifierStart| RegExpUnicodeEscapeSequence| RegularExpressionBackslashSequence| RegularExpressionBody| RegularExpressionChar| RegularExpressionChars| RegularExpressionClass| RegularExpressionClassChar| RegularExpressionClassChars| RegularExpressionFirstChar| RegularExpressionFlags| RegularExpressionLiteral| RegularExpressionModifier| RegularExpressionModifiers| RegularExpressionNonTerminator| RelationalExpression| ReservedWord| ReturnStatement| RightBracePunctuator| Script| ScriptBody| ShiftExpression| ShortCircuitExpression| SignedInteger| SingleEscapeCharacter| SingleLineComment| SingleLineCommentChar| SingleLineCommentChars| SingleLineDelimitedComment| SingleLineDelimitedCommentChars| SingleLineDelimitedCommentSequence| SingleLineHTMLCloseComment| SingleLineHTMLOpenComment| SingleLineNotAsteriskChar| SingleLineNotForwardSlashOrAsteriskChar| SingleLinePostAsteriskCommentChars| SingleNameBinding| SingleStringCharacter| SingleStringCharacters| SourceCharacter| SourceCharacterIdentityEscape| SpreadElement| Statement| StatementList| StatementListItem| StrDecimalLiteral| StrIntegerLiteral| StrNumericLiteral| StrUnsignedDecimalLiteral| StrWhiteSpace| StrWhiteSpaceChar| StringIntegerLiteral| StringLiteral| StringNumericLiteral| SubstitutionTemplate| SuperCall| SuperProperty| SwitchStatement| SyntaxCharacter| Template| TemplateCharacter| TemplateCharacters| TemplateEscapeSequence| TemplateHead| TemplateLiteral| TemplateMiddle| TemplateMiddleList| TemplateSpans| TemplateSubstitutionTail| TemplateTail| TemporalDecimalFraction| TemporalDecimalSeparator| Term| ThrowStatement| TimeSeparator| TryStatement| UTCOffset| UnaryExpression| UnicodeEscapeSequence| UnicodeIDContinue| UnicodeIDStart| UnicodeLeadSurrogate| UnicodePropertyName| UnicodePropertyNameCharacter| UnicodePropertyNameCharacters| UnicodePropertyValue| UnicodePropertyValueCharacter| UnicodePropertyValueCharacters| UnicodePropertyValueExpression| UnicodeTrailSurrogate| UniqueFormalParameters| UpdateExpression| UsingDeclaration| VariableDeclaration| VariableDeclarationList| VariableStatement| WhileStatement| WhiteSpace| WhiteSpaceSequence| WithClause| WithEntries| WithStatement| YieldExpression| ZeroToThreeFrom lean/Ecma/Grammar/Core.lean
The grammars of spec.html (the lexical, syntactic, RegExp and numeric string grammars, the supplemental grammars and Annex B's) are generated as values of these types by lean/SpecTec (Grammar/Gen/*, constructor and List data only), and Grammar/Print.lean prints them back in spec.html's notation (docs/parser/GRAMMAR.md). Each constructor is one form of §5.1.6's notation (or §5.1.1's colons); its docstring says which. What the notation means, a derivation relation over these values, is Grammar.Derives.
The nonterminals and the parameters are the enumerations NT and Param of Gen/Symbols.lean, generated from the same blocks.
Grammar.Colons
Core.lean:36§5.1.1 (sec-context-free-grammars), §5.1.3 (sec-lexical-and-regexp-grammars), §5.1.4 (sec-runtime-grammars) and §5.1.5 (sec-syntactic-grammar): the grammar a production belongs to, by its colons: : the syntactic grammar, :: the lexical and RegExp grammars, ::: the numeric string grammar.
inductive Colons whereGrammar.Sign
Core.lean:44§5.1.6 (sec-grammar-notation, "Grammatical Parameters"): how a reference sets a parameter: +P (set), ~P (not set), ?P (as the referring production's own).
inductive Sign whereGrammar.Arg
Core.lean:51A parameter argument of a nonterminal reference (§5.1.6, sec-grammar-notation), Name[+In, ?Yield].
structure Arg whereGrammar.CodePointName
Core.lean:58The code points written <NAME> (§12.2, sec-white-space, table-white-space-code-points; §12.3, sec-line-terminators, table-line-terminator-code-points).
inductive CodePointName whereAuxiliary definition: Grammar.CodePointName.codePoint
Grammar.CodePointName.codePoint
Core.lean:73The code point a name stands for (§12.2 Table 34, §12.3 Table 35), or none for <USP>, the class "any code point in general category “Space_Separator”", a declared primitive of the machine.
def CodePointName.codePoint : CodePointName → Option Nat | .TAB => some 0x0009 | .VT => some 0x000B | .FF => some 0x000C | .ZWNBSP => some 0xFEFF | .USP => none | .LF => some 0x000A | .CR => some 0x000D | .LS => some 0x2028 | .PS => some 0x2029
Grammar.Terminal
Core.lean:86A terminal symbol (§5.1.6, sec-grammar-notation): a code point sequence written in a fixed-width font (` if `; in spec.html between backticks), or a code point by name.
inductive Terminal wherealt: spec.html spells it the other way (Terminal.render), which the derivation relation ignores.
| text (s : String) (alt : Bool)| cp (n : CodePointName)Grammar.Sym
Core.lean:95A grammar symbol (§5.1.1, sec-context-free-grammars; §5.1.6, sec-grammar-notation): a terminal, or a nonterminal with its parameter arguments.
inductive Sym whereGrammar.LookItem
Core.lean:102An element of a lookahead token sequence (§5.1.6, sec-grammar-notation): a terminal, or (in a lookahead sequence of the syntactic grammar) [no LineTerminator here].
inductive LookItem whereGrammar.Lookahead
Core.lean:111§5.1.6 (sec-grammar-notation, "Lookahead Restrictions"): [lookahead = seq] (written ==), [lookahead ≠ seq] (written !=), [lookahead ∈ set], [lookahead ∉ set] with a set of sequences in braces, and [lookahead ∉ N] with a nonterminal whose language is a finite set of terminals.
inductive Lookahead whereGrammar.Exclusion
Core.lean:121§5.1.6 (sec-grammar-notation, "but not"): what follows but not: one symbol, or one of a list, separated by or (orSep := true) or by spaces.
inductive Exclusion whereGrammar.Phrase
Core.lean:129§5.1.6 (sec-grammar-notation): the descriptive phrases (a right-hand side > … where listing all alternatives would be impractical), and the conditions of [> but only if …]. Their meaning is given by hand with the kernel; the printer prints their spec.html text.
inductive Phrase where> any Unicode code point (§11.1, SourceCharacter)
| anyCodePoint> any Unicode code point with the Unicode property “ID_Start” (§12.7)
| idStart> any Unicode code point with the Unicode property “ID_Continue” (§12.7)
| idContinue> any Unicode code point in the inclusive interval from U+D800 to U+DBFF (§22.2.1)
| leadSurrogate> any Unicode code point in the inclusive interval from U+DC00 to U+DFFF (§22.2.1)
| trailSurrogatebut only if the MV of |HexDigits| > 0x10FFFF (§12.9.4, NotCodePoint)
| mvAbove10FFFFbut only if the MV of |HexDigits| ≤ 0x10FFFF (§12.9.4, CodePoint)
| mvAtMost10FFFFbut only if the MV of |Hex4Digits| is in the inclusive interval from 0xD800 to 0xDBFF (§22.2.1)
| mvLeadbut only if the MV of |Hex4Digits| is in the inclusive interval from 0xDC00 to 0xDFFF (§22.2.1)
| mvTrailbut only if the MV of |Hex4Digits| is not in the inclusive interval from 0xD800 to 0xDFFF (§22.2.1)
| mvNonSurrogatebut only if the CapturingGroupNumber of |DecimalEscape| is ≤ CountLeftCapturingParensWithin(the |Pattern| containing |DecimalEscape|) (B.1.2)
| groupNumberAtMostCountGrammar.Item
Core.lean:155One element of a right-hand side (§5.1.6, sec-grammar-notation).
inductive Item whereA symbol, optional when written with the opt subscript (? in spec.html).
| sym (s : Sym) (opt : Bool)A lookahead restriction.
| lookahead (l : Lookahead)[no LineTerminator here].
| noLT[empty]: the right-hand side derives no terminals.
| emptybase but not …: an instance of base that is not one of the excluded.
| butNot (base : Sym) (ex : Exclusion)[> but only if …]: a condition on the item before it.
| onlyIf (c : Phrase)> …: a descriptive phrase, the whole right-hand side.
| phrase (p : Phrase)Grammar.Guard
Core.lean:175One condition of a guard [+P], [~P] or [+P, ~Q] before a right-hand side (§5.1.6, sec-grammar-notation): the alternative exists only when every condition holds, the parameter set (plus := true) or not.
structure Guard whereGrammar.Alt
Core.lean:182One alternative (§5.1.6, sec-grammar-notation): its guard (no conditions when it has none), its right-hand side and its #label.
structure Alt whereGrammar.Body
Core.lean:193A definition's alternatives, or one of (§5.1.6, sec-grammar-notation) with its rows of terminals, each terminal an alternative.
inductive Body whereGrammar.Rule
Core.lean:200One definition of a nonterminal (§5.1.1, sec-context-free-grammars; §5.1.6, sec-grammar-notation): Lhs[Params] : alternatives.
structure Rule whereGrammar.GrammarId
Core.lean:210The grammars (§5.1, sec-syntactic-and-lexical-grammars; Annex B, sec-additional-ecmascript-features-for-web-browsers), in GL's order (prodsOf): the numeric string, lexical, syntactic (with its supplemental grammars), RegExp grammars, Annex B's overlays, and json.emu's JSON grammar.
inductive GrammarId whereRight-hand sides
The order of right-hand sides (§5.1.6, "Optional Symbols": an alternative with k optional symbols specifies 2^k right-hand sides): grammar by grammar, then by written production (a rule's alternatives, or its one of terminals, in spec order), then over the presences of its optional symbols, absent before present, the first the most significant. A right-hand side's production id (ProdId) is its alphabetical index among all expanded right-hand sides (prodsById), exposed symbolically in Ecma.Known.
Grammar.Prod
Core.lean:231One right-hand side (§5.1.6, sec-grammar-notation): a written production of a grammar and the presence of each of its optional symbols.
structure Prod whereAuxiliary definitions (6): Grammar.Alt.opts, Grammar.masks, Grammar.prodsOf, Grammar.idsOfRuns, …
Grammar.Alt.opts
Core.lean:242The number of optional symbols of an alternative.
def Alt.opts (a : Alt) : Nat := (a.rhs.filter fun | .sym _ true => true | _ => false).lengthGrammar.masks
Core.lean:245The presence masks of k optional symbols, in id order.
def masks : Nat → List (List Bool) | 0 => [[]] | n + 1 => (masks n).map (false :: ·) ++ (masks n).map (true :: ·)
Grammar.prodsOf
Core.lean:256The right-hand sides of gs, in id order.
def prodsOf (gs : List (GrammarId × List Rule)) : List Prod := gs.flatMap fun (g, rules) => let ws := rules.flatMap fun r => r.written.zipIdx.map fun (k, i) => (r, i, k) ws.zipIdx.flatMap fun ((r, i, k), c) => (masks k).map fun m => ⟨g, r, i, c, m⟩
Grammar.idsOfRuns
Core.lean:262The numbers of runs (a, n): a, a + 1, …, a + n - 1, run by run.
def idsOfRuns (rs : List (Nat × Nat)) : List Nat := rs.flatMap fun (a, n) => List.range' a nGrammar.prodsById
Core.lean:267The right-hand sides of gs by production id: ids (as runs) gives each of prodsOf gs, in order, its number, and entry n of the next entries is the right-hand side numbered n; none at a number no right-hand side has (a retired production's).
def prodsById (gs : List (GrammarId × List Rule)) (ids : List (Nat × Nat)) (next : Nat) : Array (Option Prod) := let numbered := (prodsOf gs).zip (idsOfRuns ids) ((List.range' 0 next).map fun n => (numbered.find? (·.2 == n)).map (·.1)).toArray
Grammar.Prod.altOf
Core.lean:272A written production's alternative (none for a one of terminal).
def Prod.altOf (p : Prod) : Option Alt := match p.rule.body with | .alts as => as[p.alt]? | .oneOf _ => none
Grammar.AnnexB
Core.lean:282The Annex B sections whose grammar is an overlay of the main grammar, by clause id: B.1.1 sec-html-like-comments, B.1.2 sec-regular-expressions-patterns, B.3.3 sec-functiondeclarations-in-ifstatement-statement-clauses and B.3.5 sec-initializers-in-forin-statement-heads.
inductive AnnexB where| htmlLikeComments| regExpPatterns| functionDeclarationsInIfStatement| initializersInForInGrammar.AnnexB.Set
Core.lean:298A set of Annex B sections (the ones a host supports, Annex B, sec-additional-ecmascript-features-for-web-browsers), one membership bit per section.
structure AnnexB.Set wherehtml : Bool := falseregExp : Bool := falseifFunctions : Bool := falseforInInit : Bool := falseAuxiliary definition: Grammar.AnnexB.Set.any
Grammar.AnnexB.Set.any
Core.lean:313Whether any section is in the set.
def AnnexB.Set.any (S : AnnexB.Set) : Bool := S.html || S.regExp || S.ifFunctions || S.forInInitGrammar.OverlayMode
Core.lean:326How an overlay's rules combine with the main grammar's definitions of the same nonterminals, as its section says (Annex B, sec-additional-ecmascript-features-for-web-browsers): extend (B.1.1 "is extended as follows", B.3.3 and B.3.5 "augments") is the union of the main definition's alternatives and the overlay's, an alternative the overlay restates (equal as an Alt) counted once: B.1.1 restates whole definitions (its InputElementHashbangOrRegExp repeats the main one's six alternatives and adds HTMLCloseComment), and a restated alternative is not a second production. replace is B.1.2's (sec-regular-expressions-patterns) "is modified and extended as follows … each alternative is considered only if previous production alternatives do not match": the overlay's definition, in its order, replaces the main one.
inductive OverlayMode whereGrammar.OverlayCond
Core.lean:338When an Annex B overlay applies (Annex B, sec-additional-ecmascript-features-for-web-browsers), as its section's prose says: always (B.1.2, sec-regular-expressions-patterns), notModule (B.1.1, sec-html-like-comments: "this extension is not allowed when parsing source text using the goal symbol Module"), nonStrict (B.3.3 and B.3.5: "This production only applies when parsing non-strict code"). So the grammar a parse uses depends on the goal and on strictness, besides which Annex B sections the host supports.
inductive OverlayCond whereGrammar.BlockKind
Core.lean:347What a definition block is: of the main grammar (§5.1, sec-syntactic-and-lexical-grammars), a supplemental grammar (§5.1.5, sec-syntactic-grammar: "the interpretation of |cover| is refined using the following grammar"), or an Annex B overlay (sec-additional-ecmascript-features-for-web-browsers) with its mode and its condition.
inductive BlockKind whereGrammar.Block
Core.lean:354One grammar definition block (§5.1.6, sec-grammar-notation): its grammar, clause id, kind and rules in order.
structure Block whereGrammar.Semi
Core.lean:405§12.10.1 (sec-rules-of-automatic-semicolon-insertion): where a ; of the syntactic grammar's right-hand sides may be a virtual (inserted) one.
inductive Semi whereRules 1–3 may insert it.
| insertableInsertable by rules 1–3, as insertable (an offending token after a LineTerminator, }, or the end of input), and also by rule 1's special case: "the previous token is ) and the inserted semicolon would then be parsed as the terminating semicolon of a do-while statement (14.7.2)".
| doWhileNever: "if the semicolon would then be parsed as an empty statement".
| emptyStatementNever: "if that semicolon would become one of the two semicolons in the header of a for statement (see 14.7.4)".
| forHeaderInsertable, except where this production ends the LexicalDeclaration of for ( LexicalDeclaration Expression? ; …, where the ; is the header's first: there it is forHeader.
| forHeaderIfDeclarationFrom lean/Ecma/Grammar/Notation.lean
What reading GL needs beyond its data: the context a parse is under, the Annex B overlays and readings in effect (GL.alts), production ids of right-hand sides, parameters through a reference (applyArgs) and guards, and chain and unit productions. Definitions only; the derivation relation (Ecma.Grammar.Derives) and the parser (Parse) both read them.
Grammar.Ctx
Notation.lean:21What a parse is under (§5.1.2, sec-parsing; Annex B, sec-additional-ecmascript-features-for-web-browsers): the goal is a Module, and the Annex B overlay sections the host supports (normative optional). Strictness is regional (NonStrictOk).
structure Ctx wheremodule : BoolannexB : AnnexB.SetGrammar.GL
Notation.lean:31GL as the derivation relation reads it (§5.1, sec-syntactic-and-lexical-grammars; §5.1.6, sec-grammar-notation; §12.10, sec-automatic-semicolon-insertion): each grammar's rules in spec order, the production ids of their right-hand sides, the definition blocks (the overlays' sections, modes and conditions), and §12.10's class of each ; of the syntactic grammar (written production, position).
structure GL wheregrammars : List (GrammarId × List Rule)The production id of each right-hand side of grammars, in prodsOf's order, as runs (idsOfRuns): its alphabetical index among all expanded right-hand sides.
ids : List (Nat × Nat)The count of production ids.
next : Natblocks : List Blocksemis : List (Nat × Nat × Semi)Auxiliary definitions (6): Grammar.GL.byId, Grammar.overlayGrammar, Grammar.condHolds, Grammar.baseGrammar, …
Grammar.GL.byId
Notation.lean:43GL's right-hand sides by production id (prodsById): entry n is the right-hand side ids numbers n.
def GL.byId (gl : GL) : Array (Option Prod) := prodsById gl.grammars gl.ids gl.nextGrammar.overlayGrammar
Notation.lean:46The grammar an Annex B section overlays.
def overlayGrammar : AnnexB → GrammarId | .htmlLikeComments => .lexical | .regExpPatterns => .regExp | .functionDeclarationsInIfStatement | .initializersInForIn => .syntactic
Grammar.condHolds
Notation.lean:53An overlay's condition, as far as the context decides it: nonStrict holds here, and NonStrictOk excludes the overlay's nodes in strict mode code.
def condHolds (cx : Ctx) : OverlayCond → Bool | .always | .nonStrict => true | .notModule => !cx.module
Grammar.baseGrammar
Notation.lean:59The grammar whose definitions a grammar uses for the nonterminals it does not define: the RegExp and numeric string grammars use the lexical grammar's.
def baseGrammar : GrammarId → Option GrammarId | .regExp | .numericString => some .lexical | _ => none
Grammar.codeGrammars
Notation.lean:64The code point grammars, in the order a goal is tried. Annex B's rules enter them through GL.overlays.
def codeGrammars : List GrammarId := [.numericString, .lexical, .regExp, .json]Grammar.writtenAlts
Notation.lean:68A rule's written productions as alternatives: a one of terminal is the alternative of that terminal alone.
def writtenAlts (r : Rule) : List Alt := match r.body with | .alts as => as | .oneOf rows => rows.flatten.map fun t => ⟨[], [.sym (.t t) false], none⟩
Grammar.Src
Notation.lean:75An alternative in effect (§5.1.6, sec-grammar-notation): the grammar and rule it is written in and its index among the rule's written productions.
structure Src whereAuxiliary definitions (15): Grammar.srcsOf, Grammar.GL.rulesOf, Grammar.GL.pinned, Grammar.GL.overlays, …
Grammar.srcsOf
Notation.lean:83All written alternatives of rule r in grammar g as Src entries (§5.1.6, sec-grammar-notation).
def srcsOf (g : GrammarId) (r : Rule) : List Src := (writtenAlts r).zipIdx.map fun (a, i) => ⟨g, r, i, a⟩
Grammar.GL.rulesOf
Notation.lean:87The rules of grammar g in gl (§5.1, sec-syntactic-and-lexical-grammars).
def GL.rulesOf (gl : GL) (g : GrammarId) : List Rule := (gl.grammars.lookup g).getD []Grammar.GL.pinned
Notation.lean:90The pinned definition of n in grammar g, or in its base grammar.
def GL.pinned (gl : GL) (g : GrammarId) (n : NT) : List Src := match (gl.rulesOf g).find? (·.lhs == n) with | some r => srcsOf g r | none => match baseGrammar g with | some b => ((gl.rulesOf b).find? (·.lhs == n)).map (srcsOf b) |>.getD [] | none => []
Grammar.GL.overlays
Notation.lean:98The overlays in effect on grammar g, in spec order, with their modes.
def GL.overlays (gl : GL) (cx : Ctx) (g : GrammarId) : List (Block × OverlayMode) := if !cx.annexB.any then [] else gl.blocks.filterMap fun b => match b.kind with | .overlay s m c => if overlayGrammar s == g && cx.annexB.has s && condHolds cx c then some (b, m) else none | _ => none
Grammar.GL.alts
Notation.lean:106The alternatives of n in effect in grammar g with the overlays in effect: extend adds the alternatives it does not restate, replace replaces the definition.
def GL.alts (gl : GL) (cx : Ctx) (g : GrammarId) (n : NT) : List Src := (gl.overlays cx g).foldl (fun acc (b, m) => match b.rules.find? (·.lhs == n), m with | none, _ => acc | some r, .extend => acc ++ (srcsOf .annexB r).filter fun s => !acc.any (·.alt == s.alt) | some r, .replace => srcsOf .annexB r) (gl.pinned g n)
Grammar.GL.prodId
Notation.lean:114The production id of a right-hand side: the number GL gives it (GL.byId).
def GL.prodId (gl : GL) (s : Src) (m : List Bool) : Option Nat := let hit := fun (p : Prod) => p.grammar == s.grammar && p.rule.lhs == s.rule.lhs && p.alt == s.idx && p.mask == m gl.byId.findIdx? (·.any hit)
Grammar.GL.ctorOf
Notation.lean:119The written production index (Production constructor) of a right-hand side.
def GL.ctorOf (gl : GL) (s : Src) : Option Nat := ((prodsOf gl.grammars).find? fun p => p.grammar == s.grammar && p.rule.lhs == s.rule.lhs && p.alt == s.idx).map (·.ctor)
Grammar.GL.ordered
Notation.lean:124B.1.2 ("each alternative is considered only if previous production alternatives do not match"): grammar g's alternatives are ordered, §B.1.2's overlay being in effect on it.
def GL.ordered (gl : GL) (cx : Ctx) (g : GrammarId) : Bool := (gl.overlays cx g).any fun (b, _) => b.kind matches .overlay .regExpPatterns _ _
Grammar.GL.orderedNts
Notation.lean:128The nonterminals B.1.2's ordering sentence orders on grammar g: those its overlay restates.
def GL.orderedNts (gl : GL) (cx : Ctx) (g : GrammarId) : List NT := (gl.overlays cx g).flatMap fun (b, _) => if b.kind matches .overlay .regExpPatterns _ _ then b.rules.map (·.lhs) else []
Grammar.GL.altPos
Notation.lean:132The position in GL.alts of the alternative of n with production id id.
def GL.altPos (gl : GL) (cx : Ctx) (g : GrammarId) (n : NT) (id : Nat) : Option Nat := ((gl.alts cx g n).zipIdx.find? fun (s, _) => (masks s.alt.opts).any (gl.prodId s · == some id)).map (·.2)
Grammar.capturingRhs
Notation.lean:136The right-hand side ( GroupSpecifier? Disjunction ).
def capturingRhs : List Item → Bool | [.sym (.t (.text "(" _)) false, .sym (.nt .GroupSpecifier _) true, .sym (.nt .Disjunction _) false, .sym (.t (.text ")" _)) false] => true | _ => false
Grammar.GL.capturingIds
Notation.lean:143§22.2.1.2, B.1.2.2: the productions of a left-capturing parenthesis, Atom :: ( GroupSpecifier? Disjunction ) and B.1.2's same right-hand side of ExtendedAtom.
def GL.capturingIds (gl : GL) : List Nat := gl.byId.toList.zipIdx.filterMap fun (o, id) => o.bind fun p => if (p.rule.lhs == .Atom || p.rule.lhs == .ExtendedAtom) && (p.altOf.map (capturingRhs ·.rhs)).getD false then some id else none
Grammar.applyArgs
Notation.lean:149§5.1.6: a reference's arguments give the parameters set for its nonterminal.
def applyArgs (ps : List Param) (args : List Arg) : List Param := args.filterMap fun a => match a.sign with | .plus => some a.param | .tilde => none | .quest => if ps.contains a.param then some a.param else none
Grammar.Guard.holds
Notation.lean:156A guard condition holds under the parameters set.
def Guard.holds (ps : List Param) (g : Guard) : Bool := ps.contains g.param == g.plusGrammar.GL.sloppyIds
Notation.lean:159The ids of the productions of overlays that apply only to non-strict code.
def GL.sloppyIds (L : GL) : List Nat := L.byId.toList.zipIdx.filterMap fun (o, id) => o.bind fun p => if p.grammar == .annexB && L.blocks.any (fun b => b.kind matches .overlay _ _ .nonStrict && b.rules.contains p.rule) then some id else none