[antlr-interest] Tree grammars & optional AST nodes
Nicolas Rouquette
nicolas.rouquette at jpl.nasa.gov
Thu Oct 19 17:09:17 PDT 2006
Thanks for the answer!
Terence Parr <parrt at ...> writes:
> Hi :)
>
> You mean a parser grammar that builds trees, right?
yes
> expression
> options {backtrack=true;}
> : e1=conditionalExpression op=assignmentOperator e2=expression
> -> ^($op $e1 $e2)
> | conditionalExpression
> ;
>
> OR, do this:
>
> expression
> : conditionalExpression (assignmentOperator^^ expression)?
> ;
>
> :)
>
> Hard to beat tree operators for expression stuff.
An ANTLR afficionado colleague suggested
adding a simple semantic predicate
to guide the tree construction:
@init { boolean flag=false; }
: e1=conditionalExpression (op=assignmentOperator e2=expression {flag=true;})?
-> {flag} ? ^($op $e1 $e2)
-> $e1
;
I tried this w/ the ANTLRWorks debugger on a grammar
with several nested expression-like rules. Works very nicely!
I've used the same options as the java grammar
(although my language isn't java at all).
Adding the semantic predicate obfuscates a bit the grammar
but the price is really worth the result IMHO.
-- Nicolas.
> Ter
More information about the antlr-interest
mailing list