开发者

If statement to tree representation in ANTLR

开发者 https://www.devze.com 2023-02-19 22:42 出处:网络
I have the following if statement that parses correctly: ifStatement : \'IF\' expression \'THEN\' statementBlock

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'^ expre开发者_JAVA技巧ssion '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)
;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号