Dear fellow ANTLR 4 fans,
The language I'm trying to write a grammar for has a similar kind of ambiguity to the one about C++ that Terrence mentions in his book:
A macro definition is syntactically identical to an assignment to a subscripted variable. To wit, here's a grammar excerpt:
topNode: defLines execLines ;
defLines: defLine* ;
defLine: macroDef | otherDef ;
macroDef: id formals '=' expr ;
execLines: execLine* ;
execLine: assignment | otherExec ;
assignment: scalarAssignment | arrayAssignment ;
arrayAssignment: id formals '=' expr ;
formals: '(' id ( ',' id )* ')' ;
...so occasionally an assignment will wrongly end up in the macro definitions, which messes up my parse tree structure.
There is a simple test that eliminates most of the questionable cases: A legitimate macro will use all of its formal arguments (the 'id's to the left of the '=') in the expression to the right.
'expr' can be an arbitrarily complex tree, but the variables in it are of course all of type 'id'.
Ideally, I would like to access my formal args and my expr before they get cast into the rule 'macroDef' or 'arrayAssignment' and veto the macro def unless all formal args appear in the expr.
I've done the Java coding (it's simple enough) but how can I incorporate the test into my grammar? It looks to me like semantic predicates can only be applied _before_ you know what you're looking at.