If I am understanding back-references correctly, the general idea is that with a parser like the following,
const parser = peg`
add: <a>$addend '+' >a< ${({a}) => 2 * Number(a)}
$addend @raw: [0-9]+
`
The value of an input ran through this will either be twice whatever $addend
resolves to, or a failure, as the back-reference cannot correctly match whatever the first value is.
Imagine a scenario where an AST is being constructed, where given non-terminals in the grammar generate nodes corresponding to matched text. Is is possible, with back-references, to exactly match the same AST found earlier in a production rule?
For example:
const parser2 = peg`
add: <a>multiply '+' >a< => 'ADD'
multiply: <a>$factor '*' <b>$factor => 'MULTIPLY'
$factor @raw: [0-9]+
`
The idea being that multiplications could have any arbitrary numbers multiplied together, forming a Node, which would then be exactly matched twice by the addition. So,
parser2.test('2*3 + 2*3') // pass
parser2.test('2*3 + 3*4') // fail
As far as I can tell, (as of 0.5.5) the back-reference in parser2
will fail, asserting that it is expecting an object. Is there enough context present at the point a back-reference might be used to attempt to reparse an exact match? Is this impossible to represent in PEGs, or grammars more broadly?
Thanks for your consideration.