簡體   English   中英

XText以編程方式將DSL腳本解析為Ecore模型

[英]XText programmatically parse a DSL script into an Ecore model

我需要以編程方式將符合XText語法的文本轉換為符合XText從同一語法生成的Ecore元模型的AST。

我知道XText也會生成實現這種解析器的Java類,但我不知道它們在哪里以及如何使用它。

可以在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);

將文件擴展名( mydsl )更改為您自己的語言擴展名。

這是代碼:

@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM