Question

Using the grammar

start
  = b
  / a

a
  = "4" "2"

b
  = "4"

with peg.js recognizes 4 but not 42 in which case the error

"Line 1, column 2: Expected end of input but "2" found."

is reported. Obviously the parser completes the start -> b rule consuming "4" and then has no idea what to do with the "2". But why doesn't it try again with the other rule for a, when it encounters the error?

Was it helpful?

Solution

In a PEG grammar, the choice operator is called a "prioritized choice", and alternatives are meant to be processed in order of appearance in the grammar. At runtime, a PEG parser will start processing a choice with the first alternative. When that fails, the parser backtracks to the state it was in before parsing that alternative, and then proceeds with the next one. However upon success, the alternative is assumed to be part of the correct parse and any remaining alternatives are not considered with respect to the current choice.

For your grammar, this means that the second alternative is never tried, because the first one forms a prefix of it. If you reorder the alternatives, it should work as you expect it to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top