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. The C grammar I started with is from: http://www.antlr.org/grammar/1153358328744/C.g
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
...
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_expressi开发者_如何学编程on
part in the grammar.
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:
making it easy to evaluate the expression left to right.
精彩评论