Question

I am creating my first AST. I want to remove the '=' from it.

I'm having something like:

              BLOCK
                |
          |-----------|
     STATEMENTS     RETURN
          |
     ASSIGNMENT
          |
          |
    |-----|-----|
 field    =    value


An extract from my Grammar file:

parse
  :  block EOF -> block
  ;

block
  :  (statement)* (Return Identifier ';')? 
     -> ^(BLOCK ^(STATEMENTS statement*) ^(RETURN Identifier?))
  ;

statement
  :  assignment ';'   -> assignment
  ;

assignment
   :  expression 
   -> ^(ASSIGNMENT expression)
   ;

expression
    :   NAME '=' Identifier
    ;

So, how can I remove the '=' node that is print in the tree?

Was it helpful?

Solution

By either using the inline operator ! that discards nodes from the tree:

expression
    :   NAME '='! Identifier
    ;

or by using a rewrite operator:

expression
    :   NAME '=' Identifier -> NAME Identifier
    ;

Related Q&A that explains these operators: How to output the AST built using ANTLR?

Note that there is no ASSIGNMENT token in your grammar. If you want to inject such a token, put it in your tokens{ ... } block and insert it in a rewrite rule:

grammar T;

options {
  // ...
}

tokens {
  ASSIGNMENT;
}

statement
    :  assignment ';' -> assignment
    ;

expression
    :   NAME '=' Identifier -> ^(ASSIGNMENT NAME Identifier)
    ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top