XText programmatically parses DSL script in Ecore model

I need to programmatically convert text to XText grammar to AST match with Ecore metamodel generated by XText from the same grammar.

I know that XText also generates Java classes that implement such a parser, but I do not know where they are and how to use it.

+7
source share
2 answers

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.

+7
source

Here is the code:

 @Inject ParseHelper<Domainmodel> parser def void parseDomainmodel() { // When in a vanilla Java application (ie 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 .

+4
source

All Articles