xtext: expression/factor/term grammar

怎甘沉沦 提交于 2019-12-23 02:01:29

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9444860/xtext-expression-factor-term-grammar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!