[英]If statement to tree representation in ANTLR
I have the following if statement that parses correctly: 我有以下正确解析的if语句:
ifStatement
: 'IF' expression 'THEN' statementBlock
(options {greedy=true;}
: 'ELSE' statementBlock)?
;
Now, I want to parse this into an AST. 现在,我想将其解析为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. 我的结果是一个有3个孩子的AST:1是有条件的,2和3是语句块。 The else part is optional: if there is no else, node 3 is missing.
else部分是可选的:如果没有其他部分,则节点3丢失。
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
请注意,在“令牌”部分中声明了“ IF”,“ THEN”和“ ELSE”
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 [edit]或者您可以更明确一点,这也应该有效
ifStatement
: IF expression THEN ifStat=statementBlock ELSE elseStat=statementBlock -> ^(IF expression $ifStat $elseStat)
| IF expression THEN ifStat=statementBlock -> ^(IF expression $ifStat)
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.