M010: First-Character Dispatch

An ordered choice may call several rules that cannot begin with the next input character. A conservative first-terminal guard rejects those alternatives before constructing their call and memo state.

Mechanism and Invariants

The Core IR analysis finds a required starting literal or class through safe expression wrappers and calls, and the Guards pass sets it as the guard of the alternative. Unknown, left-recursive and Operators Rule starts retain ordinary matching. A rejected alternative records the expectation its first terminal would have produced. The next character is examined, so a Document edit can invalidate the result. Depth-limit behavior also constrains skipped calls. The VMs encode guards in GUARD instructions; generated parsers emit equivalent tests. Alternatives that pass still execute in their original order.

A case-insensitive literal ("x"i, or a literal under #ignorecase) is guarded by both cases of its first ASCII letter in the VMs and in the generated Go and TypeScript parsers, and in the typed Go path through the Core first set (a lower-case letter with a fold flag). Record 119 has the measurement.

Scope and State

Applied by default to eligible choices in closure, both VMs, generated Go Node/recognition, typed Go and TypeScript. It is not a reordering of PEG alternatives or a general lookahead prediction.

Reference Control

For generated Go and TypeScript parsers, -no-opt guards generates the same grammar without first-character guards, and -no-opt guarded-classes keeps the guards but leaves the leading class of a guarded alternative to test the character again. Both are same-generator references. The closure backend and the VMs have no guard-disable control, and old bytecode without GUARD is compatibility input, not a current-source reference compiler.

Evidence and Implementation

A leading class of a guarded alternative consumes the character its guard read in ordinary generated Go parsers (record 112). The flags are measured in record 136: with guards off, parse time is 1.091 times that of the default over the ten language grammars and parser.go is 0.917 times its size.

Historical records 049–051 report JSON parsing improvements of 13% in generated Node, 7% in closure, and 13%/15% in the VMs on their recorded runs. Record 050 also measures incremental reparse benefits. The revisions and operations differ; the percentages cannot be combined or generalized to unknown starts or current TypeScript workloads.

Evidence records: 049, 050, 051, 112, 136.

Source owners: Guards pass, the guarded-classes Flow pass, closure.Builder.Choice and Guard, the GUARD emission of the bytecode compiler, generated choice guards, TypeScript choice guards.

The comparison policy distinguishes same-source controls, historical changes and full checkpoints.

Related mechanisms: M020, M080.

Optimization Catalog