XText programmatically parse a DSL script into an Ecore model
Asked Answered
A

2

8

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.

Abracadabra answered 8/8, 2012 at 15:28 Comment(0)
A
7

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.

Abracadabra answered 15/8, 2012 at 9:13 Comment(0)
N
4

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.

Nightclub answered 9/8, 2012 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.