[英]How to transform postfix_expression in ANTLR C grammar to AST?
I'm learning ANTLR by modifying the C grammar and trying something interests myself. 我正在通过修改C语法并尝试自己感兴趣的事情来学习ANTLR。 The C grammar I started with is from: http://www.antlr.org/grammar/1153358328744/Cg
我开始使用的C语法来自: http : //www.antlr.org/grammar/1153358328744/Cg
Now I want to transform postfix_expression
to its corresponding AST but haven't known anything related to the transformation of the form xx (aa|bb|cc)* yy
现在,我想将
postfix_expression
转换为其相应的AST,但不知道与xx (aa|bb|cc)* yy
格式的转换有关的任何信息
...
unary_expression
: postfix_expression
| unary_operator^ unary_expression
;
postfix_expression
: primary_expression
( '[' expression ']'
| '(' ')'
| '(' argument_expression_list ')'
| '.' ID
)*
;
unary_operator
: '+'
| '-'
| '~'
| '!'
;
...
Can you help me with this problem? 您能帮我解决这个问题吗? You may just add some
^
and/or !
您可以只添加一些
^
和/或!
notations to the postfix_expression
part in the grammar. 语法中的
postfix_expression
部分的符号。
Id'd go for something like this: 我会去做这样的事情:
grammar T;
options {
output=AST;
}
tokens {
ROOT;
MEMBER;
INDEX;
CALL;
}
parse
: unary_expression EOF -> ^(ROOT unary_expression)
;
unary_expression
: postfix_expression
| unary_operator unary_expression -> ^(unary_operator unary_expression)
;
postfix_expression
: primary_expression tail* -> ^(primary_expression tail*)
;
tail
: '[' expression ']' -> ^(INDEX expression)
| '(' argument_expression_list? ')' -> ^(CALL argument_expression_list?)
| '.' ID -> ^(MEMBER ID)
;
primary_expression
: ID
| '(' expression ')' -> expression
;
argument_expression_list
: expression (',' expression)* -> expression+
;
unary_operator
: '+'
| '-'
| '~'
| '!'
;
expression
: NUMBER
| ID
;
NUMBER : '0'..'9'+;
ID : ('a'..'z' | 'A'..'Z')+;
which will parse the input: 它将解析输入:
a.b.c(foo,42)[123]
into the following AST: 进入以下AST:
making it easy to evaluate the expression left to right. 轻松评估从左到右的表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.