简体   繁体   中英

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.

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.

A complete answer to this question can be found on the Xtext page of the Eclipse wiki.

 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM