caret prefix instead of postfix in antlr
Asked Answered
L

1

6

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

Luedtke answered 6/7, 2012 at 16:2 Comment(0)
W
7

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:

Warsle answered 6/7, 2012 at 18:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.