javascriptpegpegjs

parser unable to match the consequent rule due to error evaluating a former rule


Example:

start = name / invocation;

name = [a-zA-Z]+ { return text() };

invocation = a:name "()" { return {type: 'inv', value: a } };

If input is abc() I am getting error:

Expected [a-zA-Z] or end of input but "(" found

However, if start was defined as follows no issues arise:

start = invocation / name;

For the earlier case, shouldn't the name rule not match and consequently enter the invocation rule? Else how to manage such a thing?

For working example, see playground


Solution

  • This is a property of Parser Expression Grammar. Changing the order of expressions in a choice-operator can change the result.

    From wikipedia:

    The fundamental difference between context-free grammars and parsing expression grammars is that the PEG's choice operator is ordered. If the first alternative succeeds, the second alternative is ignored. Thus ordered choice is not commutative, unlike unordered choice as in context-free grammars.