0
votes

I'd like to use ANTLR to produce an AST which I can walk manually (using hand-written visitor code instead of ANTLR's tree grammars.) Say I have the following grammar

expr    : term ( ( PLUS | MINUS )^  term )*;

term    : factor ( ( MULT | DIV )^ factor )* ;

factor  : NUMBER

I'd like both expr and term to produce AST nodes with type BinaryExpression if and only if there is an operator (plus, minus, times or divide) being matched, and to produce a plain NUMBER otherwise. I know I could append an action like $type = "BINARYEXPRESSION", but that seems like a hack. Is there a better approach? Is using ANTLR to generate a parser for a manually-traversed tree a bad idea?

Edit:

I've tried

expr    : term ( ( PLUS<BinaryExpression> | MINUS<BinaryExpression> )^  term )*;

But a) this doesn't seem to have any effect at all (the nodes produced are still instances of CommonTree and CommonToken), and b) to save on repetition, I want this typing to be applied to the entire node constructed by a given rule, instead of applying the type to the child nodes of the current rule. I.e. I shouldn't have to put <Identifier> in every rule which has Identifiers as children.

1

1 Answers

0
votes

The typical syntax is Terminal<ASTNodeType> (click for reference), but since it appears you're using the Python target you'll have to verify this.