开发者

Parsing expressions with subexpressions in ANTLR

I am trying to parse recursive expressions in ANTLR such as:

(a + (b + C))

or

((a + b))

I read this supposed solution: ANTLR Grammar for expressions

However when I try to create a rule such as:

ParenthesisExpression: '(' (ParenthesisExpression | Expression) ')';

ANTLR complains that "Rule ParenthesisExpre开发者_如何学运维ssion is left-recursive".

How can I parse expressions that can have within themselves, subexpressions of the same form?


You could do something like this:

parse
  :  addExp EOF
  ;

addExp
  :  multExp (('+' | '-') multExp)*
  ;

multExp
  :  atom (('*' | '/') atom)*
  ;

atom
  :  ID
  |  '(' addExp ')'
  ;

ID    : 'a'..'z' | 'A'..'Z';

The closer you come to the atom rule, the higher the precedence: so + and - have the lowest precedence, followed by * and /, and lastly, ID and ( ... ) have the highest precedence.


It parses the input:

((a / b)) - x

as follows:

Parsing expressions with subexpressions in ANTLR


and the input:

(a * (b + C))

is parsed like:

Parsing expressions with subexpressions in ANTLR

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜