xtext: expression/factor/term grammar

2019-05-29 07:57发布

This has got to be one of those well-known examples that's somewhere on the internet, but I can't seem to find it.

I'm trying to learn XText and I figured a calculator expression parser would be a good start. But I'm getting syntax errors in my grammar:

Expression:
    Term (('+'|'-') Term)*;

Term:
    Factor (('*'|'/') Factor)*;

Factor:
    number=Number | variable=ID | ('(' expression=Expression ')');

I get this error in the Expression and Term lines:

Multiple markers at this line
 - Cannot change type twice within a rule
 - An unassigned rule call is not allowed, when the 'current'
   was already created.

What gives? How can I fix this? And when do I have instanceName=Rule vs. Rule entries in a grammar?

标签: grammar xtext
1条回答
可以哭但决不认输i
2楼-- · 2019-05-29 08:27

I downloaded xtext integrated with eclipse and it comes with a calculator example which does approximately what you wish called arithmetics. From what I can gather you will need to assign an associativity to your tokens. This grammar runs fine for me:

Expression:
    Term (({Plus.left=current}'+'|{Minus.left=current}'-') right=Term)*;

Term:
    Factor (({Multiply.left=current} '*'| {Division.left=current}'/') right=Factor)*;

Factor:
    number=NUMBER | variable=ID | ('(' expression=Expression ')');

The example grammar they have for arithmetics can be viewed here. It includes a bit more than your, like function calls, but the basics are the same.

查看更多
登录 后发表回答