[英]XText programmatically parse a DSL script into an Ecore model
I need to programmatically turn a text conform to an XText grammar into an AST conform to an Ecore meta-model generated by XText from the same grammar. 我需要以编程方式将符合XText语法的文本转换为符合XText从同一语法生成的Ecore元模型的AST。
I know XText also generate the Java classes implementing such parser but I don't know either where they are and how to use it. 我知道XText也会生成实现这种解析器的Java类,但我不知道它们在哪里以及如何使用它。
A complete answer to this question can be found on the Xtext page of the Eclipse wiki. 可以在Eclipse wiki的Xtext页面上找到这个问题的完整答案。
new org.eclipse.emf.mwe.utils.StandaloneSetup().setPlatformUri("../");
Injector injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration();
XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);
resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);
Resource resource = resourceSet.createResource(URI.createURI("dummy:/example.mydsl"));
InputStream in = new ByteArrayInputStream("type foo type bar".getBytes());
resource.load(in, resourceSet.getLoadOptions());
Model model = (Model) resource.getContents().get(0);
Change the file extension ( mydsl
) to your own language extension. 将文件扩展名( mydsl
)更改为您自己的语言扩展名。
Here's the code: 这是代码:
@Inject
ParseHelper<Domainmodel> parser
def void parseDomainmodel() {
// When in a vanilla Java application (i.e. not within Eclipse),
// you need to run a global setup:
val injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration
injector.injectMembers(this) // sets the field 'parser'
// this is how you can use it:
val model = parser.parse(
"entity MyEntity {
parent: MyEntity
}")
val entity = model.elements.head as Entity
assertSame(entity, entity.features.head.type)
}
See also http://www.eclipse.org/Xtext/documentation.html#TutorialUnitTests . 另见http://www.eclipse.org/Xtext/documentation.html#TutorialUnitTests 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.