使用XText将DSL脚本编程方式解析为Ecore模型

8

我需要以编程方式将符合XText语法的文本转换为符合由相同语法生成的Ecore元模型的AST。

我知道XText还会生成实现这种解析器的Java类,但我不知道它们在哪里以及如何使用它们。

2个回答

7
这个问题的完整答案可以在Eclipse维基的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);

将文件扩展名 (mydsl) 更改为您自己语言的扩展名。


4
这里是代码:

@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)
}

另请参阅http://www.eclipse.org/Xtext/documentation.html#TutorialUnitTests


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接