Sanjiv
Sanjiv

Reputation: 1815

Not able to understand ANTLR parser rule

I am new to ANTLR , and walking through existing grammar(got at Internet). See the given rule , i am not able to understand it for what is it all about?

Specially $model_expr inside Tree construct and initial (unary_expr -> unary_expr). Please help me understanding the same.

model_expr
:    (unary_expr -> unary_expr)
    (LEFT_BRACKET model_expr_element RIGHT_BRACKET
        -> ^(MODEL_EXPR[$LEFT_BRACKET] $model_expr model_expr_element))?
;

Thanks

Upvotes: 0

Views: 64

Answers (1)

Sanjiv
Sanjiv

Reputation: 1815

See the detailed explanation of above syntax with example (copied from book)

Referencing Previous Rule ASTs in Rewrite Rules

Sometimes you can’t build the proper AST in a purely declarative manner. In other words, executing a single rewrite after the parser has matched everything in a rule is insufficient. Sometimes you need to iteratively build up the AST . To iteratively build an AST, you need to be able to reference the previous value of the current rule’s AST. You can reference the previous value by using $r within a rewrite rule where r is the enclosing rule. For example, the following rule matches either a single integer or a series of integers addedtogether:

    expr : (INT -> INT) ( '+' i=INT -> ^( '+' $expr $i) ) * ;

The (INT->INT) subrule looks odd but makes sense. It says to match INT and then make its AST node the result of expr . This sets a result AST in case the (...)* subrule that follows matches nothing. To add another integer to an existing AST, you need to make a new ’+’ root node that has the previous expression as the left child and the new integer as the right child. That grammar with embedded rewrite rules recognizes the same input and generates the same tree as the following version that uses the construction operators:

    expr : INT ('+'^ INT)*;

Upvotes: 1

Related Questions