Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

caret prefix instead of postfix in antlr

Tags:

antlr

antlr3

I know what the caret postfix means in antlr(ie. make root) but what about when the caret is the prefix as in the following grammar I have been reading(this grammar is brand new and done by a new team learning antlr)....

selectClause
    : SELECT resultList -> ^(SELECT_CLAUSE resultList) 
    ;


fromClause
    : FROM tableList -> ^(FROM_CLAUSE tableList) 
    ;

Also, I know what => means but what about the -> ? What does -> imply?

thanks, Dean

like image 250
Dean Hiller Avatar asked Jul 06 '12 16:07

Dean Hiller


1 Answers

The ^ is used as an inline tree operator, indicating a certain token should become the root of the tree.

For example, the rule:

p : A B^ C;

creates the following AST:

  B
 / \
A   C

There's another way to create an AST which is using a rewrite rule. A rewrite rule is placed after (or at the right of) an alternative of a parser rule. You start a rewrite rule with an "arrow", ->, followed by the rules/tokens you want to be in the AST.

Take the previous rule:

p : A B C;

and you want to reverse the tokens, but keep the ASST "flat" (no root node). THis can be done using the following rewrite rule:

p : A B C -> C B A;

And if you want to create an AST similar to p : A B^ C;, you start your rewrite rule with ^( ... ) where the first token/rule inside the parenthesis will become the root node. So the rule:

p : A B C -> ^(B A C);

produces the same AST as p : A B^ C;.


Related:

  • Tree construction
  • How to output the AST built using ANTLR?
like image 145
Bart Kiers Avatar answered Sep 28 '22 10:09

Bart Kiers