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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With