简体   繁体   中英

If statement to tree representation in ANTLR

I have the following if statement that parses correctly:

ifStatement
    : 'IF' expression 'THEN' statementBlock 
        (options {greedy=true;} 
            : 'ELSE' statementBlock)?

    ;

Now, I want to parse this into an AST. This is how I did it:

ifStatement
    : 'IF'^ expression 'THEN'! statementBlock 
        (options {greedy=true;} 
            : 'ELSE'! statementBlock)?

    ;

Added ! and ^ , as -> building instruction didn't seem to work.

My result is an AST with 3 children: 1 is the conditional, 2 and 3 are the statement blocks. The else part is optional: if there is no else, node 3 is missing.

The problem is that the statement blocks are always empty. How to fix that?

The following is basically how I implemented it. Note that 'IF', 'THEN', and 'ELSE' are declared in the 'tokens' section

ifStatement
:   IF expression THEN ifStat=statementBlock 
    (   ELSE elseStat=statementBlock  ->  ^(IF expression $ifStat $elseStat)
    |                                 ->  ^(IF expression $ifStat)
    )
;

[edit] Or you could be more explicit which should also work

ifStatement
:   IF expression THEN ifStat=statementBlock ELSE elseStat=statementBlock  ->  ^(IF expression $ifStat $elseStat)
|   IF expression THEN ifStat=statementBlock                               ->  ^(IF expression $ifStat)
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM