英文:
Extracting parts of a rule for reusability
问题
我正在处理一个被翻译成EMF模型的语法。实际模型包括许多属性的类型,这使得语法难以阅读。此外,一些规则包含相同的部分,我希望能提取出来以便重复使用。我正在寻找一个不需要对EMF模型进行更改的解决方案。
考虑这个非常简化的示例:
Function1 returns Function:
'function' name=ID
'{' (statements=Statement)* '}';
Function2 returns Function:
'function2' name=ID
'{' (statements=Statement)* '}';
我想要提取重复的部分并将其移动到自己的规则中,如下所示:
Function1 returns Function:
'function' name=ID;
Body;
Function2 returns Function:
'function2' name=ID;
Body;
Body returns Function:
'{' (statements=Statement)* '}';
这里的想法是,将Function1和Body合并为一个单一的实例。不幸的是,这并不起作用,因为只允许一个未分配的规则。
我知道我可以将主体移动到自己的规则并使用赋值,例如:
Function1:
'function' name=ID;
body=Body;
但据我了解,这将要求我更改EMF模型并添加一个"Body"类型和一个"body"特性到函数中。是否有避免更改模型的其他方法?
英文:
I'm working on a grammar that is translated to an EMF model. The actual model consists of types with many attributes which make the grammar hard to read. Also some rules contain identical parts which I would like to extract for reusability. I'm looking for a solution that doesn't require changes in the EMF model though.
Consider this very simplified example:
Function1 returns Function:
'function' name=ID
'{' (statements=Statement)* '}';
Function2 returns Function:
'function2' name=ID
'{' (statements=Statement)* '}';
I would like to extract the repeating part and move it to its own rule like this:
Function1 returns Function:
'function' name=ID;
Body;
Function2 returns Function:
'function2' name=ID;
Body;
Body returns Function:
'{' (statements=Statement)* '}';
The idea here is, that Function1 and Body are merged into a single instance. Unfortunately that doesn't work though, because only a single unassigned rule is allowed.
I know I could move the body to it's own rule and use assignments, e.g.
Function1:
'function' name=ID;
body=Body;
But as far as I understand that would require me to change the EMF model an add a "Body" type and a "body" feature to the function. Is there any other way which avoids changing the model?
答案1
得分: 2
如果您将"Body"声明为解析规则片段,您将获得完全符合您要求的行为。
如果您将"Body"声明为解析规则片段,您将获得完全符合您要求的行为。
它仍然是一个未记录的功能,但自2015年以来可用并且非常稳定。
英文:
If you declare Body as a parser rule fragment, you'll get exactly your desired behavior.
fragment Body returns Function: ...;
It's still an undocumented feature, but available since 2015 and it is stable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论