Xtext User Guide
Xtext User Guide
Xtext 1.0 1
1. Overview .................................................................................................................... 1
1.1. What is Xtext? ................................................................................................... 1
1.2. How Does It Work? ............................................................................................ 1
1.3. Xtext is Highly Configurable ................................................................................ 1
1.4. Who Uses Xtext? ................................................................................................ 1
1.5. Who is Behind Xtext? ......................................................................................... 1
1.6. What is a Domain-Specific Language ..................................................................... 2
2. Getting Started ............................................................................................................ 3
2.1. Creating a DSL ................................................................................................. 3
2.1.1. Create an Xtext Project ............................................................................. 3
2.1.2. Project Layout ......................................................................................... 4
2.1.3. Build Your Own Grammar ......................................................................... 5
2.1.4. Generate Language Artifacts ...................................................................... 8
2.1.5. Run the Generated IDE Plug-in ................................................................... 8
2.1.6. Adding a Namespace Concept .................................................................... 9
2.2. Processing Xtext Models .................................................................................... 11
2.2.1. Loading a Resource ............................................................................... 12
2.2.2. Working with EMF Models ...................................................................... 12
2.2.3. Working with the Parse Tree (aka Node Model) ........................................... 13
2.2.4. Working with the Grammar ...................................................................... 13
2.2.5. Working with Live Models ....................................................................... 13
2.2.6. Summary ............................................................................................... 14
2.3. Writing a Code Generator ................................................................................... 15
2.3.1. Xpand and MWE2 .................................................................................. 15
2.3.2. The Empty Generator Project .................................................................... 15
2.3.3. Replacing the Example Model File (1) ........................................................ 15
2.3.4. The Modeling Workflow Engine File (2) .................................................... 16
2.3.5. Using Xpand (3) and Xtend (4) for Code Generation ..................................... 18
3. The Grammar Language ............................................................................................ 21
3.1. A First Example ............................................................................................... 21
3.2. The Syntax ...................................................................................................... 22
3.2.1. Language Declaration .............................................................................. 22
3.2.2. EPackage Declarations ............................................................................. 22
3.2.3. Rules .................................................................................................... 24
3.2.4. Parser Rules ........................................................................................... 26
3.2.5. Hidden Terminal Symbols ........................................................................ 30
3.2.6. Data Type Rules ..................................................................................... 31
3.2.7. Enum Rules ........................................................................................... 31
3.3. Ecore Model Inference ....................................................................................... 32
3.3.1. Type and Package Generation ................................................................... 32
3.3.2. Feature and Type Hierarchy Generation ...................................................... 32
3.3.3. Enum Literal Generation .......................................................................... 33
3.3.4. Feature Normalization ............................................................................. 33
3.3.5. Customized Post Processing ...................................................................... 33
3.3.6. Error Conditions ..................................................................................... 34
3.4. Grammar Mixins ............................................................................................... 34
3.5. Common Terminals ........................................................................................... 34
4. Configuration ............................................................................................................ 36
4.1. The Generator .................................................................................................. 36
4.1.1. A Short Introduction to MWE2 ................................................................. 36
4.1.2. General Architecture .............................................................................. 37
4.1.3. Standard Generator Fragments .................................................................. 40
4.2. Dependency Injection in Xtext with Google Guice .................................................. 40
4.2.1. The Module API .................................................................................... 41
4.2.2. Obtaining an Injector ............................................................................. 42
5. Runtime Concepts ...................................................................................................... 43
5.1. Runtime Setup (ISetup) ...................................................................................... 43
5.2. Setup within Eclipse-Equinox (OSGi) ................................................................... 43
Xtext 1.0 ii
Xtext User Guide
Xtext 1.0 iv
Chapter 1. Overview
1.1. What is Xtext?
No matter if you want to create a small textual domain-specific language (DSL) or you want to implement
a full-blown general purpose programming language. With Xtext you can create your very own languages
in a snap. Also if you already have an existing language but it lacks decent tool support, you can use Xtext
to create a sophisticated Eclipse-based development environment providing editing experience known
from modern Java IDEs in a surprisingly short amount of time. We call Xtext a language development
framework.
Xtext 1.0 1
Overview
Xtext 1.0 2
Chapter 2. Getting Started
In this mini-tutorial we will implement a small domain-specific language and a corresponding Eclipse
IDE integration with Xtext. Later, we will create a code generator that is capable of reading the models
you create with the DSL editor and process them, i.e. generate some Java code from it.
entity Session {
title: String
isTutorial : Bool
}
entity Conference {
name : String
attendees : Person*
speakers : Speaker*
}
entity Person {
name : String
}
Keep “Create generator project” checked, as we will also create a code generator in a second step. If you
want to materialize the full blown Domainmodel example that ships with Xtext, it is strongly recommend
to use another language name and file extension for this tutorial.
Click on Finish to create the projects.
Xtext 1.0 3
Getting Started
It is good to be clear and unambiguous whether the code is generated or is to be manipulated by the
developer. Thus, the generated code should be held separately from the manually written code. We follow
this pattern by having a folder src/ and a folder src-gen/ in each project. Keep in mind not to make changes
in the src-gen/ folder. They will be overwritten by the generator without any further warning.
A third project, org.eclipse.xtext.example.domainmodel.generator will later contain an Xpand code
generator that leverages the model created with the DSL editor. This is fully optional and it is also optional
to use Xpand. In fact you can use any programming language running on the JVM to implement a code
Xtext 1.0 4
Getting Started
generator for your Xtext models. Also it is of course perfectly ok, to have no code generator at all but use
the models dynamically at runtime. We call these kind of model processors interpreters.
In Xtext each grammar has a unique name, which like public Java classes needs to reflect the location of
the file within the Java classpath. In our case the grammar file is located in /org/eclipse/xtext/example/
Domainmodel.xtext therefore the name of the grammar is org.eclipse.xtext.example.Domainmodel. The
second part of that statement ( with org.eclipse.xtext.common.Terminals) states, that this grammar reuses
and overrides rules from the specified grammar. The org.eclipse.xtext.common.Terminals is a library
grammar shipped with Xtext and predefines the most common terminal rules, such as ID, STRING and
INT. It also introduces single-line and multi-line comments as well as rules for whitespace, which may
occur everywhere by default. You can open that grammar in the editor to have a look at these rules. It
turns out that these set of rules are often the same and often used, so that most Xtext languages extend
this grammar. However, it is just a library, so you won’t use it if it doesn’t fit your needs. Also you can
use the grammar inheritance mechanism for your own grammar libraries, of course.
The next statement declares an EMF Ecore package, aka EPackage, to be derived from the grammar:
generate domainmodel "http://www.eclipse.org/xtext/example/Domainmodel"
Ecore EPackages are effectively a set of classes (in EMF they are called EClass) which are used to
represent the in-memory-model of a text file. Instead of model we also sometimes refer to it as semantic
model or _Abstract Syntax Tree (AST)_. Note, that in the case of Xtext it’s actually a graph rather than
a tree, since it also contains crosslinks. But as the term AST is so commonly used and well known we
are ignoring this minor detail.
In order to tell the parser which EClasses to use when creating the AST, we need to make them available
by either importing existing Ecore packages or like in our example let Xtext derive a package from the
grammar. An EPackage has a mandatory name and namespace URI (short: nsURI), so we have to declare
these two values in that statement.
That’s all for the prelude, now we have to define the parser rules which effectively define a bi-directional
mapping from text to a constructed AST. It is bi-directional because Xtext not only derives a parser from
the grammar but also a serializer. Anyway, we will mostly talk about parsing in this chapter.
Ignore and delete the parser rules generated by the wizard and start by declaring an entry rule for our
language. The entry rule for the parser will be called DomainModel. Xtext is fine with any name, it just
picks the first rule in a grammar and interprets it as the entry rule.
As a DomainModel consists of one or more Entity entries, this rule delegates to another rule named
Entity, which will be defined later on. As we can have an arbitrary number of entities within a model, the
cardinality is ' *'. There are four different cardinalities available.
Each rule ends with a semicolon. So our first rule reads for now as
Xtext 1.0 5
Getting Started
DomainModel :
Entity*;
An Xtext grammar does not only describe rules for the parser but also the structure of the resulting AST.
Usually, each parser rule will create a new object in that tree. The type of that element can be specified
after the rule name using the keyword returns. If the type’s name is the same as the rule’s name, it can
be omitted as in our case. Which effectively means that
DomainModel returns DomainModel: ...
is the same as
DomainModel : ...
In order to connect the different objects together, we have to assign the elements returned by called rules
to some feature of the current rule’s object. This is done by using so called assignments.
DomainModel :
(elements+=Entity)*;
The assignment with the ' +=' operator adds every object returned by the Entity rule to the elements
referenced of the AST type Model. If you use ' +=' as opposed to ' =' the feature needs to be a list – the
upperBound has to be -1. In addition to the two mentioned assignment operators there is a third one ' ?='
which is called boolean assignment and which sets a certain feature to true, if the part on the right hand
side was parsed successfully. Here’s the list of available assignment operators:
The next rule on our list is the rule Entity. Looking at our target syntax, each entity begins with the
keyword 'entity' followed by the entity’s name and an opening curly brace (we will handle the extends
clause in a second step). Then, an entity defines a number of features and ends with a closing curly brace.
The rule looks like this:
Entity :
'entity' name=ID '{'
(features+=Feature)*
'}';
Keywords are simply declared as string literals within the rules. The name uses the ID rule from the
mixed-in grammar org.eclipse.xtext.common.Terminals. The ID rule is a so called terminal rule which
always returns simple data types, such as String, Date, or Integer. Actually any Java class can be a simple
EMF EDataType. The ID rule recognizes alphanumeric words similar to identifiers in Java and returns
the value as a String. You can navigate to its declaration using F3. As mentioned before the assignment
operator ' =' denotes a single valued feature.
We want to allow inheritance for entities and therefore now add an optional ' extends' part.
Entity :
'entity' name=ID ('extends' superType=[Entity])? '{'
(features+=Feature)*
'}';
The question mark marks an element or as in this case an entire group of elements as optional. The
other new thing is the right hand side of of the assignment superType=[Entity]. This is a cross-reference
literal and states, that a cross-reference to an elsewhere declared Entity should be established. So in this
case Entity does not point to the corresponding rule but to the EClass. As both are named equally this
might cause a little confusion at first. The full syntax for a cross-reference is [TypeName|RuleCall] where
RuleCall defaults to ID. This means that ? would work equally well. The parser only parses the name of
Xtext 1.0 6
Getting Started
the cross-referenced element using the ID rule and stores it internally. Later on the linker establishes the
cross-reference using the name, the defined cross-reference’s type ( Entity in this case) and the defined
scoping rules. Scoping is not covered in this tutorial since the domain model DSL works with the default
scoping semantics. By default a namespace-based scoping is applied, which means that all entities living
in the same namespace are possible candidates for a cross-reference. We talk a bit about this later on in
this chapter when we introduce namespaces.
In our introductory example model we had not only defined entities but also two data types. So the
DomainModel rule needs to be able to parse data types as well. As both entities and data types will be
referenced from the yet to be defined Feature rule, we should introduce a common super type for them.
DomainModel :
(elements+=Type)*;
Type:
DataType | Entity;
DataType:
'datatype' name=ID;
A DomainModel now consists of types where a Type can either be a DataType or an Entity. Our rule Type
will just delegate to either of them, using the ' |' alternatives operator. Now that we have a common super
type for Entity and DataType we are able to refer to both types of elements with a single cross-reference.
Next up we need to define the syntax of Feature, which shouldn’t be surprising to you, as we do not
use any new concepts here.
Feature:
name=ID ':' type=TypeRef;
In many target platforms there is a difference between the notion of a simple attribute and a reference.
In relational databases, for instance, a table contains the values of attributes directly, but references are
“modeled” by the means of foreign keys. In object-relational persistence technologies such as JPA or
Hibernate references can have additional life-cycle semantics, which define what to do with referenced
objects in certain circumstances. Therefore you typically make a distinction between the two concepts,
as we do in the Domain Model Example you can create using the wizard. However, in this small scenario
we do not need a separation therefore we stick with one single concept for features.
As the type reference has an additional property for the multiplicity (many or one), we make it a separate
model element and parser rule TypeRef. The presence of the postfix ‘*’ in an input file should set the
boolean flag to ‘true’ that indicates a multi-value type reference in the AST model. This is the purpose
of the assignment operator ' ?='. The parser rule looks like this:
TypeRef :
referenced=[Type] (multi?='*')?;
Again we have specified a cross-reference, which this time not only allows to reference entities but all
instances of type. So far this only includes data type and entities, but you may want to introduce additional
concepts in a future version, like for instance a Value Object as proposed in Eric Evan’s great book
Domain Driven Design.
In the end your grammar editor should look like this:
Xtext 1.0 7
Getting Started
grammar org.eclipse.xtext.example.Domainmodel
with org.eclipse.xtext.common.Terminals
DomainModel :
(elements+=Entity)*;
Type:
DataType | Entity;
DataType:
'datatype' name=ID;
Entity:
'entity' name=ID ('extends' superType=[Entity])? '{'
(features+=Feature)*
'}';
Feature:
name=ID ':' type=TypeRef;
TypeRef:
referenced=[Type] (multi?='*')?;
Xtext 1.0 8
Getting Started
package my.entities {
import my.types.*
entity Session {
title: String
isTutorial : Boolean
}
entity Conference {
name : String
attendees : Person*
speakers : Speaker*
}
entity Person {
name : String
}
Let’s start to modify our grammar now. First we introduce the rule AbstractElement:
AbstractElement:
PackageDeclaration | Type;
To allow qualified names, we need a new rule QualifiedName. This rule returns a string. But we do not
want this to be a terminal rule, as terminal rules have special semantics (they are used context-less in the
lexer, which often causes problems). Instead we want it to be a parser rule, but one which doesn’t return
an instance of an EClass from the referenced EPackage but just a plain String. Such rules are called data
type rules, because they return instances of EDataType as opposed to instances of EClass. String is the
Xtext 1.0 9
Getting Started
most often used EDataType in this context and is therefore the default return type for data type rules.
The rule looks like this:
QualifiedName:
ID ('.' ID)*;
Note, that Xtext automatically figures out that the rule is a data type rule rather then a normal parser rule,
because it doesn’t contain any assignments and all rule calls go to either other data type rules or terminal
rules. For a data type rule the parser simply concatenates the consumed text and returns it as a string. The
transformation to a user defined data type is done by so called ValueConverters. But as we use strings
we don’t need to care about ValueConverters here.
Next up we need to define the syntax of PackageDeclarations, which makes use of the QualifiedName
rule but doesn’t make use of anything we haven’t yet talked about.
PackageDeclaration:
'package' name=QualifiedName '{'
(elements+=AbstractElement)*
'}';
Having qualified names at hand, we want to specify cross-references that way, too. As mentioned by
default, Xtext assumes the rule ID as the syntax for cross-references, which has been fully sufficient so
far. But now we want to allow fully qualified names as well, so we explicitly specify the syntax rule
after a delimiter ' |':
fn.. Note, that the ' |' has nothing to do with the previously introduced alternative operator. In the context
of a cross-reference it is simply a delimiter.
Entity:
'entity' name=ID ('extends' superType=[Entity|QualifiedName])? '{'
(features+=Feature)*
'}';
and
TypeRef:
referenced=[Type|QualifiedName] (multi?='*')?;
As the last step, we introduce imports. An Import is an instance of AbstractElement, too, so that it can
occur as a child of DomainModel as well as of PackageDeclaration.
AbstractElement:
PackageDeclaration | Type | Import;
An imported namespace is not just a qualified name but it also allows an optional wildcard character '
*' at the end, so that multiple names can be imported with one statement. That requires a new data type
rule which we name QualifiedNameWithWildCard:
QualifiedNameWithWildCard:
QualifiedName '.*'?;
The default scoping implementation is based on naming conventions. First everything which has a name
is referenceable. By default something has a name if it has a property 'name'. If such an EAttribute
is available, the default implementation computes a qualified name by asking the container for its
name and concatenates the two names separated by a dot. The computation of qualified names can be
arbitrarily changed by implementing an IQualifedNameProvider. The other naming convention is that
if some element has an EAttribute ‘importedNamespace’ that value is used as a namespace import and
is automatically prefixed to any simple names used within that namespace. Also the asterisk ' *' is used
as a wildcard by default.
Xtext 1.0 10
Getting Started
DomainModel:
(elements+=AbstractElement)*;
AbstractElement:
PackageDeclaration | Type | Import;
Import:
'import' importedNamespace=QualifiedNameWithWildCard;
PackageDeclaration:
'package' name=QualifiedName '{'
(elements+=AbstractElement)*
'}';
Type:
Entity | DataType;
DataType:
'datatype' name=ID;
Entity:
'entity' name=ID ('extends' superType=[Entity|QualifiedName])? '{'
(features+=Feature)*
'}';
Feature:
name=ID ':' type=TypeRef;
TypeRef:
referenced=[Type|QualifiedName] (multi?='*')?;
QualifiedName:
ID ('.' ID)*;
QualifiedNameWithWildCard:
QualifiedName '.*'?;
Now you should regenerate the language infrastructure as described in the previous section, and give the
editor a try. You can even split up your model into smaller parts and have cross-references across file
boundaries, as long as the referenced models are on the classpath.
Xtext 1.0 11
Getting Started
The first line initializes the language infrastructure to run in standalone mode. That is EMF is designed
to work in Eclipse and therefore makes use of Equinox extension points in order to register factories
and the like. In a vanilla Java project there is no Equinox, hence we do the registration programmaticly.
The generated MyLanguageStandaloneSetup class does just that. You don’t have to do this kind of
initialization when you run your plug-ins within Eclipse, since in that case the extension point declarations
are used.
The other thing the StandaloneSetup takes care of is creating a Guice injector. The use of Guice and
Dependency Injection is explained here.
Now that the language infrastructure is initialized and the different contributions to EMF are registered,
we want to load a Resource. To do so we first create a ResourceSet, which as the name suggests represents
a set of Resources. If one Resource references another Resource, EMF will automatically load that other
Resource into the same ResourceSet as soon as the cross-reference is resolved. Resolution of cross-
references is done lazy, i.e. on first access.
The 4th line loads the Resource using the resource set. We pass in a URI which points to the file in the
file system. EMF’s URI is a powerful concept. It supports a lot of different schemes to load resources
from file system, web sites, jars, OSGi bundles or even from Java’s classpath. And if that is not enough
you can come up with your own schemes. Also a URI can not only point to a resource but also to any
EObject in a resource. This is done by appending a so called URI fragment to the URI.
The second parameter denotes whether the resource should automatically be loaded if it wasn’t already
before. Alternatively we could have written
Resource resource = rs.getResource(URI.createURI("./mymodel.dmodel"), false);
resource.load(null);
The load method optionally takes a map of properties, which allows to define a contract between a client
and the specific implementation. In Xtext, for instance, we use the map to state whether cross-references
should be eagerly resolved. In order to find out what properties are supported, it’s usually best to look
into the concrete implementations. That said, in most cases you don’t need to pass any properties at all.
The last line
EObject eobject = resource.getContents().get(0);
assigns the root element to a local variable. Actually it is the first element from the contents list of a
Resource, but in Xtext a Resource always has just one root element.
It is also possible to create new instances or get and set values using the reflection layer. That reflection
layer is very helpful when creating generic libraries for EMF models, however if you know what kind of
model you are working with it’s much nicer to program against the generated Java classes. As we know
Xtext 1.0 12
Getting Started
that the root element is an instance of DomainModel we can just cast it to the Java interface generated
by EMF:
DomainModel dm = (DomainModel) eobject;
The generated Java types provide getter and setter methods for each EAttribute and EReference, so that
you can easily navigate the model using Java:
EList<AbstractElement> elements = domainModel.getElements();
for (AbstractElement abstractElement : elements) {
if (abstractElement instanceof Entity) {
Entity entity = ((Entity)abstractElement);
System.out.println("entity "
+ entity.getName()
+ " extends "
+ entity.getSuperType().getName());
}
}
Note that you’ll find a lot of convenience API in EMF’s EcoreUtil and Xtext’s EcoreUtil2.
In addition to the text LeafNodes also hold information about the line, the offset and the length of that
token.
The other node type is called CompositeNode and is created for almost each grammar element. A
composite node can contain other composite nodes and leaf nodes. The super type of both node types is
AbstractNode. One can find a couple of convenience methods in NodeUtil and ParseTreeUtil.
Xtext 1.0 13
Getting Started
outline of your model, it is essential to keep other threads from modifying the model while the outline
component reads it.
Many of the prominent locations where users can hook in their own code in Xtext are already called from
within a thread safe context, e.g. the API for quick fixes. Consequently, the following usually applies
only if you add additional functionality on top of Xtext, e.g. custom UI actions.
Each XtextEditor uses an IXtextDocument to store its model. To avoid synchronization trouble,
neither of them provides direct access to the XtextResource storing the semantic model. Instead, the
IXtextDocument has two methods readOnly() and modify(). Both take an argument of type IUnitOfWork
(<T>, IXtextResource) which defines a method <T> exec(IXtextResource) that contains what you want
to do with the model and allows to deliver a result of arbitrary type.
So here is an example of safely reading a model:
IXtextDocument myDocument = ...;
String rootElementName = myDocument.readOnly(
new IUnitOfWork(){
public String exec(IXtextResource resource) {
MyType type = (MyType)resource.getContents().get(0);
return myType.getName();
}
});
Direct write-access on the document is usually only performed inside the framework. If you want to
change a document by means of its semantic model, you should rather use an IDocumentEditor which
uses the modify() method internally but takes care of synchronizing the node model, too:
@Inject
private IDocumentEditor documentEditor;
2.2.6. Summary
Let’s summarize what we have learned: An Xtext model is loaded by an EMF Resource. The main model
is represented as an instance of so called EClasses which are themselves declared within Ecore models.
A parse tree is created as well, which effectively acts as a tracing model between the text, the AST and
the grammar. The following diagram illustrates the four different kinds of models.
Xtext 1.0 14
Getting Started
Xtext 1.0 15
Getting Started
package java.lang {
datatype String
datatype Boolean
}
package my.entities {
import java.lang.*
entity Session {
title: String
isTutorial : Boolean
}
entity Conference {
name : String
attendees : Person*
speakers : Speaker*
}
entity Person {
name : String
}
Xtext 1.0 16
Getting Started
module workflow.DomainmodelGenerator
import org.eclipse.emf.mwe.utils.*
Workflow {
component = org.eclipse.xtext.mwe.Reader {
// lookup all resources on the classpath
// useJavaClassPath = true
component = org.eclipse.xpand2.Generator {
expand = "templates::Template::main FOREACH greetings"
outlet = {
path = targetDir
}
fileEncoding = fileEncoding
}
}
The first line just declares a name for this workflow file. Any qualified Java identifier is allowed, but it
should match the file name of the MWE2 file (and in future versions we might make this mandatory). It
is followed by an import statement. MWE2 references Java classes and to make that convenient, you can
specify imports after the module declaration. Next up we see a couple of vars are declared. Such vars
can be overridden when invoking a workflow file.
The important part is the Workflow part. There we declare an instance of
org.eclipse.emf.mwe.utils.Workflow and add two instances to the component property. The first one is a
Reader which is used to initialize Xtext languages, read in Xtext files, and fetch specific elements from
those models in order to make them available to following workflow components (such as the declared
Generator).
Xtext language initialization is done by specifying any number of ISetup implementations. In our case the
generated DomainModelStandaloneSetup is registered, which makes sure that the infrastructure of your
domain model language is set up properly. If you have multiple languages just add additional assignments
for each language.
You have to tell the Reader which paths to scan for model files. In this particular case we just specified
one path. Another convenient option is to reuse the Java classpath, as suggested in the comments.
The load section specifies which elements to fetch from the loaded resources. In this case we state that
we want all elements of type Greeting. Note that this is completely file agnostic, it will provide you with
all elements from all files the Reader could find on the specified paths. The slot name is the name by
which other workflow components can access the stored elements.
The second workflow component is an instance of org.eclipse.xpand2.Generator, which is the MWE2
facade to the Xpand template language. The Xpand generator needs to know which template to invoke
for which models. Qualified names in Xpand are separated by a double colon '::'. That is the name
'templates::Template::main' points to the definition main in the file templates/Template.xpt on the Java
classpath. The second part FOREACH greetings references the greetings slot which has previously been
populated by the reader component.
Xtext 1.0 17
Getting Started
An Outlet describes where to put the generated sources. In Xpand there is a file-statement which refers
to outlets. If you only have one outlet you don’t have to give it a name, but you need to declare where
the root folder for that outlet can be found in the file system. I.e. you specifiy where the generated code
should go. Oulets allow you to specify a couple of other things as well. As MWE2 just instantiates Java
objects, you can go to the Java code of org.eclipse.xpand2.output.Outlet in order to find out (see the adder
and setter methods). about the different options.
Now that we understood the most important things in the workflow we have to adapt it to match our
domain model language. We only have to change the type which is used to fetch and filter the elements
in the load section. We want to generate code for entities, therefore we change it to Entity. We should
change the slot’s name, too:
module workflow.DomainmodelGenerator
import org.eclipse.emf.mwe.utils.*
Workflow {
component = org.eclipse.xtext.mwe.Reader {
// lookup all resources on the classpath
// useJavaClassPath = true
component = org.eclipse.xpand2.Generator {
expand = "templates::Template::main FOREACH entities" //changed to entities
outlet = {
path = targetDir
}
fileEncoding = fileEncoding
}
}
2.3.5. Using Xpand (3) and Xtend (4) for Code Generation
The MWE2 file invokes an Xpand definition called main located in templates/Template.xpt. Please open
that file and replace its contents with the following Xpand code:
Xtext 1.0 18
Getting Started
«IMPORT org::eclipse::xtext::example::domainmodel»
«EXTENSION templates::Extensions»
You might get a couple of error markers, because the Xpand file references another file ( Extensions.ext
(4)) which has not yet been updated. Let’s ignore this for a moment and have a look at the general structure
of an Xpand template file. In the first line we import the namespace (i.e. Java package) of the generated
AST classes, that is Entity and Feature, we want to refer to in the generator. Next up the previously
mentioned Xtend file is imported. An Xtend file defines functions which can be used in Xpand.
The rest of the file contains two so called definitions. A definition in Xpand is similar to a function in that
it can be called, it has a name and it is defined for one or more arguments. The general syntax is as follows:
«DEFINE name(ArgType1 arg1, ArgType2 arg2) FOR MainArgType»
Where MainArgType is bound to the variable name this which can like in Java be omitted when referring
to.
The first definition main is defined for Entity and is the one invoked from the previously discussed MWE2
file (2). The first thing the definition does is opening a file using the qualifiedName() of the given Entity.
The function qualifiedName() should be declared in the referenced Xtend file (4). To do so open that file
and replace its current contents by the following snippet:
import org::eclipse::xtext::example::domainmodel;
packageName(Type this) :
qualifiedName(eContainer());
It defines the qualifiedName() function not only for Entity but also generally for types. Note how it
computes the qualified name by calling qualifiedName() recursively on its eContainer(). Both Xpand and
Xtend are based on the same expression language, which is statically typed and allows for very convenient
navigation over object graphs and collections.
Xtext 1.0 19
Getting Started
Back to the Xpand file (3) we see some static text which goes directly into the opened file. The EXPAND
statement calls the other definition defined in this file. It will effectively generate a Java field and two
accessor-methods for each Feature.
You’ll now able able to run the generator by opening the context menu on the *.mwe2 file (2) and choose
Run As->MWE2 Workflow. For more information on Xpand and Xtend see the corresponding language
documentation (available through Eclipse Help). MWE2 is explained in detail in a later section.
Xtext 1.0 20
Chapter 3. The Grammar Language
The grammar language is the corner stone of Xtext. It is a domain-specific language, carefully designed
for the description of textual languages. The main idea is to describe the concrete syntax and how it is
mapped to an in-memory model created during parsing.
resetEvents
doorOpened
end
commands
unlockPanel PNUL
lockPanel PNLK
lockDoor D1LK
unlockDoor D1UL
end
state idle
actions {unlockDoor lockPanel}
doorClosed => active
end
state active
drawOpened => waitingForLight
lightOn => waitingForDraw
end
state waitingForLight
lightOn => unlockedPanel
end
state waitingForDraw
drawOpened => unlockedPanel
end
state unlockedPanel
actions {unlockPanel lockDoor}
panelClosed => idle
end
So, we have a bunch of declared events, commands, and states. Within states there are references
to declared actions, which should be executed when entering such a state. Also there are transitions
consisting of a reference to an event and a state. Please read Martin’s description if you want to read
the whole story.
In order to implment this little language with Xtext, you need to write the following grammar:
Xtext 1.0 21
The Grammar Language
grammar my.pack.SecretCompartments
with org.eclipse.xtext.common.Terminals
Statemachine :
'events'
(events+=Event)+
'end'
('resetEvents'
(resetEvents+=[Event])+
'end')?
'commands'
(commands+=Command)+
'end'
(states+=State)+;
Event :
name=ID code=ID;
Command :
name=ID code=ID;
State :
'state' name=ID
('actions' '{' (actions+=[Command])+ '}')?
(transitions+=Transition)*
'end';
Transition :
event=[Event] '=>' state=[State];
Martin uses this example throughout his book “Domain-Specific Languages” to implement external and
internal DSLs using different technologies. Note, that none of his implmentations is nearly as readable
and concise as the description in Xtext’s grammar language above. That is of course because the grammar
language is designed to do just that, i.e. it is specific to the domain of language descriptions.
Xtext 1.0 22
The Grammar Language
See the section on Referring Java Types for a full explanation of this useful feature.
Xtext 1.0 23
The Grammar Language
When referring to a type somewhere in the grammar you need to qualify the reference using that alias
(example another::CoolType). We’ll see later where such type references occur.
It is also supported to put multiple EPackage imports into one alias. This is no problem as long as there
are not any two EClassifiers with the same name. In such cases none of them can be referenced. It is
even possible to import multiple and generate one Ecore model and all of them are declared for the same
alias. If you do so, for a reference to an EClassifier first the imported EPackages are scanned before it is
assumed that a type needs to by generated into the to-be-generated package.
Note, that using this feature is not recommended, because it might cause problems, which are hard to track
down. For instance, a reference to classA would as well be linked to a newly created EClass, because the
corresponding type in http://www.eclipse.org/packContainingClassA is spelled with a capital letter.
3.2.3. Rules
Basically parsing can be separated in the following phases.
1. lexing
2. parsing
3. linking
4. validation
It says that a token ID starts with an optional '^' character (caret), followed by a letter (‘a’..‘z’|‘A’..‘Z’)
or underscore (‘_’) followed by any number of letters, underscores and numbers (‘0’..‘9’).
The caret is used to escape an identifier for cases where there are conflicts with keywords. It is removed
by the ID rule’s ValueConverter.
This is the formal definition of terminal rules:
TerminalRule :
'terminal' name=ID ('returns' type=TypeRef)? ':'
alternatives=TerminalAlternatives ';'
;
Note, that the order of terminal rules is crucial for your grammar, as they may hide each other. This is
especially important for newly introduced rules in connection with mixed rules from used grammars.
If you for instance want to add a rule to allow fully qualified names in addition to simple IDs, you should
implement it as a data type rule, instead of adding another terminal rule.
Return Types
A terminal rule returns a value, which is a string (type ecore::EString) by default. However, if you want
to have a different type you can specify it. For instance, the rule INT is defined as:
terminal INT returns ecore::EInt :
('0'..'9')+;
Xtext 1.0 24
The Grammar Language
This means that the terminal rule INT returns instances of ecore::EInt. It is possible to define any kind
of data type here, which just needs to be an instance of ecore::EDataType. In order to tell the parser
how to convert the parsed string to a value of the declared data type, you need to provide your own
implementation of IValueConverterService (cf. value converters). The value converter is also the point
where you can remove things like quotes from string literals or the caret (‘^’) from identifiers. Its
implementation needs to be registered as a service (cf. Service Framework).
Keywords / Characters
Keywords are a kind of token rule literals. The ID rule in org.eclipse.xtext.common.Terminals for instance
starts with a keyword:
terminal ID : '^'? .... ;
The question mark sets the cardinality to “none or one” (i.e. optional) like explained above.
Note that a keyword can have any length and contain arbitrary characters.
The following standard Java notations for special characters are allowed: \n, \r, \t, \b, and \f. We currently
don’t support quoted unicode character notation, as \u123.
Character Ranges
A character range can be declared using the ‘..’ operator.
Example:
terminal INT returns ecore::EInt: ('0'..'9')+;
In this case an INT is comprised of one or more (note the + operator) characters between (and including)
'0' and '9'.
Wildcard
If you want to allow any character you can simple write the wildcard operator ' .' (dot): Example:
FOO : 'f' . 'o';
The rule above would allow expressions like ‘foo’, ‘f0o’ or even ‘f\no’.
Until Token
With the until token it is possible to state that everything should be consumed until a certain token occurs.
The multi-line comment is implemented this way:
terminal ML_COMMENT : '/*' -> '*/';
This is the rule for Java-style comments that begin with ' /*' and end with ' */'.
Negated Token
All the tokens explained above can be inverted using a preceding exclamation mark:
terminal BETWEEN_HASHES : '#' (!'#')* '#';
Rule Calls
Rules can refer to other rules. This is done by writing the name of the rule to be called. We refer to this
as rule calls. Rule calls in terminal rules can only point to terminal rules.
Example:
terminal DOUBLE : INT '.' INT;
Xtext 1.0 25
The Grammar Language
Alternatives
Using alternatives one can state multiple different alternatives. For instance, the whitespace rule uses
alternatives like this:
terminal WS : (' '|'\t'|'\r'|'\n')+;
That is a WS can be made of one or more whitespace characters (including ‘ ’, ' \t', ' \r', ' \n').
Groups
Finally, if you put tokens one after another, the whole sequence is referred to as a group. Example:
terminal ASCII : '0x' ('0'..'7') ('0'..'9'|'A'..'F');
That is the 2-digit hexadecimal code of ASCII characters.
Assignments
Assignments are used to assign the parsed information to a feature of the current object. The type of the
current object, its EClass, is specified by the return type of the parser rule. If it is not explicitly stated it
is implied that the type’s name equals the rule’s name. The type of the feature is inferred from the right
hand side of the assignment.
Example:
State :
'state' name=ID
('actions' '{' (actions+=[Command])+ '}')?
(transitions+=Transition)*
'end'
;
The syntactic declaration for states in the state machine example starts with a keyword state followed
by an assignment:
name=ID
The left hand side refers to a feature ' name' of the current object (which has the EClass ' State' in this
case). The right hand side can be a rule call, a keyword, a cross-reference (explained later) or even an
alternative comprised by the former. The type of the feature needs to be compatible with the type of the
expression on the right. As ID returns an EString in this case, the feature ' name' needs to be of type
EString as well.
Assignment Operators
There are three different assignment operators, each with different semantics.
Xtext 1.0 26
The Grammar Language
1. The simple equal sign ' =' is the straight forward assignment, and used for features which take only
one element.
2. The ' +=' sign (the add operator) expects a multi-valued feature and adds the value on the right hand
to that feature, which is a list feature.
3. The ' ?=' sign (boolean assignment operator) expects a feature of type EBoolean and sets it to true if
the right hand side was consumed independently from the concrete value of the right hand side.
The used assignment operator does not effect the cardinality of the expected symbols on the right hand
side.
Cross-References
A unique feature of Xtext is the ability to declare crosslinks in the grammar. In traditional compiler
construction the crosslinks are not established during parsing but in a later linking phase. This is the same
in Xtext, but we allow to specify crosslink information in the grammar. This information is used by the
linker. The syntax for crosslinks is:
CrossReference :
'[' type=TypeRef ('|' ^terminal=CrossReferenceableTerminal )? ']'
;
For example, the transition is made up of two cross-references, pointing to an event and a state:
Transition :
event=[Event] '=>' state=[State]
;
It is important to understand that the text between the square brackets does not refer to another rule, but
to a type! This is sometimes confusing, because one usually uses the same name for the rules and the
returned types. That is if we had named the type for events differently like in the following the cross-
reference needs to be adapted as well:
Transition :
event=[MyEvent] '=>' state=[State]
;
Looking at the syntax definition of cross-references, there is an optional part starting with a vertical bar
(pipe) followed by CrossReferenceableTerminal. This is the part describing the concrete text, from which
the crosslink later should be established. If the terminal is omitted, it is expected to be ID.
You may even use alternatives as the referencable terminal. This way, either an ID or a STRING may be
used as the referencable terminal, as it is possible in many SQL dialects.
TableRef: table=[Table|(ID|STRING)];
Have a look at the linking section in order to understand how linking is done.
Unordered Groups
The elements of an unordered group can occur in any order but each element must appear once. Unordered
groups are separated with ' &', e.g.
Modifier:
static?='static'? & final?='final'? & visibility=Visibility;
enum Visibility:
PUBLIC='public' | PRIVATE='private' | PROTECTED='protected';
allows
public static final
static protected
final private static
public
Xtext 1.0 27
The Grammar Language
but not
static final static // ERROR: static appears twice
public static final private // ERROR: visibility appears twice
final // ERROR: visibility is missing
Note that if you want an element of an unordered group to appear once or not at all, you have to choose
a cardinality of ' ?'. In the example, the visibility is mandatory, while ' static' or ' final' are optional.
Elements with a cardinality of ' *' or ' +' have to appear continuously without interruption, i.e.
Rule:
values+=INT* & name=ID;
will parse
0 8 15 x
x 0 8 15
but not
0 x 8 15 // wrong, as values cannot be interrupted.
Simple Actions
By default the object to be returned by a parser rule is created lazily on the first assignment. Then the type
of the EObject to be created is determined from the specified return type or the rule name if no explicit
return type is specified. With Actions however, the creation of returned EObject can be made explicit.
Xtext supports two kinds of Actions:
1. simple actions, and
2. assigned actions.
If at some point you want to enforce the creation of a specific type you can use alternatives or simple
actions. In the following example TypeB must be a subtype of TypeA. An expression A ident should create
an instance of TypeA, whereas B ident should instantiate TypeB.
Example with alternatives:
MyRule returns TypeA :
"A" name=ID |
MyOtherRule
;
Generally speaking, the instance is created as soon as the parser hits the first assignment. However,
actions allow to explicitly instantiate any EObject. The notation {TypeB} will create an instance of TypeB
and assign it to the result of the parser rule. This allows parser rules without any assignment and object
creation without the need to introduce unnecessary rules.
Xtext 1.0 28
The Grammar Language
Unassigned rule calls (the name suggests it) are rule calls to other parser rules, which are not used within
an assignment. If there is no feature the returned value shall be assigned to, the value is assigned to the
“to-be-returned” result of the calling rule.
With unassigned rule calls one can, for instance, create rules which just dispatch between several other
rules:
AbstractToken :
TokenA |
TokenB |
TokenC
;
As AbstractToken could possibly return an instance of TokenA, TokenB or TokenC its type must by a
super type of these types. It is now for instance as well possible to further change the state of the AST
element by assigning additional things.
Example:
AbstractToken :
( TokenA |
TokenB |
TokenC ) (cardinality=('?'|'+'|'*'))?
;
This way the cardinality is optional (last question mark) and can be represented by a question mark, a
plus, or an asterisk. It will be assigned to either an EObject of type TokenA, TokenB, or TokenC which are
all subtypes of AbstractToken. The rule in this example will never create an instance of AbstractToken
directly as long as the preceeding TokenX rule call returns an element.
Assigned Actions
LL-parsing has some significant advantages over LR algorithms. The most important ones for Xtext are,
that the generated code is much simpler to understand and debug and that it is easier to recover from
errors. Especially ANTLR has a very nice generic error recovery mechanism. This allows to construct
an AST even if there are syntactic errors in the text. You wouldn’t get any of the nice IDE features as
soon as there is one little error, if we hadn’t error recovery.
However, LL also has some drawbacks. The most important one is that it does not allow left recursive
grammars. For instance, the following is not allowed in LL-based grammars, because Expression ‘+’
Expression is left recursive:
Expression :
Expression '+' Expression |
'(' Expression ')' |
INT
;
TerminalExpression :
'(' Expression ')' |
INT
;
In practice this is always the same pattern and therefore not that problematic. However, by simply
applying the Xtext AST construction features we’ve covered so far, a grammar ...
Xtext 1.0 29
The Grammar Language
Expression :
{Operation} left=TerminalExpression (op='+' right=TerminalExpression)?
;
... would result in unwanted elements in the AST. For instance the expression (42) would result in a tree
like this:
Operation {
left=Operation {
left=IntLiteral {
value=42
}
}
}
Typically one would only want to have one instance of IntLiteral instead.
One can solve this problem using a combination of unassigned rule calls and assigned actions:
Expression :
TerminalExpression ({Operation.left=current}
op='+' right=Expression)?
;
In the example above {Operation.left=current} is a so called tree rewrite action, which creates a new
instance of the stated EClass ( Operation in this case) and assigns the element currently to-be-returned
( current variable) to a feature of the newly created object (in this case feature left of the Operation
instance). In Java these semantics could be expressed as:
Operation temp = new Operation();
temp.setLeft(current);
current = temp;
Xtext 1.0 30
The Grammar Language
Fullname:
(firstname=ID)? lastname=ID
;
The sample rule “Person” defines multiline comments (_ML_COMMENT_), single-line comments
(_SL_COMMENT_), and whitespace ( WS) to be allowed between the Fullname and the age. Because
the rule Fullname does not introduce another set of hidden terminals, it allows the same symbols to appear
between firstname and lastname as the calling rule Person. Thus, the following input is perfectly valid
for the given grammar snippet:
John /* comment */ Smith // line comment
/* comment */
42 ; // line comment
A list of all default terminals like WS can be found in section Grammar Mixins.
In contrast to a terminal rule this is only valid in certain contexts, i.e. it won’t conflict with the rule ID.
If you had defined it as a terminal rule, it would possibly hide the ID rule.
In addition when this has been defined as a data type rule, it is allowed to use hidden tokens (e.g. “/*
comment **/”) between the IDs and dots (e.g. foo/* comment */. bar . Baz).
Return types can be specified in the same way as in terminal rules:
QualifiedName returns ecore::EString :
ID ('.' ID)*
;
Note that if a rule does not call another parser rule and does neither contain any actions nor assignments,
it is considered to be a data type rule and the data type EString is implied if none has been explicitly
declared. You have to import Ecore with the alias ecore in this case.
For conversion again value converters are responsible (cf. value converters).
Xtext 1.0 31
The Grammar Language
It is even possible to use alternative literals for your enums or reference an enum value twice:
enum ChangeKind :
ADD = 'add' | ADD = '+' |
MOVE = 'move' | MOVE = '->' |
REMOVE = 'remove' | REMOVE = '-'
;
Please note, that Ecore does not support unset values for enums. If you formulate a grammar like
Element: "element" name=ID (value=SomeEnum)?;
with the input of
element Foo
the resulting value of the element Foo will hold the enum value with the internal representation of
‘0’ (zero). When generating the EPackage from your grammar this will be the first literal you define. As
a workaround you could introduce a dedicated none-value or order the enums accordingly. Note that it
is not possible to define an enum literal with an empty textual representation.
enum Visibility:
package | private | protected | public
;
You can overcome this by modifying the infered Ecore model through a model to model transformation.
Xtext 1.0 32
The Grammar Language
• Entering a group in an alternative the set is reset to the same state it was in when entering the first
group of this alternative.
• Leaving an alternative the set contains the union of all types at the end of each of its groups.
• After an optional element, the set is reset to the same state it was before entering it.
• After a mandatory (non-optional) rule call or mandatory action the set contains only the return type
of the called rule or action.
• An optional rule call does not modify the set.
• A rule call is optional, if its cardinality is ' ?' or ' *'.
While iterating the parser rules Xtext creates
• an EAttribute in each current return type
• of type EBoolean for each feature assignment using the ' ?=' operator. No further EReferences or
EAttributes will be generated from this assignment.
• for each assignment with the ' =' or ' +=' operator calling a terminal rule. Its type will be the return
type of the called rule.
• an EReference in each current return type
• for each assignment with the ' =' or ' +=' operator in a parser rule calling a parser rule. The
EReference's type will be the return type of the called parser rule.
• for each assigned action. The reference’s type will be set to the return type of the current calling rule.
Each EAttribute or EReference takes its name from the assignment or action that caused it. Multiplicities
will be 0...1 for assignments with the ' =' operator and 0...* for assignments with the ' +=' operator.
Furthermore, each type that is added to the currently possible return types automatically extends the
current return type of the parser rule. You can specify additional common super types by means of
“artificial” parser rules, that are never called, e.g.
CommonSuperType:
SubTypeA | SubTypeB | SubTypeC;
process(ecore::EPackage this) :
... do something
;
Xtext 1.0 33
The Grammar Language
The invoked extension can then augment the generated Ecore model in place. Some typical use cases
are to:
• set default values for attributes,
• add container references as opposites of existing containment references, or
• add operations with implementation using a body annotation.
Great care must be taken to not modify the Ecore model in a way preventing the Xtext parser from
working correctly (e.g. removing or renaming model elements).
Mixing in another grammar makes the rules defined in that grammar referable. It is also possible to
overwrite rules from the used grammar.
Example :
grammar my.SuperGrammar
...
RuleA : "a" stuff=RuleB;
RuleB : "{" name=ID "}";
Model : (ruleAs+=RuleA)*;
// overrides my.SuperGrammar.RuleB
RuleB : '[' name=ID ']';
Note that declared terminal rules always get a higher priority then imported terminal rules.
Xtext 1.0 34
The Grammar Language
grammar org.eclipse.xtext.common.Terminals
hidden(WS, ML_COMMENT, SL_COMMENT)
terminal ID :
'^'?('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'_'|'0'..'9')* ;
terminal INT returns ecore::EInt: ('0'..'9')+ ;
terminal STRING :
'"' ( '\\' ('b'|'t'|'n'|'f'|'r'|'"'|"'"|'\\') | !('\\'|'"') )* '"' |
"'" ( '\\' ('b'|'t'|'n'|'f'|'r'|'"'|"'"|'\\') | !('\\'|"'") )* "'";
terminal ML_COMMENT : '/*' -> '*/' ;
terminal SL_COMMENT : '//' !('\n'|'\r')* ('\r'? '\n')? ;
terminal WS : (' '|'\t'|'\r'|'\n')+ ;
terminal ANY_OTHER: . ;
Xtext 1.0 35
Chapter 4. Configuration
4.1. The Generator
Xtext provides lots of generic implementations for your language’s infrastructure but also uses code
generation to generate some of the components. Those generated components are for instance the parser,
the serializer, the inferred Ecore model (if any) and a couple of convenient base classes for content assist,
etc.
The generator also contributes to shared project resources such as the plugin.xml, MANIFEST.MF and
the Guice modules.
Xtext’s generator leverages MWE2 – the modeling workflow engine from EMFT to configure the
generator.
One can create a family tree with MWE2 easily by describing it in a declarative manner without writing
a single line of Java code and without the need to compile classes:
module com.mycompany.CreatePersons
Person {
name = "Grandpa"
child = {
name = "Father"
child = {
name = "Son"
}
}
}
These couple of lines will, when interpreted by MWE2, result in an object tree consisting of three
instances of com.mycompany.Person. The interpreter will basically do the same as the following main
method:
Xtext 1.0 36
Configuration
package com.mycompany;
The root element is a class-name following the Java classpath visibility rules. As the module is a
sibling to the class com.mycompany.Person it is not necessary to use use fully qualified name. There
are other packages implicitly imported into this workflow as well to make it convenient to instantiate
actual workflows and components, but these ones are covered in depth in the appropriate chapter. The
constructed objects are furthermore configured according to the declaration in the module, e.g. a second
instance of Person will be created and added to the list of children of “Grandpa” while the third person –
the class is inferred from the assigned feature – becomes a child of “Father”. All three instances will have
their respective name assigned via a reflective invocation setName. If one wants to add another child to
“Father”, she can simply repeat the child assignment:
child = com.mycompany.Person {
name = "Father"
child = {
name = "Son"
}
child = {
name = "Daughter"
}
}
As you can see in the example above MWE2 can be used to instantiate arbitrary Java object models
without any dependency or limitation to MWE2 specific implementations. This is conceptually very close
to the dependency injection mechanism and the XML language in the Spring Framework.
Tip Whenever you are in an *.mwe2 file and wonder what kind of configuration the underlying component
may accept: Just use the Content Assist in the MWE2 Editor or navigate directly to the declaration of the
underlying Java implementation by means of F3 (Go To Declaration).
This is the basic idea of the MWE2 language. There are of course a couple of additional concepts and
features in the language and we also have not yet talked about the runtime workflow model. Please refer
to the dedicated MWE2 reference documentation for additional information.
Xtext 1.0 37
Configuration
4.1.2.2. Configuration
As already explained we use MWE2 from EMFT in order to instantiate, configure and execute this
structure of components. In the following we see an exemplary Xtext generator configuration written in
MWE2 configuration code:
Xtext 1.0 38
Configuration
module org.xtext.example.MyDsl
import org.eclipse.emf.mwe.utils.*
import org.eclipse.xtext.generator.*
import org.eclipse.xtext.ui.generator.*
Workflow {
bean = StandaloneSetup {
platformUri = "${runtimeProject}/.."
}
component = DirectoryCleaner {
directory = "${runtimeProject}/src-gen"
}
component = DirectoryCleaner {
directory = "${runtimeProject}.ui/src-gen"
}
component = Generator {
pathRtProject = runtimeProject
pathUiProject = "${runtimeProject}.ui"
projectNameRt = projectName
projectNameUi = "${projectName}.ui"
language = {
uri = grammarURI
fileExtensions = file.extensions
Here the root element is Workflow and is part of the very slim runtime model shipped with MWE2. It
accepts bean s and component s. The var declaration is a first class concept of MWE2’s configuration
language and defines the interface of the module. They allow to externalize some common configuration
parameters. This comes especially handy in String variables where one can easily use ${variable} to
concatenate values.
The method Workflow.addBean(Object) does nothing but provides a means to apply global side-effects,
which unfortunately is required sometimes. In this example we do a so called EMF stand-alone setup.
This class initializes a bunch of things for a non-OSGi environment that are otherwise configured by
means of extension points, e.g. it allows to populate EMF’s singletons like the EPackage.Registry.
Following the bean assignment there are three component elements. The Workflow.addComponent()
method accepts instances of IWorkflowComponent, which is the primary concept of MWE2’s workflow
model. Xtext’s generator itself is an instance of IWorkflowComponent and can therefore be used within
MWE2 workflows.
There are two fragments ImplicitRuntimeFragment and ImplicitUiFragment will be called implicitly if
the required paths and project names are set. They take care of common defaults.
Xtext 1.0 39
Configuration
@Inject
private IScopeProvider scopeProvider;
It is not the duty of the code to care about where the IScopeProvider comes from or how it is created.
When above’s class is instantiated, Guice sees that it requires an instance of IScopeProvider and assigns
it to the specified field or method parameter. This of course only works, if the object itself is created
by Guice. In Xtext almost every instance is created that way and therefore the whole dependency net is
controlled and configured by the means of Google Guice.
Guice of course needs to know how to instantiate real objects for declared dependencies. This is done in
so called Modules. A Module defines a set of mappings from types to either existing instances, instance
providers or concrete classes. Modules are implemented in Java. Here’s an example:
public class MyDslRuntimeModule extends AbstractMyDslRuntimeModule {
@Override
public void configure(Binder binder) {
super.configure(binder);
binder.bind(IScopeProvider.class).to(MyConcreteScopeProvider.class);
}
}
Xtext 1.0 40
Configuration
With plain Guice modules one implements a method called configure and gets a so called Binder passed
in. That binder provides a fluent API to define the mentioned mappings. This was just a very brief and
simplified description. We highly recommend to have a look at the website Google Guice to learn more.
which would do the same as the code snippet above. It simply declares a binding from IScopeProvider
to MyConcreteScopeProvider. That binding will make Guice instantiate and inject a new instance of
MyConcreteScopeProvider whenever a dependency to IScopeProvider is declared.
Having a method per binding allows to deactivate individual bindings by overriding the corresponding
methods and either change the binding by returning a different target type or removing that binding
completely by returning null.
There are two additional kinds of binding-methods supported. The first one allows to configure a provider.
A Provider is an interface with just one method :
public interface Provider<T> {
/**
* Provides an instance of {@code T}. Must never return {@code null}.
*/
T get();
}
This one can be used if you need a hook whenever an instance of a certain type is created. For instance if
you want to provide lazy access to a singleton or you need to do some computation each time an instance
is created (i.e. factory). If you want to point to a provider rather than to a concrete class you can use the
following binding method.
public Class<? extends Provider<IScopeProvider>> provideIScopeProvider() {
return MyConcreteScopeProviderFactory.class;
}
(Please forgive us the overuse of the term provider. The IScopeProvider is not a Guice provider .)
That binding tells Guice to instantiate MyConcreteScopeProviderFactory and invoke get() in order
to obtain an instance of IScopeProvider for clients having declared a dependency to that type. Both
mentioned methods are allowed to return an instance instead of a type. This may be useful if some global
state should be shared in the application:
public Provider<IScopeProvider> provideIScopeProvider() {
return new MyConcreteScopeProviderFactory();
}
or
public IScopeProvider bindIScopeProvider() {
return new MyConcreteScopeProvider();
}
respectively.
Xtext 1.0 41
Configuration
The last binding method provided by Xtext allows to do anything you can do with Guice’s binding API,
since it allows you to use it directly. If your method’s name starts with the name ‘configure’, has a return
type void and accepts one argument of type Binder
public void configureIScopeProvider(Binder binder) {
binder.bind(IScopeProvider.class).to(MyConcreteScopeProvider.class);
}
Xtext uses EMF which makes use of a couple of global registries, which have to be configured
on startup. Because we of course want to leverage Guice also for all factories, etc. that we put
into those registries, we have introduced a so called ISetup which provides a method called Injector
createInjectorAndDoEMFRegistration(). So instead of using the plain Guice code shown above you
rather use the ISetup class generated for your language, which, as the method name suggests, creates an
Injector and uses it to initialize a couple of EMF objects and register them in the corresponding registries.
Injector injector =
new MyStandaloneSetup().createInjectorAndDoEMFRegistration();
These are the basic ideas around Guice and the small extension Xtext provides on top. For more
information we strongly encourage you to read through the documentation on the website of Google
Guice.
Xtext 1.0 42
Chapter 5. Runtime Concepts
Xtext itself and every language infrastructure developed with Xtext is configured and wired-up using
dependency injection. Xtext may be used in different environments which introduce different constraints.
Especially important is the difference between OSGi managed containers and plain vanilla Java programs.
To honor these differences Xtext uses the concept of ISetup-implementations in normal mode and uses
Eclipse’s extension mechanism when it should be configured in an OSGi environment.
5.3. Logging
Xtext uses Apache’s log4j for logging. It is configured using the so called log4j.properties, which is
looked up in the root of the Java classpath. If you want to change or provide configuration at runtime
(i.e. non-OSGI), all you have to do is putting such a log4j.properties in place and make sure that it is not
overridden by other log4j.properties in previous classpath entries.
In OSGi you provide configuration by creating a fragment for org.apache.log4j. In this case you need to
make sure that there’s no second fragment contributing a log4j.properties file.
5.4. Validation
Static analysis or validation is one of the most interesting aspects when developing a programming
language. The users of your languages will be grateful if they get informative feedback as they type. In
Xtext there are basically three different kinds of validation.
Xtext 1.0 43
Runtime Concepts
Xtext 1.0 44
Runtime Concepts
@SingletonBinding(eager = true)
public Class<? extends ConcreteSyntaxEValidator>
bindConcreteSyntaxEValidator() {
return ConcreteSyntaxEValidator.class;
}
To customize error messages please see IConcreteSyntaxDiagnosticProvider and subclass
ConcreteSyntaxDiagnosticProvider.
The generator will provide you with two Java classes. An abstract class generated to src-gen/ which
extends the library class AbstractDeclarativeValidator. This one just registers the EPackages for which
this validator introduces constraints. The other class is a subclass of that abstract class and is generated
to the src/ folder in order to be edited by you. That’s where you put the constraints in.
The purpose of the AbstractDeclarativeValidator is to allow you to write constraints in a declarative way
– as the class name already suggests. That is instead of writing exhaustive if-else constructs or extending
the generated EMF switch you just have to add the @Check annotation to any method and it will be
invoked automatically when validation takes place. Moreover you can state for what type the respective
constraint method is, just by declaring a typed parameter. This also lets you avoid any type casts. In
addition to the reflective invocation of validation methods the AbstractDeclarativeValidator provides a
couple of convenient assertions.
All in all this is very similar to how JUnit works. Here is an example:
public class DomainmodelJavaValidator
extends AbstractDomainmodelJavaValidator {
@Check
public void checkTypeNameStartsWithCapital(Type type) {
if (!Character.isUpperCase(type.getName().charAt(0)))
warning("Name should start with a capital",
DomainmodelPackage.TYPE__NAME);
}
}
You can also implement quick fixes for individual validation errors and warnings. See the chapter on
quick fixes for details.
After regenerating your language artifacts you will find three new files “YourLanguageChecks.chk”,
“YourLanguageFastChecks.chk” and “YourLanguageExpensiveChecks.chk” in the src/ folder in the
sub-package validation. The checks in these files will be executed when saving a file, while typing
Xtext 1.0 45
Runtime Concepts
(FastChecks) or when triggering the validation explicitly (ExpensiveChecks). When using Check the
example of the previous chapter could be written like this.
context Type#name WARNING "Name should start with a capital":
name.toFirstUpper() == name;
Each check works in a specific context (here: Type) and can further denote a feature to which a warning
or error should be attached to (here: name). Each check could either be a WARNING or an ERROR with
a given string to explain the situation. The essential part of each check is an invariant that must hold true
for the given context. If it fails the check will produce an issue with the provided explanation.
Please read more about the Check language as well as the underlying expression language in Xpand’s
reference documentation which is shipped as Eclipse help.
JUnit-Test:
Xtext 1.0 46
Runtime Concepts
@Override
public void setUp() {
with(MyLanguageStandaloneSetup.class);
MyLanguageValidator validator = get(MyLanguageValidator.class);
tester = new ValidatorTester<TestingValidator>(validator);
}
tester.validator().checkFooElement(model);
tester.diagnose().assertError(101);
}
tester.validate(model).assertError(101);
}
}
This example uses JUnit 3, but since the involved classes from Xtext have no dependency on
JUnit whatsoever, JUnit 4 and other testing frameworks will work as well. JUnit runs the setUp()-
method before each testcase and thereby helps to create some common state. In this example, the
validator ( MyLanguageValidator) is instantiated by means of Google Guice. As we inherit from
the AbstractXtextTests there are a plenty of useful methods available and the state of the global
EMF singletons will be restored in the tearDown(). Afterwards, the ValidatorTester is created and
parameterized with the actual validator. It acts as a wrapper for the validator, ensures that the validator
has a valid state and provides convenient access to the validator itself ( tester.validator()) as well as to the
utility classes which assert diagnostics created by the validator ( tester.diagnose()). Please be aware that
you have to call validator() before you can call diagnose(). However, you can call validator() multiple
times in a row.
While validator() allows to call the validator’s @Check-methods directly, validate(model) leaves it to
the framework to call the applicable @Check-methods. However, to avoid side-effects between tests, it
is recommended to call the @Check-methods directly.
diagnose() and validate(model) return an object of type AssertableDiagnostics which provides several
assert-methods to verify whether the expected diagnostics are present:
• assertError(int code): There must be one diagnostic with severity ERROR and the supplied error code.
• assertErrorContains(String messageFragment): There must be one diagnostic with severity ERROR
and its message must contain messageFragment.
• assertError(int code, String messageFragment): Verifies severity, error code and messageFragment.
• assertWarning(...): This method is available for the same combination of parameters as assertError().
• assertOK(): Expects that no diagnostics (errors, warnings etc.) have been raised.
• assertDiagnostics(int severity, int code, String messageFragment): Verifies severity, error code and
messageFragment.
• assertAll(DiagnosticPredicate... predicates): Allows to describe multiple diagnostics at the same
time and verifies that all of them are present. Class AssertableDiagnostics contains static
error() and warning()-methods which help to create the needed DiagnosticPredicate. Example:
assertAll(error(123), warning(“some part of the message”)).
• assertAny(DiagnosticPredicate predicate): Asserts that a diagnostic exists which matches the
predicate.
Xtext 1.0 47
Runtime Concepts
5.5. Linking
The linking feature allows for specification of cross-references within an Xtext grammar. The following
things are needed for the linking:
1. declaration of a crosslink in the grammar (at least in the Ecore model)
2. specification of linking semantics (usually provided via the scoping API)
Example:
ReferringType :
'ref' referencedObject=[Entity|STRING]
;
The Ecore model inference would create an EClass ReferringType with an EReference referencedObject
of type Entity ( containment=false). The referenced object would be identified either by a STRING and
the surrounding information in the current context (see scoping). If you do not use generate but import
an existing Ecore model, the class ReferringType (or one of its super types) would need to have an
EReference of type Entity (or one of its super types) declared. Also the EReference's containment and
container properties needs to be set to false.
5.6. Scoping
Using the scoping API one defines which elements are referable by a certain reference. For instance, using
the introductory example (fowler’s state machine language) a transition contains two cross-references:
One to a declared event and one to a declared state.
Example:
Xtext 1.0 48
Runtime Concepts
events
nothingImportant MYEV
end
state idle
nothingImportant => idle
end
The grammar states that for the reference event only instances of the type Event are allowed and that for
the EReference state only instances of type State can be referenced. However, this simple declaration
doesn’t say anything about where to find the states or events. That is the duty of scopes.
An IScopeProvider is responsible for providing an IScope for a given context EObject and EReference.
The returned IScope should contain all target candidates for the given object and cross-reference.
public interface IScopeProvider {
/**
* Returns a scope for the given context. The scope
* provides access to the compatible visible EObjects
* for a given reference.
*
* @param context the element from which an element shall be referenced
* @param reference the reference to be used to filter the elements.
* @return {@link IScope} representing the inner most {@link IScope} for
* the passed context and reference. Note for implementors: The
* result may not be <code>null</code>. Return
* <code>IScope.NULLSCOPE</code> instead.
*/
IScope getScope(EObject context, EReference reference);
A single IScope represents an element of a linked list of scopes. That means that a scope can be nested
within an outer scope. Each scope works like a symbol table or a map where the keys are strings and the
values are so called IEObjectDescription, which is effectively an abstract description of a real EObject.
Xtext 1.0 49
Runtime Concepts
information is important in order to compute the transitive hull of dependent resources, which the shipped
index infrastructure automatically does for you.
For users and especially in the context of scoping the most important information is the list of exported
EObjects. An IEObjectDescription contains information about the URI to the actual EObject and the
qualified name of that element as well as the corresponding EClass. In addition one can export arbitrary
information using the user data map. The following diagram gives an overview on the description classes
and their relationships.
Xtext 1.0 50
Runtime Concepts
If you’re running in a Guice enabled scenario, the code looks like this:
@Inject
private IResourceServiceProvider.Registry resourceServiceProviderRegistry;
If you don’t run in a Guice enabled context you will likely have to directly access the singleton:
private IResourceServiceProvider.Registry resourceServiceProviderRegistry =
IResourceServiceProvider.Registry.INSTANCE;
However, we strongly encourage you to use dependency injection. Now, that we know how to
export elements to be referenceable from other resources, we need to learn how those exported
IEObjectDescriptions can be made available to the referencing resources. That is the responsibility of
global scoping (i.e. IGlobalScopeProvider) which is described in the following chapter.
Import :
'import' importURI=STRING; // feature must be named importURI
This effectively allows import statements to be declared before the events section. In addition you’ll have
to make sure that you have bound the ImportUriGlobalScopeProvider for the type IGlobalScopeProvider
by the means of Guice. That implementation looks up any EAttributes named ‘importURI’ in your
model and interprets their values as URIs that point to imported resources. That is it adds the
corresponding resources to the current resource’s resource set. In addition the scope provider uses
the IResourceDescription.Manager of that imported resource to compute all the IEObjectDescriptions
returned by the IScope.
Global scopes based on import URIs are available if you use the ImportURIScopingFragment
in the workflow of your language. It will bind an ImportUriGlobalScopeProvider (
IgnoreCaseImportUriGlobalScopeProvider if the caseInsensitve flag is set) that handles importURI
features.
Xtext 1.0 51
Runtime Concepts
of classpaths to define containers (jars and class folders) which contain any referenceable elements. In
the case of Java also the order of such entries is important.
Since version 1.0.0 Xtext provides support for this kind of global scoping. To enable it, a
DefaultGlobalScopeProvider has to be bound to the IGlobalScopeProvider interface. For case insensitive
names use the IgnoreCaseDefaultGlobalScopeProvider.
By default Xtext leverages the classpath mechanism since it is well designed and already understood
by most of our users. The available tooling provided by JDT and PDE to configure the classpath adds
even more value. However, it is just a default: You can reuse the infrastructure without using Java and
independent from the JDT.
In order to know what is available in the “world” a global scope provider which relies on external
configuration needs to read that configuration in and be able to find all candidates for a certain EReference.
If you don’t want to force users to have a folder and file name structure reflecting the actual qualified
names of the referenceable EObjects, you’ll have to load all resources up front and either keep holding
them in memory or remembering all information which is needed for the resolution of cross-references.
In Xtext that information is provided by a so called IEObjectDescription .
Xtext ships two implementations of IContainer.Manager which are as usual bound with Guice:
The default binding is to SimpleResourceDescriptionsBasedContainerManager, which assumes all
IResourceDescription to be in a single common container. If you don’t care about container support,
you’ll be fine with this one. Alternatively, you can bind StateBasedContainerManager and an additional
IAllContainersState which keeps track of the set of available containers and their visibility relationships.
Xtext 1.0 52
Runtime Concepts
Xtext offers a couple of strategies for managing containers: If you’re running an Eclipse workbench,
you can define containers based on Java projects and their classpaths or based on plain Eclipse projects.
Outside Eclipse, you can provide a set of file system paths to be scanned for models. All of these only
differ in the bound instance of IAllContainerState of the referring language. These will be described in
detail in the following sections.
Xtext 1.0 53
Runtime Concepts
in the UI module of the referencing language. The latter looks a bit more difficult than a common
binding, as we have to bind a global singleton to a Guice provider. The StrictJavaProjectsState requires
all elements to be on the classpath, while the default JavaProjectsState also allows models in non-source
folders.
ResourceSet-Based Containers
If you need an IContainer.Manager that is independent of Eclipse projects, you can use the
ResourceSetBasedAllContainersState. This one can be configured with a mapping of container handles
to resource URIs.
It is unlikely you want to use this strategy directly in your own code, but it is used in the back-end of the
MWE2 workflow component Reader. This is responsible for reading in models in a workflow, e.g. for
later code generation. The Reader allows to either scan the whole classpath or a set of paths for all models
therein. When paths are given, each path entry becomes an IContainer of its own. In the following snippet,
component = org.eclipse.xtext.mwe.Reader {
// lookup all resources on the classpath
// useJavaClassPath = true
...
}
Xtext 1.0 54
Runtime Concepts
In fact the classpath scope should also reflect the order of classpath entries. For instance:
classpathScope{stuff from bin/}
-> classpathScope{stuff from foo.jar/}
-> ...
-> classpathScope{stuff from JRE System Library}
-> NULLSCOPE{}
Please find the motivation behind this and some additional details in this blog post .
The former is used when evaluating the scope for a specific cross-reference and here ContextReference
corresponds to the name of this reference (prefixed with the name of the reference’s declaring type and
separated by an underscore). The ref parameter represents this cross-reference.
The latter method signature is used when computing the scope for a given element type and is applicable
to all cross-references of that type. Here TypeToReturn is the name of that type.
So if you for example have a state machine with a Transition object owned by its source State and you
want to compute all reachable states (i.e. potential target states), the corresponding method could be
declared as follows (assuming the cross-reference is declared by the Transition type and is called target):
IScope scope_Transition_target(Transition this, EReference ref)
If such a method does not exist, the implementation will try to find one for the context object’s container.
Thus in the example this would match a method with the same name but State as the type of the first
parameter. It will keep on walking the containment hierarchy until a matching method is found. This
container delegation allows to reuse the same scope definition for elements in different places of the
containment hierarchy. Also it may make the method easier to implement as the elements comprising the
scope are quite often owned or referenced by a container of the context object. In the example the State
objects could for instance be owned by a containing StateMachine object.
Xtext 1.0 55
Runtime Concepts
If no method specific to the cross-reference in question was found for any of the objects in the containment
hierarchy, the implementation will start looking for methods matching the other signature. Again it will
first attempt to match the context object. Thus in the example the signature first matched would be:
IScope scope_State(Transition this, EReference ref)
If no such method exists, the implementation will again try to find a method matching the context object’s
container objects. In the case of the state machine example you might want to declare the scope with
available states at the state machine level:
IScope scope_State(StateMachine this, EReference ref)
This scope can now be used for any cross-references of type State for context objects owned by the state
machine.
5.6.3.1. IQualifiedNameProvider
The ImportedNamespaceAwareLocalScopeProvider makes use of the so called IQualifiedNameProvider
service. It computes qualified names for EObjects. The default implementation (
DefaultDeclarativeQualifiedNameProvider) uses a simple name look up and concatenates the result to
the qualified name of its parent object using a dot as separator.
It also allows to override the name computation declaratively. The following snippet shows how you
could make Transitions in the state machine example referable by giving them a name. Don’t forget to
bind your implementation in your runtime module.
FowlerDslQualifiedNameProvider
extends DefaultDeclarativeQualifiedNameProvider {
public String qualifiedName(Transition t) {
if(t.getEvent() == null || !(t.eContainer() instanceof State))
return null;
else
return ((State)t.eContainer()).getName() + "." t.getEvent().getName();
}
}
package bar {
entity Foo {}
}
Xtext 1.0 56
Runtime Concepts
Of course the declared elements within a package are as well referable by their simple name:
package bar {
entity Bar extends Foo {}
entity Foo {}
}
5.8. Serialization
Serialization is the process of transforming an EMF model into its textual representation. Thereby,
serialization complements parsing and lexing.
In Xtext, the process of serialization is split into the following steps:
1. Validating the semantic model. This is optional, enabled by default, done by the concrete syntax
validator and can be turned off in the save options.
2. Matching the model elements with the grammar rules and creating a stream of tokens. This is done
by the parse tree constructor.
Xtext 1.0 57
Runtime Concepts
3. Associating comments with semantic objects. This is done by the comment associator.
4. Associating existing nodes from the node model with tokens from the token stream.
5. Merging existing whitespace and line-wraps into to token stream.
6. Adding further needed whitespace or replacing all whitespace using a formatter.
Serialization is invoked when calling XtextResource.save(...). Furthermore, Serializer provides resource-
independent support for serialization. Serialization is not called when a textual editors contents is saved
to disk. Another situation that triggers serialization is applying Quick Fixes with semantic modifications.
MyRule in this example reads ID- and INT-elements which may occur in an arbitrary order in the textual
representation. However, when serializing the model all ID-elements will be written first and then all
INT-elements. If the order is important it can be preserved by storing all elements in the same list – which
may require wrapping the ID- and INT-elements into objects.
5.8.2. Roles of the Semantic Model and the Node Model During
Serialization
A serialized document represents the state of the semantic model. However, if there is a node model
available (i.e. the semantic model has been created by the parser), the serializer
• preserves existing whitespaces from the node model.
• preserves existing comments from the node model.
• preserves the representation of cross-references: If a cross-referenced object can be identified by
multiple names (i.e. scoping returns multiple EObjectDescriptions for the same object), the serializer
tries to keep the previously used name.
• preserves the representation of values: For values handled by the value converter, the serializer checks
whether the textual representation converted to a value equals the value from the semantic model. If
that is true, the textual representation is kept.
Xtext 1.0 58
Runtime Concepts
• An assignment in the grammar has no corresponding model element. The default transient value service
considers a model element to be transient if it is unset or equals its default value. However, the parse
tree constructor may serialize default values if this is required by a grammar constraint to be able to
serialize another model element. The following solution may help to solve such a scenario:
• A model element should be added to the model.
• The assignment in the grammar should be made optional.
• The type of the model element differs from the type in the grammar. The type of the model element
must be identical to the return type of the grammar rule or the action’s type. Sub-types are not allowed.
• Value conversion fails. The value converter can indicate that a value is not serializeable by throwing
a ValueConverterException.
• An enum literal is not allowed at this position. This can happen if the referenced enum rule only lists
a subset of the literals of the actual enumeration.
To understand error messages and performance issues of the parse tree constructor it is important to know
that it implements a backtracking algorithm. This basically means that the grammar is used to specify the
structure of a tree in which one path (from the root node to a leaf node) is a valid serialization of a specific
model. The parse tree constructor’s task is to find this path – with the condition, that all model elements
are consumed while walking this path. The parse tree constructor’s strategy is to take the most promising
branch first (the one that would consume the most model elements). If the branch leads to a dead end
(for example, if a model element needs to be consumed that is not present in the model), the parse tree
constructor goes back the path until a different branch can be taken. This behavior has two consequences:
• In case of an error, the parse tree constructor has found only dead ends but no leaf. It cannot tell which
dead end is actually erroneous. Therefore, the error message lists dead ends of the longest paths, a
fragment of their serialization and the reason why the path could not be continued at this point. The
developer has to judge on his own which reason is the actual error.
• For reasons of performance, it is critical that the parse tree constructor takes the most promising branch
first and detects wrong branches early. One way to achieve this is to avoid having many rules which
return the same type and which are called from within the same alternative in the grammar.
5.8.4. Options
SaveOptions can be passed to XtextResource.save(options) and to Serializer.serialize(..). Available
options are:
• Formatting. Default: false. If enabled, it is the formatters job to determine all whitespace information
during serialization. If disabled, the formatter only defines whitespace information for the places in
which no whitespace information can be preserved from the node model. E.g. When new model
elements are inserted or there is no node model.
• Validating. Default: true: Run the concrete syntax validator before serializing the model.
Xtext 1.0 59
Runtime Concepts
terminal Plural:
'item' | 'items';
Valid models for this example are contents 1 item or contents 5 items. However, it is not stored
in the semantic model whether the keyword item or items has been parsed. This is due to the
fact that the rule call Plural is unassigned. However, the parse tree constructor needs to decide
which value to write during serialization. This decision can be be made by customizing the
IValueSerializer.serializeUnassignedValue(EObject, RuleCall, AbstractNode).
Xtext 1.0 60
Runtime Concepts
@Override
protected void configureFormatting(FormattingConfig c) {
ExampleLanguageGrammarAccess f = getGrammarAccess();
c.setAutoLinewrap(120);
The formatter has to implement the method configureFormatting(...) which declaratively sets up a
FormattingConfig.
The FormattingConfig consist of general settings and a set of formatting instructions:
Xtext 1.0 61
Runtime Concepts
To understand when an instruction is applied think of a stream of tokens whereas each token is associated
with the corresponding grammar element. The instructions are matched against these grammar elements.
The following matching criteria exist:
• after(ele): The instruction is applied after the grammar element ele has been matched. For example, if
your grammar uses the keyword “;” to end lines, this can instruct the formatter to insert a line break
after the semicolon.
• before(ele): The instruction is executed before the matched element. For example, if your grammar
contains lists which separate their values with the keyword “,”, you can instruct the formatter to
suppress the whitespace before the comma.
• around(ele): This is the same as before(ele) combined with after(ele).
• between(ele1, ele2): This matches if ele2 directly follows ele1 in the document. There may be no other
tokens in between ele1 and ele2.
• bounds(ele1, ele2): This is the same as after(ele1) combined with before(ele2).
• range(ele1, ele2): The rule is enabled when ele1 is matched, and disabled when ele2 is matched.
Thereby, the rule is active for the complete region which is surrounded by ele1 and ele2.
The term tokens is used slightly different here compared to the parser/lexer. Here, a token is a keyword
or the string that is matched by a terminal rule, data type rule or cross-reference. In the terminology of
the lexer a data type rule can match a composition of multiple tokens.
The parameter ele can be a grammar’s AbstractElement or a grammar’s AbstractRule. All grammar
rules and almost all abstract elements can be matched. This includes rule calls, parser rules, groups and
alternatives. The semantic of before(ele), after(ele), etc. for rule calls and parser rules is identical to when
the parser would “pass” this part of the grammar. The stack of called rules is taken into account. The
following abstract elements can not have assigned formatting instructions:
• Actions. E.g. {MyAction} or {MyAction.myFeature=current}.
• Grammar elements nested in data type rules. This is due to to the fact that tokens matched by a data type
rule are treated as atomic by the serializer. To format these tokens, please implement a ValueConverter.
• Grammar elements nested in CrossReferences.
After having explained how rules can be activated, this is what they can do:
• setIndentationIncrement() increments indentation by one unit at this position. Whether one
unit consists of one tab-character or spaces is defined by IIndentationInformation. The default
implementation consults Eclipse’s PreferenceStore.
• setIndentationDecrement() decrements indentation by one unit.
• setLinewrap(): Inserts a line-wrap at this position.
• setLinewrap(int count): Inserts count numbers of line-wrap at this position.
• setLinewrap(int min, int default, int max): If the amount of line-wraps that have been at this position
before formatting can be determined (i.g. when a node model is present), then the amount of of line-
wraps is adjusted to be within the interval [ min, max] and is then reused. In all other cases default line-
wraps are inserted. Example: setLinewrap(0, 0, 1) will preserve existing line-wraps, but won’t allow
more than one line-wrap between two tokens.
• setNoLinewrap(): Suppresses automatic line wrap, which may occur when the line’s length exceeds
the defined limit.
• setSpace(String space): Inserts the string space at this position. If you use this to insert something else
than whitespace, tabs or newlines, a small puppy will die somewhere in this world.
• setNoSpace(): Suppresses the whitespace between tokens at this position. Be aware that between some
tokens a whitespace is required to maintain a valid concrete syntax.
Xtext 1.0 62
Runtime Concepts
• findKeywords(String... keywords) returns all keywords that equal one of the parameters.
• findKeywordPairs(String leftKw, String rightKw): returns tuples of keywords from the same grammar
rule. Pairs are matched nested and sequentially. Example: for Rule: ‘(’ name=ID (‘(’ foo=ID ‘)’) ‘)’ |
‘(’ bar=ID ')' findKeywordPairs(“(”, “)”) returns three pairs.
@Inject
private IQualifiedNameProvider qualifiedNameProvider;
For performance reasons it is usually a good idea to navigate the resource based on the fragment
information instead of traversing it completely. If you know that your fragment is computed from
qualified names and your model contains something like NamedElements, you should split your fragment
into those parts and query the root elements, the children of the best match and so on.
Xtext 1.0 63
Runtime Concepts
Furthermore it’s a good idea to have some kind of conflict resolution strategy to be able to distinguish
between equally named elements that actually are different, e.g. properties may have the very same
qualified name as entities.
Xtext 1.0 64
Runtime Concepts
@Override
public void configureRuntimeEncodingProvider(Binder binder) {
binder.bind(IEncodingProvider.class)
.annotatedWith(DispatchingProvider.Runtime.class)
.to(MyEncodingProvider.class);
}
For the uniform encoding, bind the plain IEncodingProvider to the same implementation in both modules:
@Override
public Class<? extends IEncodingProvider> bindIEncodingProvider() {
return MyEncodingProvider.class;
}
Xtext 1.0 65
Chapter 6. MWE2
The Modeling Workflow Engine 2 (MWE2) is a rewritten backwards compatible implementation of
the Modeling Workflow Engine (MWE). It is a declarative, externally configurable generator engine.
Users can describe arbitrary object compositions by means of a simple, concise syntax that allows to
declare object instances, attribute values and references. One use case – that’s where the name had its
origins – is the definition of workflows. Such a workflow consists usually of a number of components
that interact with each other. There are components to read EMF resources, to perform operations
(transformations) on them and to write them back or to generate any number of other artifacts out of the
information. Workflows are typically executed in a single JVM. However there are no constraints the
prevent implementors to provide components that spawn multiple threads or new processes.
6.1. Examples
Let’s start with a couple of examples to demonstrate some usage scenarios for MWE2. The first examples
is a simple HelloWorld module that does nothing but print a message to standard out. The second module
is assembled of three components that read an Ecore file, transform the contained classifier-names to
upper-case and serialize the resource back to a new file. The last examples uses the life-cycle methods
to print the execution time of the workflow.
SayHello {
message = "Hello World!"
}
It configures a very simple workflow component with a message that should be printed to System.out
when the workflow is executed. The module begins with a declaration of its name. It must fulfill the Java
conventions for fully qualified class-names. That’s why the module HelloWorld has to be placed into the
default package of a Java source folder. The second element in the module is the class-name SayHello
which introduces the root element of the module. The interpreter will create an instance of the given type
and configure it as declared between the curly braces. E.g. the assignment message = "Hello World!" in
the module will be interpreted as an invocation of the setMessage(String) on the instantiated object. As
one can easily imagine, the implementation of the class SayHello looks straight forward:
import org.eclipse.emf.mwe2.runtime.workflow.IWorkflowComponent;
import org.eclipse.emf.mwe2.runtime.workflow.IWorkflowContext;
Xtext 1.0 66
MWE2
module HelloWorld
Workflow {
component = SayHello {
message = "Hello World!"
}
}
The class Workflow is actually org.eclipse.emf.mwe2.runtime.workflow.Workflow but its package is
implicitly imported in MWE2 modules to make the the modules more concise. The execution result of
this workflow will be revealed after a quick Run As .. -> MWE2 Workflow in the console as
Hello World!
Xtext 1.0 67
MWE2
Xtext 1.0 68
MWE2
Each of the mentioned implementations is rather simple and can be done in a couple of minutes. This
is true for many tedious tasks that developers face in their daily work. MWE2 can be used to automize
these tasks with minimum effort.
6.1.3. A Stopwatch
The last example demonstrates how to combine the MWE2 concepts to create a simple stopwatch that
allows to measure the execution time of a set of components. The idea is to add the very same stopwatch
twice as a component to a workflow. It will measure the time from the first pre-invoke to the last post-
invoke event and print the elapsed milliseconds to the console.
public class StopWatch implements IWorkflowComponent {
private long start;
private boolean shouldStop = false;
public void invoke(IWorkflowContext ctx) {}
Workflow {
component = StopWatch: stopWatch {}
component = @OtherWorkflow {}
component = stopWatch
}
import java.util.*
SampleClass {
singleValue = 'a string'
multiValue = ArrayList {}
child = {}
}
Xtext 1.0 69
MWE2
package com.mycompany;
import java.util.List;
6.2.2. Module
As MWE2 modules have a fully qualified name, it is possible to refer to them from other modules. The
type of the module is derived from the type of its root component. The com.mycompany.Example can be
assigned at any place where a com.mycompany.SampleClass is expected.
Let’s create a second module com.mycompany.Second like this:
module com.mycompany.sub.Second
import com.mycompany.*
SampleClass {
child = @Example {}
}
The child value will be assigned to an instance of SampleClass that is configured as in the first example
workflow. This enables nice composition and a very focused, reusable component design.
As the same rules apply in MWE2 like in Java, the module com.mycompany.sub.Second has to be defined
in a file called Second.mwe2 in the package com.mycompany.sub. The import semantic for other modules
is the same as for classes. The import statement allows to refer to com.mycompany.Example with a
shortened name.
6.2.3. Properties
MWE2 allows to extract arbitrary information into properties to ensure that these pieces are not cluttered
around the workflow and to allow for easier external customization. The exemplary component definition
was only changed slightly by introducing a property value.
Xtext 1.0 70
MWE2
module com.mycompany.Example
SampleClass {
singleValue = value
}
The type of the property will be derived from the default value similar to the mechanism that is already
known from set- and add-methods. If no default value is given, java.lang.String will be assumed.
However, properties are not limited to strings. The second built in type is boolean via the familiar literals
true and false. More flexibility is available via actual component literals.
module com.mycompany.Example
SampleClass {
child = childInstance
}
If one wants to define string properties that are actual reusable parts for other properties, she may use
defined variables inside other literals like this:
var aString = "part"
var anotherString = "reuse the ${part} here"
This is especially useful for file paths in workflows as one would usually want to define some common
root directories only ones in the workflow and reuse this fragment across certain other file locations.
SampleClass {
singleValue = optional
child = {
singleValue = mandatory
}
}
This version of the example module exposes two externally assignable properties. The second one has no
default value assigned and is thereby considered to be mandatory. The mandatory value must be assigned
if we reuse org.mycompany.Example in another module like this:
module com.mycompany.Second
var newMandatory
@Example {
mandatory = "mandatoryValue"
optional = newMandatory
}
Note that it is even possible to reuse another module as the root component of a new module. In this
case we set the mandatory property of Example to a specific constant value while the previously optional
value is now redefined as mandatory by means of a new property without a default value.
It is not only possible to define mandatory properties for MWE2 modules but for classes as well. Therefore
MWE2 ships with the @Mandatory annotation. If a set- or add-method is marked as mandatory, the
module validation will fail if no value was assigned to that feature.
Xtext 1.0 71
MWE2
SampleClass : self {
child = self
}
A named component can be referenced immediately after its creation but it is not possible to define
forward references in a MWE2 file.
SampleClass auto-inject {
}
This example will implicitly assign the value of the property child to the feature child of the root
component. This is especially useful for highly configurable workflows that expose dozens of optional
parameters each of which can be assigned to one or more components.
The auto-inject modifier can be used for a subset of the available features as well. It will suppressed for
the explicitly set values of a component.
6.3.1. Module
Xtext 1.0 72
MWE2
A module consists of four parts. The very first statement in a *.mwe2 file is the module declaration. The
name of the module must follow the naming convention for Java classes. That MWE2 file’s name must
therefore be the same as the last segment of the module-name and it has to be placed in the appropriate
package of a Java source path.
It is allowed to define any number of import statements in a module. Imports are either suffixed by a
wild-card or concrete for a class or module. MWE2 can handle relative imports in case one uses the wild-
card notation:
'import' name '.*'?
6.3.2. Property
The list of declared properties follows the optional import section. It is allowed to define modules without
any properties.
Each declared property is locally visible in the module. It furthermore defines an assignable feature of
the module in case one refers to it from another module. Properties may either have a default value or
they are considered to be mandatory. If the type of property is omitted it will be inferred from the default
value. The default type of a property is java.lang.String so if no default value is available, the property
is mandatory and of type String.
There are four types of values available in MWE2. One may either define a string, boolean or component
literal or a reference to a previously defined property.
6.3.3. Component
The last part of a module is the root component. It defines the externally visible type of the module and
may either be created from a Java type or from another module.
The type of the component can be derived in many cases except for the root component. That’s why
it’s optional in the component literal. If no type is given, it will be inferred from the left side of the
assignment. The assigned feature can either be a declared property of the module or a set- or add-method
of a Java class.
Components can be named to make them referable in subsequent assignments. Following the ':' keyword,
one can define an identifier for the instantiated component. The identifier is locally visible in the module
and any assignment that is defined after the named component can refer to this identifier and thereby
point to exactly the instantiated object.
The next option for a component is auto-inject. If this modifier is set on a component, any available
feature of the component that has the same name as a property or previously created named component
will be automatically assigned.
The core of a component is the list of assignments between the curly braces. An arbitrary number of
values can be set on the component by means of feature-to-value pairs.
Xtext 1.0 73
MWE2
The available constructs on the right hand side of the assignment are the same as for default values for
properties.
6.3.6. References
Each assigned value in MWE2 either as default for properties or in a component assignment can be a
reference to a previously declared property or named component. The can be referenced intuitively by
their name.
Xtext 1.0 74
Chapter 7. IDE Concepts
For the following part we will refer to a concrete example grammar in order to explain certain aspect of
the UI more clearly. The used example grammar is as follows:
grammar org.eclipse.text.documentation.Sample
with org.eclipse.xtext.common.Terminals
Model :
"model" intAttribute=INT (stringDescription=STRING)? "{"
(rules += AbstractRule)*
"}"
;
AbstractRule:
RuleA | RuleB
;
RuleA :
"RuleA" "(" name = ID ")" ;
Xtext 1.0 75
IDE Concepts
@Override
public void configureContentProposalLabelProvider(Binder binder) {
binder.bind(ILabelProvider.class)
.annotatedWith(ContentProposalLabelProvider.class)
.to(MyContentAssistLabelProvider.class);
}
If your grammar uses an imported EPackage, there may be an existing .edit plug-in generated by EMF
that also provides label providers for model elements. To use this as a fallback, your label provider should
call the constructor with the delegate parameter and use DI for the initialization, e.g.
public class MyLabelProvider {
@Inject
public MyLabelProvider(AdapterFactoryLabelProvider delegate) {
super(delegate);
}
...
}
7.1.1.1. DefaultEObjectLabelProvider
The default implementation of the LabelProvider interface utilizes the polymorphic dispatcher idiom
to implement an external visitor as the requirements of the LabelProvider are kind of a best match
for this pattern. It comes down to the fact that the only thing you need to do is to implement a
method that matches a specific signature. It either provides a image filename or the text to be used to
represent your model element. Have a look at following example to get a more detailed idea about the
DefaultEObjectLabelProvider.
public class SampleLabelProvider extends DefaultLabelProvider {
What is especially nice about the default implementation is the actual reason for its class name: It provides
very reasonable defaults. To compute the label for a certain model element, it will at first have a look
for an EAttribute name and try to use this one. If it cannot find such a feature, it will try to use the first
feature, that can be used best as a label. At worst it will return the class name of the model element, which
is kind of unlikely to happen.
You can a also customize error handling by overriding the methods handleTextError() or
handleImageError().
Xtext 1.0 76
IDE Concepts
7.2.1. ProposalProvider
public void complete[TypeName]_[FeatureName](
EObject model,
Assignment assignment,
ContentAssistContext context,
ICompletionProposalAcceptor acceptor) {
// clients may override
}
The snippet above indicates that the generated ProposalProvider class contains a complete*-method for
each assigned feature in the grammar and for each rule. The brackets are place-holders that should give a
clue about the naming scheme used to create the various entry points for clients. The generated proposal
provider falls back to some default behavior for cross-references and keywords. Furthermore it inherits
the logic that was introduced in reused grammars.
Clients who want to customize the behavior may override the methods from the
AbstractProposalProvider or introduce new methods with a specialized first parameter. The framework
dispatches method calls according to the current context to the most concrete implementation, that can
be found.
It is important to know, that for a given offset in a model file, many possible grammar elements exist.
The framework dispatches to the method declarations for any valid element. That means, that a bunch
of complete* methods may be called.
Xtext 1.0 77
IDE Concepts
Now that the validation has a unique code identifying the problem we can register quick fixes for it.
We start by adding the QuickfixProviderFragment to our workflow and after regenerating the code we
should find an empty class MyDslQuickfixProvider in our DSL’s UI project and new entries in the
_==plugin.xml_gen==_ file.
Continuing with the _==INVALID_TYPE_NAME==_ problem from the Domainmodel example we add
a method with which the problem can be fixed (have a look at the DomainmodelQuickfixProvider for
details):
Xtext 1.0 78
IDE Concepts
@Fix(DomainmodelJavaValidator.INVALID_TYPE_NAME)
public void fixName(final Issue issue, IssueResolutionAcceptor acceptor) {
acceptor.accept(issue,
"Capitalize name", // quick fix label
"Capitalize name of '" + issue.getData()[0] + "'", // description
"upcase.png", // quick fix icon
new IModification() {
public void apply(IModificationContext context)
throws BadLocationException {
IXtextDocument xtextDocument = context.getXtextDocument();
String firstLetter = xtextDocument.get(issue.getOffset(), 1);
xtextDocument.replace(issue.getOffset(), 1,
Strings.toFirstUpper(firstLetter));
}
}
);
}
By using the correct signature (see below) and annotating the method with the @Fix annotation
referencing the previously specified issue code from the validator, Xtext knows that this method
implements a fix for the problem. This also allows us to annotate multiple methods as fixes for the same
problem.
The first three parameters given to the IssueResolutionAcceptor define the UI representation of the
quick fix. As the document is not necessarily loaded when the quick fix is offered, we need to provide
any additional data from the model that we want to refer to in the UI when creating the issue in the
validator above. In this case, we provided the existing type name. The additional data is available as
Issue.getData(). As it is persisted in markers, only strings are allowed.
The actual model modification is implemented in the IModification. The IModificationContext provides
access to the erroneous document. In this case, we’re using Eclipse’s IDocument API to replace a text
region.
If you prefer to implement the quick fix in terms of the semantic model use a ISemanticModification
instead. Its apply(EObject, IModificationContext) method will be invoked inside a modify-transaction
and the first argument will be the erroneous semantic element. This makes it very easy for the fix method
to modify the model as necessary. After the method returns the model as well as the Xtext editor’s content
will be updated accordingly. If the method fails (throws an exception) the change will not be committed.
The following snippet shows a semantic quick fix for a similar problem.
@Fix(DomainmodelJavaValidator.INVALID_FEATURE_NAME)
public void fixFeatureName(final Issue issue,
IssueResolutionAcceptor acceptor) {
acceptor.accept(issue,
"Uncapitalize name", // label
"Uncapitalize name of '" + issue.getData()[0] + "'", // description
"upcase.png", // icon
new ISemanticModification() {
public void apply(EObject element, IModificationContext context) {
((Feature) element).setName(
Strings.toFirstLower(issue.getData()[0]));
}
}
);
}
Xtext 1.0 79
IDE Concepts
By default Xtext registers ContextTypes for each rule ( .[RuleName]) and for each
keyword ( .kw[keyword]_). If you don’t like these defaults you’ll have to subclass
XtextTemplateContextTypeRegistry and configure it via Guice.
In addition to the standard template proposal extension mechanism, Xtext ships with
a predefined set of TemplateVariableResolvers to resolve special variable types inside a
given template (i.e. TemplateContext). Besides the standard template variables available in
org.eclipse.jface.text.templates.GlobalTemplateVariables like ${user}, ${date}, ${time}, ${cursor},
etc., these TemplateVariableResolver support the automatic resolving of CrossReferences (type
CrossReferences) and Enumerations (type Enum) like it is explained in the following sections.
It is best practice to edit the templates in the preferences page, export them into the templates.xml-file
and put this one into the templates folder of your UI-plug-in. However, these templates will not be visible
by default. To fix it, you have to manually edit the xml-file and insert an ID attribute for each template
element.
Xtext 1.0 80
IDE Concepts
yields the text event => state and allows selecting any events and states using a drop down.
yields the text public op name(): type where the display text ‘public’ is replaced with a drop down filled
with the literal values as defined in the EEnum Visibility. Also, name and type are template variables.
Xtext 1.0 81
IDE Concepts
You can customize various aspects of the outline by providing implementation for its various interfaces.
The following sections show how to do this.
Xtext 1.0 82
IDE Concepts
/**
* This method will be called by naming convention:
* - method name must be getChildren
* - first param: subclass of EObject
*/
public List<EObject> getChildren(Attribute attribute) {
return attribute.eContents();
}
To make sure Xtext picks up your new outline transformer, you have to register your implementation
with your UI module. This binding is usually added by the respective generator fragment.
public class MyDslUiModule extends AbstractMyDslUiModule {
@Override
public Class<? extends ISemanticModelTransformer>
bindISemanticModelTransformer() {
return MyDslTransformer.class;
}
...
}
7.5.2. Filtering
Often, you want to allow users to filter the contents of the outline to make it easier to concentrate
on the relevant aspects of the model. To add filtering capabilities to your outline, you need to add
AbstractFilterActions to the outline. Actions can be contributed by implementing and registering a
DeclarativeActionBarContributor.
To register a DeclarativeActionBarContributor, add the following lines to your MyDslUiModule class:
Xtext 1.0 83
IDE Concepts
@Override
public Class<? extends IActionBarContributor> bindIActionBarContributor() {
return MyDslActionBarContributor.class;
}
...
}
Filter actions must extend AbstractFilterAction (this ensures that the action toggle state is handled
correctly):
public class FilterFooAction extends AbstractFilterAction {
@Override
protected String getToggleId() {
return "FilterFooAction.isChecked";
}
@Override
protected ViewerFilter createFilter() {
return new FooOutlineFilter();
}
@Override
public boolean select(
Viewer viewer, Object parentElement, Object element) {
if ((parentElement != null)
&& (parentElement instanceof ContentOutlineNode)) {
ContentOutlineNode parentNode = (ContentOutlineNode) parentElement;
EClass clazz = parentNode.getClazz();
if (clazz.equals(MyDslPackage.Literals.ATTRIBUTE)) {
return false;
}
}
return true;
}
Xtext 1.0 84
IDE Concepts
If you want to bind context menu actions to nodes representing Attribute and Entity, you need to change
the declaration of _types as follows:
private static final Class<?>[] types = { Attribute.class, Entity.class };
Next, you need to define a handler which will eventually execute the code to operate on the selected node.
Please pay special attention to the attribute commandId - it must match the id attribute of your command.
<extension
point="org.eclipse.ui.handlers">
<handler
class="org.example.mydsl.ui.editor.outline.SampleOutlineNodeHandler"
commandId="org.example.mydsl.ui.editor.outline.SampleOutlineCommand">
</handler>
</extension>
Xtext 1.0 85
IDE Concepts
<extension
point="org.eclipse.ui.menus">
<menuContribution
locationURI="popup:org.eclipse.xtext.ui.outline?after=additions">
<command
commandId="org.example.mydsl.ui.editor.outline.SampleOutlineCommand"
label="Sample action registered for Attributes">
<visibleWhen checkEnabled="false">
<iterate>
<adapt type="org.example.mydsl.Attribute" />
</iterate>
</visibleWhen>
</command>
</menuContribution>
</extension>
Again, pay attention to the commandId attribute. The connection between your node type(s) and the menu
contribution is made by the part
<adapt></adapt>
.
7.6. Hyperlinking
The Xtext editor provides hyperlinking support for any tokens corresponding to cross-references in your
grammar definition. You can either CTRL-click on any of these tokens or hit F3 while the cursor position
is at the token in question and this will take you to the referenced model element. As you’d expect this
works for references to elements in the same resource as well as for references to elements in other
resources. In the latter case the referenced resource will first be opened using the corresponding editor.
@Override
public Class<? extends ILocationInFileProvider>
bindILocationInFileProvider() {
return MyDslLocationInFileProvider.class;
}
...
}
Xtext 1.0 86
IDE Concepts
Often the default strategy only needs some guidance (e.g. selecting the text corresponding to another
feature than name). In that case you can simply subclass DefaultLocationInFileProvider and override the
methods getIdentifierFeature() and / or useKeyword() to guide the first and last steps of the strategy as
described above (see XtextLocationInFileProvider for an example).
The highlighting is done in two stages. This allows for sophisticated algorithms that are executed
asynchronously to provide advanced coloring while simple pattern matching may be used to highlight
parts of the text instantaneously. The latter is called lexical highlighting while the first is based on the
meaning of your different model elements and therefore called semantic highlighting.
When you introduce new highlighting styles, the preference page for your DSL is automatically
configured and allows the customization of any registered highlighting setting. They are automatically
persisted and reloaded on startup.
Xtext 1.0 87
IDE Concepts
The IHighlightingConfiguration is used to register any default style without a specific binding to a pattern
in the model file. It is used to populate the preferences page and to initialize the ITextAttributeProvider,
which in turn is the component that is used to obtain the actual settings for a style’s id. An implementation
will usually be very similar to the DefaultHighlightingConfiguration and read like this:
public class DefaultHighlightingConfiguration
implements IHighlightingConfiguration {
// ...
}
Implementations of the ITokenScanner are responsible for splitting the content of a document into various
parts, the so called tokens, and return the highlighting information for each identified range. It is critical
that this is done very fast because this component is used on each keystroke. Xtext ships with a default
implementation that is based on the lexer that is generated by ANTLR which is very lightweight and
fast. This default implementation can be customized by clients easily. They simply have to bind another
implementation of the AbstractAntlrTokenToAttributeIdMapper. To get an idea about it, have a look at
the DefaultAntlrTokenToAttributeIdMapper.
Xtext 1.0 88
IDE Concepts
This example refers to an implementation of the IHighlightingConfiguration that registers a style for a
cross-reference. It is pretty much the same implementation as for the previously mentioned sample of a
lexical IHighlightingConfiguration.
public class HighlightingConfiguration
implements IHighlightingConfiguration {
Xtext 1.0 89
IDE Concepts
import org.eclipse.xtext.ui.generator.*
Here
• the generatorProjectName is used to specify the project that contains the workflows and templates
used to generate artifacts from your DSL. The generated project wizard uses this to add a corresponding
dependency to the created project.
• and the modelFileExtension specifies the default file extension associated with your DSL. When the
user clicks the Finish button the project wizard will look for a file with the given extension in the
created project and open a editor.
After running the Xtext generator, the DSL’s UI project will contain a new Xpand template
MyDslNewProject.xpt in the src folder in the package .ui.wizard. Note: It may be necessary to manually
merge the new entry in the _plugin.xml___gen_ into your plugin.xml of the UI project to enable the
wizard contribution.
The generated Xpand template will be expanded by the project wizard when the user clicks the Finish
button and it is responsible for initializing the project with some sample content. When finishing the
wizard the template will be used to create a sample model file and a simple workflow to run the model
through the generator project’s MyDslGenerator.mwe workflow. However, this is only a pragmatic
default. As the Xpand template is in the src source folder you may of course modify it to generate whatever
initial content you want for a new project. Just make sure to leave the top-level main definition in place,
as that is the interface for the project wizard.
Note: To edit the generated Xpand template you should check that the JavaBeans meta model contributor
is enabled under Preferences > Xtend/Xpand. Further you should also configure the UI project with the
Xpand/Xtend nature using Configure > Add Xpand/Xtend Nature in the context menu.
Xtext 1.0 90
Chapter 8. Referring to Java Types
A common use case when developing languages is the requirement to refer to existing concepts of other
languages. Xtext makes this very easy for other self defined languages. However, it is often very useful
to have access to the available types of the Java Virtual Machine. The JVM types Ecore model enables
clients to do exactly this. It is possible to create cross-references to classes, interfaces, and their fields and
methods. Basically every information about the structural concepts of the Java type system is available
via the JVM types. This includes annotations and their specific values and enumeration literals as well.
The implementation will be selected transparently to the client code depending on where the code is
executed. If the environment is a plain stand-alone Java or OSGi environment, the java.lang.reflect API
will be used to deduce the necessary data. On the contrary, the type-model will be created from the live
data of the JDT in an interactive Eclipse environment. All this happens behind the scenes via different
implementations that are bound to specific interfaces with Google Guice.
The next step is to actually refer to an imported concept. Let’s define a mapping to actually available
Java types for the simple data types in the self defined language. By means of cross-references this works
as one got already used to when dealing with references in Xtext.
Type:
'type' name=ID 'mapped-to' javaType=[types::JvmType|FQN];
Last but not least, the TypesGeneratorFragment has to be added to the workflow. The safest way is to
add it after the actually used scoping fragments as a specialized version of the IGlobalScopeProvider
will be configured. Don’t forget to refer to the genmodel of the Java VM types. The shortest possible
URI is a classpath-URI.
fragment = ecore.EcoreGeneratorFragment {
referencedGenModels="classpath:/model/JavaVMTypes.genmodel"
}
...
// scoping and exporting API
...
fragment = types.TypesGeneratorFragment {}
After regenerating your language, it will be allowed to define a type Date that maps to the java.util.Date
like this:
type Date mapped-to java.util.Date
These two steps will provide a nice integration into the Eclipse JDT. There is Find References on Java
methods, fields and types that will reveal results in your language files. Go To Declaration works as
expected and content assist will propose the list of available types.
Xtext 1.0 91
Referring to Java Types
The ITypesProposalProvider can be used to provide optimized proposals based on various filter criteria.
The most common selector can be used directly via createSubTypeProposals. The implementation is
optimized and uses the JDT Index directly to minimize the effort for object instantiation. The class
TypeMatchFilters provides a comprehensive set of reusable filters that can be easily combined to reduce
the list of proposals to a smaller number of valid entries.
import static org.eclipse.xtext.common.types.xtext.ui.TypeMatchFilters.*;
..
..
proposalProvider.createSubTypeProposals(factory, context,
and(not(canInstantiate()), isPublic()), acceptor);
Xtext 1.0 92
Chapter 9. Typical Language
Configurations
9.1. Case Insensitive Languages
In some cases, e.g. if your SHIFT key is broken, you might want to design a case insensitive language.
Xtext offers separate generator fragments for this purpose.
For case insensitive keywords, open your MWE workflow and replace the Antlr related fragments:
// The antlr parser generator fragment.
fragment = parser.antlr.XtextAntlrGeneratorFragment {
// options = {
// backtrack = true
// }
}
...
with
// The antlr parser generator fragment.
fragment = parser.antlr.ex.rt.AntlrGeneratorFragment {
options = {
ignoreCase = true
}
}
...
For case insensitve element names, use the ignoreCase option in your scope fragment, i.e.
fragment = scoping.ImportNamespacesScopingFragment {
ignoreCase = true
}
Xtext 1.0 93
Typical Language Configurations
@Override
public Class<? extends IResourceForEditorInputFactory>
bindIResourceForEditorInputFactory() {
return ResourceForIEditorInputFactory.class;
}
@Override
public Class<? extends IResourceSetProvider> bindIResourceSetProvider() {
return SimpleResourceSetProvider.class;
}
Second, configure the global scope provider to scan project root folders instead of the classpath of Java
projects.
@Override
public com.google.inject.Provider
<org.eclipse.xtext.resource.containers.IAllContainersState>
provideIAllContainersState() {
return org.eclipse.xtext.ui.shared.Access.getWorkspaceProjectsState();
}
The remaining steps show you how to adapt the project wizard for your language, if you have generated
one. The best way to do this is to create a new subclass of the generated IProjectCreator in the src/ folder
of the ui project and apply the necessary changes there. First, remove the JDT project configuration by
overriding configureProject with an empty body.
The next thing is to redefine the project natures and builders that should be applied to you language
projects.
In in this case just remove the JDT stuff in this way:
protected String[] getProjectNatures() {
return new String[] {
"org.eclipse.pde.PluginNature",
"org.eclipse.xtext.ui.shared.xtextNature"
};
}
That’s all. Your language and its IDE should now no longer depend on JDT.
Xtext 1.0 94
Typical Language Configurations
If you know EBNF a bit and wouldn’t think about avoiding left recursion, operator precedence or
associativity, you’ld probably write a grammar like this:
Expression :
Expression '+' Expression |
Expression '*' Expression |
INT;
This grammar would be left recursive because the parser reads the grammar top down and left to right and
would endlessly call the Expression rule without consuming any characters, i.e. altering the underlying
state of the parser. While this kind of grammar can be written for bottom-up parsers, you’ld still have
to deal with operator precedence in addition. That is define that a multiplication has higher precedence
than an addition for example.
In Xtext you define the precedence implicitly when left-factoring such a grammar. Left-factoring means
you get rid of left recursion by applying a certain technique, which we will show in the following.
So here is a left-factored grammar (not yet working with Xtext) for the expression language above :
Addition :
Multiplication ('+' Multiplication)*;
Multiplication:
NumberLiteral ('*' NumberLiteral)*;
NumberLiteral:
INT;
As you can see the main difference is that we have three rules instead of one and if you look a bit closer
you see, that there’s a certain delegation pattern involved. The rule Addition doesn’t call itself but calls
Multiplication instead. The operator precedence is defined by the order of delegation. The later the rule
is called the higher is its precedence. This is at least the case for the first two rules which are of a left
recursive nature (but we’ve left-factored them now). The last rule is not left recursive which is why you
can write them down without applying this pattern.
We should allow users to explicitly adjust precedence by adding parenthesis, e.g. write something like
(2 + 20) * 2. So let’s add support for that (note that the grammar is still not working with Xtext):
Addition :
Multiplication ('+' Multiplication)*;
Multiplication:
Primary ('*' Primary)*;
Primary :
NumberLiteral |
'(' Addition ')';
NumberLiteral:
INT;
So once again: if you have some construct that recurses on the left hand side, you need to put it into the
delegation chain according to their operator precedence. The pattern is always the same, the thing that
recurses delegates to the rule with the next higher precedence.
Xtext 1.0 95
Typical Language Configurations
The return type of a rule can be specified explicitly using the ‘returns’ keyword but can be inferred if the
type’s name is the same as the rule’s name. That is
NumberLiteral : ... ;
is a short form of
NumberLiteral returns NumberLiteral : ... ;
However in the case of the expressions grammar above, all rules need to return the same type since they
are recursive. So in order to make the grammar functional we need to add a common return type explicitly
(but the grammar is still missing some bits):
Addition returns Expression:
Multiplication ('+' Multiplication)*;
NumberLiteral:
INT;
The AST type inference mechanism of Xtext will infer two types: Expression and NumberLiteral. Now
we need to add assignments and Actions in order to store all the important information in the AST and
to create reasonable subtypes for the two operations.
In the following you see the final fully working Xtext grammar:
Addition returns Expression:
Multiplication ({Addition.left=current} '+' right=Multiplication)*;
NumberLiteral:
value=INT;
Let’s go through the grammar as the parser would do it for the expression
(1 + 20) * 2
The parser always starts with the first rule (Addition). Therein the first element is an unassigned rule call
to Multiplication which in turn calls Primary. Primary now has two alternatives. The first one is calling
NumberLiteral which consists only of one assignment to a feature called ‘value’. The type of ‘value’ has
to be compatible to the return type of the INT rule.
But as the first token in the sample expression is an opening parenthesis ‘(’ the parser will take the second
alternative in Primary, consume the ‘(’ and call the rule Addition. Now the value ‘1’ is the lookahead token
and again Addition calls Multiplication and Multiplication calls Primary. This time the parser takes the
first alternative because ‘1’ was consumed by the INT rule (which btw. is a reused library terminal rule).
As soon as the parser hits an assignment it checks whether an AST node for the current rule was already
created. If not it will create one based on the return type of the current rule, which is NumberLiteral. The
Xtext generator created an EClass ‘NumberLiteral’ before which can now be instantiated. That type will
also have a property called value of type int (actually of type EInt), which will get the value ‘1’ set. This
is what the Java equivalent would look like:
Xtext 1.0 96
Typical Language Configurations
// value=INT
if (current == null)
current = new NumberLiteral();
current.setValue(ruleINT());
...
Now that the rule has been completed the created EObject is returned to the calling rule Primary, which
in turn returns the object unchanged to its own caller. Within Multiplication the call to Primary has been
successfully parsed and returned an instance of NumberLiteral. The second part of the rule (everything
within the parenthesis) is a so called group. The asterisk behind the closing parenthesis states that this part
can be consumed zero or more times. The first token to consume in this part is the multiplication operator
‘*’. Unfortunately in the current situation the next token to accept is the plus operator ‘+’, so the group is
not consumed at all and the rule returns what they got from the unassigned rule call (the NumberLiteral).
In rule Addition there’s a similar group but this time it expects the correct operator so the parser steps into
the group. The first element in the group is a so called action. As Xtext grammars are highly declarative
and bi-directional it is not a good idea to allow arbitrary expression within actions as it is usually the
case with parser generators. Instead we only support two kinds of actions. This one will create a new
instance of type Addition and assign what was the to-be-returned object to the feature left. In Java this
would have been something like:
// Multiplication rule call
current = ruleMultiplication();
// {Addition.left=current}
Addition temp = new Addition();
temp.setLeft(current);
current = temp;
...
As a result the rule would now return an instance of Addition which has a NumberLiteral set to its
property left. Next up the parser consumes the ‘+’ operator. We do not store the operator in the AST
because we have an explicit Addition type, which implicitly contains this information. The assignment
(‘right=Multiplication’) calls the rule Multiplication another time and assigns the returned object (a
NumberLiteral of value=20) to the property named right.
If we now had an additional plus operation ‘+’ (e.g. 1 + 2 + 3) the group would match another time and
create another instance of Addition. But we don’t and therefore the rule is completed and returns the
created instance of Addition to its caller which was the second alternative in Primary. Now the closing
parenthesis is matched and consumed and the parser stack is reduced once more.
We are now in rule Multiplication and have the multiplication operator ‘*’ on the lookahead. The
parser goes into the group and applies the action. Finally it calls the Primary rule, gets another instance
of NumberLiteral (value=2), assigns it as the ‘right’ operand of the Multiplication and returns the
Multiplication to the rule Addition which in turn returns the very same object as there’s nothing left to
parse.
The resulting AST looks like this:
Xtext 1.0 97
Typical Language Configurations
(It’s pretty hard to follow what’s going on just by reading this text. Therefore we have prepared a small
video which visualizes and explains the details. see http://vimeo.com/14358869)
9.3.2. Associativity
There is still one topic we should mention, which is associativity. There is left and right associativity as
well as none associativity. In the example we have seen left associativity. Associativity tells the parser
how to construct the AST when there are two infix operations with the same precedence. The following
example is taken from the corresponding wikipedia entry:
Consider the expression a ~ b ~ c. If the operator ~ has left associativity, this expression would be
interpreted as (a ~ b) ~ c and evaluated left-to-right. If the operator has right associativity, the expression
would be interpreted as a ~ (b ~ c) and evaluated right-to-left. If the operator is non-associative, the
expression might be a syntax error, or it might have some special meaning. We already know the most
important form which is left associativity:
Addition returns Expression:
Multiplication ({Addition.left=current} '+' right=Multiplication)*;
Right associativity is done using the following pattern (note the quantity operator and the call to the rule
itself at the end):
Addition returns Expression:
Multiplication ({Addition.left=current} '+' right=Addition)?;
And if you don’t want to allow multiple usages of the same expression in a row (hence non-associativity)
you write:
Addition returns Expression:
Multiplication ({Addition.left=current} '+' right=Multiplication)?;
Note that sometimes it’s better to allow associativity on parser level, but forbid it later using validation,
because you can come up with a better error message. Also the whole parsing process won’t be
interrupted, so your tooling will generally be more forgiving.
Xtext 1.0 98
Chapter 10. Integration with EMF and
Other EMF Editors
Xtext relies heavily on EMF internally, but it can also be used as the serialization back-end of other EMF-
based tools. In this section we introduce the basic concepts of the Eclipse Modeling Framework (EMF)
in the context of Xtext. If you want to learn more about EMF, we recommend reading the EMF book.
The AST should contain the essence of your textual models and abstract over syntactical information. It is
used by later processing steps, such as validation, compilation or interpretation. In EMF a model is made
up of instances of EObjects which are connected and an EObject is an instance of an EClass. A set of
EClasses if contained in a so called EPackage, which are both concepts of Ecore In Xtext, meta models
are either inferred from the grammar or predefined by the user (see the section on package declarations
for details). The next diagram shows the meta model of our example:
The language in which the meta model is defined is called Ecore. In other words, the meta model is the
Ecore model of your language. Ecore an essential part of EMF. Your your models instantiate the meta
model, and your meta model instantiates Ecore. To put an end to this recursion, Ecore is defined in itself
(an instance of itself).
Xtext 1.0 99
Integration with EMF
and Other EMF Editors
The meta model defines the types of the semantic nodes as Ecore EClasses. EClasses are shown as
boxes in the meta mode diagram, so in our example, Model, Type, SimpleType, Entity, and Property are
EClasses. An EClass can inherit from other EClasses. Multiple inheritance is allowed in Ecore, but of
course cycles are forbidden.
EClasses can have EAttributes for their simple properties. These are shown inside the EClasses nodes.
The example contains two EAttributes name and one EAttribute isMulti. The domain of values for an
EAttribute is defined by its EDataType. Ecore ships with some predefined EDataTypes, which essentially
refer to Java primitive types and other immutable classes like String. To make a distinction from the Java
types, the EDataTypes are prefixed with an E. In our example, that’s EString and EBoolean.
In contrast to EAttributes, EReferences point to other EClasses. The containment flag indicates whether
an EReference is a containment reference or a cross-reference. In the diagram, references are edges and
containment references are marked with a diamond. At the model level, each element can have at most
one container, i.e. another element referring to it with a containment reference. This infers a tree structure
to the models, as can be seen in the sample model diagram. On the other hand, cross-references refer to
elements that can be contained anywhere else. In the example, elements and properties are containment
references, while type and extends are cross-references. For reasons of readability, we skipped the cross-
references in the sample model diagram. Note that in contrast to other parser generators, Xtext creates
ASTs with linked cross-references.
Other than associations in UML, EReferences in Ecore are always owned by one EClass and only
navigable in the direction form the owner to the type. Bi-directional associations must be modeled as two
references, being eOpposite of each other and owned by either end of the associations.
The superclass of EAttibutes and EReferences is EStructuralFeature and allows to define a name and a
cardinality by setting lowerBound and upperBound. Setting the latter to -1 means ‘unbounded’.
The common supertype of EDataType and EClass is EClassifier. An EPackage acts as a namespace and
container of EClassifiers.
We have summarized these most relevant concepts of Ecore in the following diagram:
additional information for the Ecore -> Java transformation. Xtext will automatically generate a generator
model with reasonable defaults for all generated metamodels, and run the EMF code generator on them.
The generated classes are based on the EMF runtime library, which offers a lot of infrastructure and tools
to work with your models, such as persistence, reflection, referential integrity, lazy loading etc.
Among other things, the code generator will generate
• A Java interface and a Java class for each EClassifier in your Ecore model. By default, all classes will
implement the interface org.eclipse.emf.ecore.EObject, linking a lot of runtime functionality.
• A Java bean property for each EStructuralFeature (member variable, accessor methods)
• A package interface and class, holding singleton objects for all elements of your Ecore model, allowing
reflection. EPackages are also registered to the EPackage.Registry to be usable at runtime.
• A factory interface and class for creating instances
• An abstract switch class implementing a visitor pattern to avoid if-instanceof cascades in your code.
The generator fragment ResourceFactoryFragment registers a factory for the XtextResource to EMF’s
resource factory registry, such that all tools using the default mechanism to resolve a resource
implementation will automatically get that resource implementation.
Using a self-defined textual syntax as the primary storage format has a number of advantages over the
default XMI serialization, e.g.
• You can use well-known and easy-to-use tools and techniques for manipulation, such as text editors,
regular expressions, or stream editors.
• You can use the same tools for version control as you use for source code. Merging and diffing is
performed in a syntax the developer is familiar with.
• It is impossible to break the model such that it cannot be reopened in the editor again.
• Models can be fixed using the same tools, even if they have become incompatible with a new version
of the Ecore model.
Xtext targets easy to use and naturally feeling languages. It focuses on the lexical aspects of a language
a bit more than on the semantic ones. As a consequence, a referenced Ecore model can contain more
concepts than are actually covered by the Xtext grammar. As a result, not everything that is possibly
expressed in the EMF model can be serialized back into a textual representation with regards to the
grammar. So if you want to use Xtext to serialize your models as described above, it is good to have a
couple of things in mind:
• Prefer optional rule calls (cardinality ? or *) to mandatory ones (cardinality + or default), such that
missing references will not obstruct serialization.
• You should not use an Xtext-Editor on the same model instance as a self-synchronizing other editor,
e.g. a canonical GMF editor (see :#gmf_integration_stage_1 for details). The Xtext parser replaces re-
parsed subtrees of the AST rather than modifying it, so elements will become stale. As the Xtext editor
continuously re-parses the model on changes, this will happen rather often. It is safer to synchronize
editors more loosely, e.g. on file changes.
• Implement an IFragmentProvider:#fragmentProvider to make the XtextResource return stable
fragments for its contained elements, e.g. based on composite names rather than order of appearance.
• Implement an IQualifiedNameProvider and an IScopeProvider:#scoping to make the names of all
linkable elements in cross-references unique.
• Provide an IFormatter:#formatting to improve the readability of the generated textual models.
• Register an IReferableElementsUnloader to turn deleted/replaced model elements into EMF proxies.
Design the rest of your application such that it does never keep references to EObjects or to cope with
proxies. That will improve the stability of your application drastically.
• Xtext will register an EMF ResourceFactory, so resources with the file extension you entered when
generating the Xtext plug-ins will be automatically loaded in an XtextResource when you use EMF’s
ResourceSet API to load it.
10.4.1. Stage 1: Make GMF Read and Write the Semantic Model As
Text
A diagram editor in GMF by default manages two resources: One for the semantic model, that is the model
we’re actually interested in for further processing. In our example it is a model representing entities and
datatypes. The second resource holds the notation model. It represents the shapes you see in the diagram
and their graphical properties. Notation elements reference their semantic counterparts. An entity’s name
would be in the semantic model, while the font to draw it in the diagram would be stored the notation
model. Note that in the integration example we’re only trying to represent the semantic resource as text.
To keep the semantic model and the diagram model in sync, GMF uses a so called CanonicalEditPolicy.
This component registers as a listener to the semantic model and automatically updates diagram elements
when their semantic counterparts change, are added or are removed. Some notational information can be
derived from the semantic model by some default mapping, but usually there is a lot of graphical stuff
that the user wants to change to make the diagram look better.
In an Xtext editor, changes in the text are transfered to the underlying XtextResource by a call to
the method org.eclipse.xtext.resource.XtextResource.update(int, int, String), which will trigger a partial
parsing of the dirty text region and a replacement of the corresponding subtree in the AST model (semantic
model).
Having an Xtext editor and a canonical GMF editor on the same resource can therefore lead to loss of
notational information, as a change in the Xtext editor will remove a subtree in the AST, causing the
CanonicalEditPolicy to remove all notational elements, even though it was customized by the user. The
Xtext rebuilds the AST and the notation model is restored using the default mapping. It is therefore not
recommended to let an Xtext editor and a canonical GMF editor work on the same resource.
In this example, we let each editor use its own memory instance of the model and synchronize on file
changes only. Both frameworks already synchronize with external changes to the edited files out-of-the-
box. In the glue code, a ConcurrentModificationObserver warns the user if she tries to edit the same file
with two different model editors concurrently.
In the example, we started with writing an Xtext grammar for an entity language. As explained above, we
preferred optional assignments and rather covered mandatory attributes in a validator. Into the bargain,
we added some services to improve the EMF integration, namely a formatter, a fragment provider and
an unloader. Then we let Xtext generate the language infrastructure. From the derived Ecore model and
its generator model, we generated the edit plug-in (needed by GMF) and added some fancier icons.
From the GMF side, we followed the default procedure and created a gmfgraph model, a gmftool model
and a gmfmap model referring to the Ecore model derived form the Xtext grammar. We changed some
settings in the gmfgen model derived by GMF from the gmfmap model, namely to enable printing and
to enable validation and validation decorators. Then we generated the diagram editor.
Voilà, we now have a diagram editor that reads/writes its semantic model as text. Also note that the
validator from Xtext is already integrated in the diagram editor via the menu bar.
create the overridden factory, and register the latter to the extension point. Note that this is a non-invasive
way to extend generated GMF editors.
When you test the editor, you will note that the node model will be corrupt after editing a few labels.
This is because the node model is only updated by the Xtext parser and not by the serializer. So we
need a way to automatically call the (partial) parser every time the semantic model is changed. You will
find the required classes in the package org.eclipse.xtext.gmf.glue.editingdomain. To activate node model
reconciling, you have to add a line
XtextNodeModelReconciler.adapt(editingDomain);
in the GenPlugin element of the gmfgen before generating the diagram editor anew.
with
<fragment
class="org.eclipse.xtext.generator.scoping.ImportURIScopingFragment"/>
<fragment
class="org.eclipse.xtext.generator.exporting.SimpleNamesFragment"/>
The PackratParserFragment has been abandoned as well. It is save to remove the reference to that one if
it is activated in your workflow. After you’ve changed your workflow, it should be possible to regenerate
your language without any errors in the console. It is ok to have compilation errors prior to executing
the workflow.
• The handling of ILabelProvider in various contexts has been refactored. The former base class
DefaultLabelProvider no longer exists. Use the DefaultEObjectLabelProvider instead. See the section
on label providers for details.
• We have introduced a couple of new packages to better separate concerns. Most classes should be
easy to relocate.
• The runtime and UI modules have separate base classes DefaultRuntimeModule and DefaultUiModule
now. We use Guice’s module overrides to combine them with the newly introduced SharedModule.
You have to add a constructor the your UiModule that takes an AbstractUiPlugin as argument and pass
that one to the super constructor. Tip: There is an Eclipse quick fix available for that one.
• The interfaces ILexicalHighlightigConfiguration and ISemanticHighlightingConfiguration have been
merged into IHighlightingConfiguration.
• The DefaultTemplateProposalProvider takes an additional, injectable constructor parameter of type
ContextTypeIdHelper.
• The HyperlinkHelper uses field injection instead of constructor injection. The method
createHyperlinksByOffset should be overridden instead of the former findCrossLinkedEObject.
• The API to skip a node in the outline has changed. Instead of returning the _HIDDEN_NODE_ you’ll
have to implement boolean consumeNode(MyType) and return false.
• The Readonly*Storage implementations have been removed. There is a new API to open editors
for objects with a given URI. Please use the IURIEditorOpener to create an editor or the
IStorage2UriMapper to obtain an IStorage for a given URI.
• The interfaces IStateAccess and IEObjectHandle have been moved along with the IUnitOfWork to the
package org.eclipse.xtext.util.concurrent.
• The ValidationJobFactory is gone. Please implement a custom IResourceValidator instead.
• The grammar elements Alternatives and Group have a new common super type CompoundElement.
The methods getGroups and getTokens have been refactored to getElements.
• Completion proposals take a StyledString instead of a plain string as display string.
• The AbstractLabelProvider does no longer expose its IImageHelper. Use convertToImage instead or
inject your own IImageHelper.
• The implementation-classes from org.eclipse.xtext.index were superseded by the builder infrastructure.
Use the QualifiedNamesFragment and the ImportNamespacesScopingFragment instead of the
ImportedNamespacesScopingFragment. Please refer to the section about the builder infrastructure for
details.
• All the Xtend-based fragments were removed.
• ILinkingService.getLinkText was removed. Have a look at the LinkingHelper and the
CrossReferenceSerializer if you relied on this method.
• The SerializerUtil was renamed to Serializer. There were other heavy refactorings that involved the
serializer and its components (like e.g. the ITransientValueService) but it should be pretty straight
forward to migrate existing client code.
• The method-signatures of the IFragmentProvider have changed. The documentation will give a clue
on how to update existing implementations.
• Some static methods were removed from utility classes such as EcoreUtil2 and ParsetreeUtil in favor
of more sophisticated implementations.
• quick outline
• MWE2
• refering to Java elements
For an overview over the new features consult our New and Noteworthy online.