Tuesday, November 24, 2009

Xtext - Using existing Ecore models

Maybe it's because it was not possible in the old oAW Xtext or because the wizard suggests a grammar which makes use of the "generated Ecore model"-feature. But somehow some people tend to think that you cannot use existing Ecore models with Xtext. YOU CAN!

The feature is described in the documentation, but maybe it got too few words (Which is not because we don't use it and don't want you to use it, but because it's so simple).

In the following I want to show you how to do this. You'll see that it is relatively straight forward.
Let's assume you have an existing Ecore model, describing a library of books (sounds familiar?;-)):

In order to create a textual syntax with Xtext you only need to create an Xtext project and change the proposed grammar to something like this :

So if you want to reuse an existing ecore model, it is just a matter of switching from a "generated Ecore"-statement to an "import"-statement. Note that as soon as you do this, the grammar is statically analyzed and you'll get all kinds of compiler errors and warnings for missing attributes and classes in the imported Ecore models (you can import multiple ecore models, of course).

Next, you run Xtext's generator and you'll get an EMF Resource writing and reading instances of your Ecore model to the textual syntax defined in aboves Xtext grammar.
In addition you'll get an editor for your new language :

You can, of course, still use any EMF-based editor, since it's just an EMF model:

Note, that you cannot only import multiple Ecore models but can even mix generated and imported Ecore models in the same grammar.

To sum it up: The feature we have in Xtext to derive an Ecore model from the grammar description, is a very convenient option to get you started. If you have one or more existing Ecore models, you won't want and need to use it. But if you start developing a new language this feature speeds up your turn-arounds dramatically.