Xtext User Guide
Xtext User Guide
Xtext 0.7
1. Overview .................................................................................................................... 1 1.1. What is Xtext? ................................................................................................... 1 1.2. What is a domain-specific language ....................................................................... 1 1.3. Getting Started ................................................................................................... 2 1.3.1. Create an Xtext project .............................................................................. 2 1.3.2. Project layout .......................................................................................... 3 1.3.3. Build your own grammar ........................................................................... 3 1.3.4. Generate language artifacts ........................................................................ 5 1.3.5. Test the generated editor ............................................................................ 5 2. The Grammar Language .............................................................................................. 7 2.1. First an example ................................................................................................. 7 2.2. The Syntax ........................................................................................................ 8 2.2.1. Language Declaration ................................................................................ 8 2.2.2. EPackage declarations ............................................................................... 8 2.2.3. Rules .................................................................................................... 10 2.2.4. Parser Rules ........................................................................................... 12 2.2.5. Hidden terminal symbols .......................................................................... 16 2.2.6. Data type rules ....................................................................................... 16 2.2.7. Enum Rules ........................................................................................... 17 2.3. Ecore model inference ....................................................................................... 17 2.3.1. Type and Package Generation ................................................................... 17 2.3.2. Feature and Type Hierarchy Generation ...................................................... 18 2.3.3. Enum Literal Generation .......................................................................... 18 2.3.4. Feature Normalization ............................................................................. 19 2.3.5. Customized Post Processing ...................................................................... 19 2.3.6. Error Conditions ..................................................................................... 19 2.4. Importing existing Ecore models .......................................................................... 19 2.5. Grammar Mixins ............................................................................................... 19 2.6. Default tokens .................................................................................................. 20 3. Configuration ............................................................................................................ 21 3.1. The Generator .................................................................................................. 21 3.1.1. A short introduction to MWE ................................................................... 21 3.1.2. General Architecture .............................................................................. 22 3.1.3. Standard generator fragments .................................................................... 24 3.2. Dependency Injection in Xtext with Google Guice .................................................. 24 3.2.1. Services ................................................................................................ 24 3.2.2. Modules ................................................................................................ 25 4. Runtime Concepts ...................................................................................................... 28 4.1. Runtime setup (ISetup) ....................................................................................... 28 4.2. Setup within Eclipse-Equinox (OSGi) ................................................................... 28 4.3. Validation ........................................................................................................ 28 4.3.1. Syntactical Validation .............................................................................. 28 4.3.2. Crosslink Validation ................................................................................ 28 4.3.3. Custom Validation .................................................................................. 29 4.3.4. Validation with the Check language ........................................................... 29 4.4. Linking ........................................................................................................... 30 4.4.1. Declaration of crosslinks .......................................................................... 30 4.4.2. Specification of linking semantics .............................................................. 30 4.4.3. Default linking semantics ......................................................................... 31 4.5. Scoping ........................................................................................................... 32 4.5.1. Declarative Scope Provider ....................................................................... 34 4.6. Value Converter ................................................................................................ 35 4.6.1. Annotation based value converters ............................................................. 35 4.7. Serialization ..................................................................................................... 36 4.7.1. The Contract .......................................................................................... 36 4.7.2. Parse Tree Constructor ............................................................................ 36 4.7.3. Transient Values ..................................................................................... 37 4.7.4. Unassigned Text ..................................................................................... 37
Xtext 0.7
ii
4.7.5. Cross Reference Serializer ........................................................................ 4.7.6. Hidden Token Merger ............................................................................. 4.7.7. Token Stream ......................................................................................... 4.8. Integration with EMF ......................................................................................... 4.8.1. XtextResource Implementation .................................................................. 4.8.2. Fragment Provider (referencing Xtext models from other EMF artifacts) ............ 5. IDE concepts ............................................................................................................. 5.1. Label Provider .................................................................................................. 5.1.1. DefaultLabelProvider ............................................................................... 5.2. Content Assist .................................................................................................. 5.2.1. ProposalProvider ..................................................................................... 5.2.2. Sample Implementation ............................................................................ 5.3. Template Proposals ........................................................................................... 5.3.1. CrossReference TemplateVariableResolver .................................................. 5.3.2. Enumeration TemplateVariableResolver ...................................................... 5.4. Outline View .................................................................................................... 5.4.1. Influencing the outline structure ................................................................ 5.4.2. Filtering ................................................................................................ 5.4.3. Context menus ....................................................................................... 5.5. Hyperlinking .................................................................................................... 5.5.1. Location Provider ................................................................................... 5.6. Formatting (Pretty Printing) ................................................................................ 5.6.1. Declarative Formatter ............................................................................. 5.7. Syntax Coloring ................................................................................................ 5.7.1. Lexical Highlighting ................................................................................ 5.7.2. Semantic Highlighting ............................................................................. 6. From oAW to TMF .................................................................................................... 6.1. Why a rewrite? ................................................................................................. 6.2. Migration overview ........................................................................................... 6.3. Where are the Xtend-based APIs? ........................................................................ 6.3.1. Xtend is hard to debug ............................................................................ 6.3.2. Xtend is slow ......................................................................................... 6.3.3. Convenient Java ..................................................................................... 6.3.4. Conclusion ............................................................................................ 6.4. Differences ...................................................................................................... 6.4.1. Differences in the grammar language .......................................................... 6.4.2. Differences in Linking ............................................................................. 6.4.3. Differences in UI customizing ................................................................... 6.5. New Features ................................................................................................... 6.5.1. Dependency Injection with Google Guice .................................................... 6.5.2. Improvements on Grammar Level .............................................................. 6.5.3. Fine-grained control for validation ............................................................. 6.6. Migration Support ............................................................................................. 7. The ANTLR IP issue (or which parser to use?) ............................................................. 7.1. What if I do not want to use non IP-approved code .................................................
37 37 37 38 38 39 40 40 40 41 41 42 42 43 44 44 45 46 48 49 49 50 50 51 52 53 55 55 55 56 56 56 56 57 57 57 59 60 60 60 60 60 61 62 62
Xtext 0.7
iii
Chapter 1. Overview
1.1. What is Xtext?
Xtext is a framework for the development of domain-specific languages and other textual programming languages. It is tightly integrated with the Eclipse Modeling Framework (EMF) and leverages the Eclipse Platform in order to provide a language-specific integrated development environment (IDE). In contrast to common parser generators (like e.g. JavaCC or ANTLR), Xtext derives much more than just a parser and lexical analyzer (lexer) from an input grammar. The grammar language is used to describe and generate: an incremental, ANTLR 3 based parser and lexer to read your models from text, Ecore models (optional), a serializer to write your models back to text, a linker, to establish cross links between model elements, an implementation of the EMF Resource interface with full support for loading and saving EMF models, and an integration of the language into your Eclipse IDE. Some of the IDE features, that are either derived from the grammar or easily implementable, are syntax coloring, model navigation (F3, etc.), code completion, outline view, and code templates. The generated artifacts are wired up through Google Guice, a dependency injection framework which makes it easy to exchange certain functionality in a non-invasive manner. Although Xtext aims at supporting fast iterative development of domain-specific languages, it can be used to implement IDEs for general purpose programming languages as well.
Xtext 0.7
Overview
hard task of reading your model, working with it and writing it back to your syntax is greatly simplified by Xtext.
Uncheck Generate Generator project, you will not need it this time. Click on Finish.
Xtext 0.7
Overview
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 manual 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.
Xtext 0.7
Overview
to another rule named Entity, which will be defined later on. As we can have one ore more entities within a model, the cardinality is +. Each rule is terminated with a semicolon. So our first rule reads as
Model : Entity+;
Please note: If you encounter strange errors while copying and pasting these snippets to your Eclipse editor your documentation viewer most likely has inserted characters different from {space} into your clipboard. Reenter these fillers or type the text by hand to be sure everything works fine. An Xtext grammar does not only describe rules for the parser but also the structure of the resulting abstract syntax tree. Usually, each parser rule will create a new node in that tree. The type of that node can be specified after the rule name using the keyword returns. If the types name is the same as the rule name, it can be omitted as in our case. The parser will create a new element of type Model when it enters the rule Model, and a new element of type Entity every time it enters the rule Entity. To connect these AST elements, we have to define the name of a reference. In our case, we call that reference entities. We specify it using the assignment operator " +=", which denotes a multi valued feature. As a result, we modify the first rule to
Model : (elements += Entity)+;
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 entitys name and an opening curly brace (we will handle the extends clause in a second step). Then, an entity defines a number of properties and ends with a closing curly brace.
Entity returns Entity: 'entity' name=ID '{' (properties+=Property)* '}' ;
Instead of creating a new AST node for the name, we rather want the name to be an attribute of the Entity class. Therefore we use the terminal rule ID, which results in a string. The assignment operator " =" denotes a single valued feature, and the asterisk a cardinality of 0..n. In our target syntax, some entities refer to an existing entity as their super type after the keyword extends. Note that this is a cross-reference, as the super type itself must be defined somewhere else. To define a cross-reference we use square brackets. Optional parts have the cardinality ?. The complete rule now reads:
Entity returns Entity: 'entity' name=ID ('extends' extends=[Entity])? '{' (properties+=Property)* '}' ;
We have not specified the rule Property, yet. In our target syntax, properties can refer to simple types such as String or Bool as well as entities. To make this easy we will first introduce a common supertype Type each Property can refer to. Change the rule Model and introduce a new rule Type and SimpleType:
Model : (elements+=Type)*; Type: SimpleType | Entity; SimpleType: 'type' name=ID;
Models new consist of types where a Type can either be a SimpleType or the Entity you already know. Our rule Type will just delegate to either of them, using the " |" alternatives operator. The
Xtext 0.7
Overview
combination of simple data types and entites this way introduces a common super type Type both Entity and SimpleType derive from. This allows you to refer to both types of elements with a single cross-reference. A Property consist of a keyword, a name, a colon and a cross-reference to an arbitrary Type. The multiplicity is either many or one. The presence of the postfix [] (technically a keyword) should trigger a boolean flag in the AST model. This is the purpose of the assignment operator " ?=". Our last parser rule is:
Property: 'property' name=ID ':' type=[Type] (many?='[]')?;
Xtext 0.7
Overview
Xtext 0.7
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 it is not clear enough.
Xtext 0.7
In order to get a complete IDE for this little language from Xtext, you need to write the following grammar:
grammar my.pack.SecretCompartments with org.eclipse.xtext.common.Terminals generate secretcompartment "http://www.eclipse.org/secretcompartment" 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];
declares the name of the grammar. Xtext leverages Javas class path mechanism. This means that the name can be any valid Java qualifier. The file name needs to correspond to the grammar name and have the file extension xtext. This means that the name has to be SecretCompartments.xtext and must be placed in a package my.pack somewhere on your projects class path. The first line is also used to declare any used language (for mechanism details see Grammar Mixins).
Xtext 0.7
That statement means: generate an EPackage with the name secretcompartment and the nsURI http://www.eclipse.org/secretcompartment. Actually these are the properties that are required to create an EPackage. The whole algorithm used to derive complete Ecore models from Xtext grammars is described in the section Ecore model inference.
Note that if you use a namespace URI, the corresponding EPackage needs to be installed into the workbench. Otherwise the editor cannot find it. At runtime (i.e. when starting the generator) you need to make sure that the corresponding EPackage is registered in the EPackage.Registry.INSTANCE. If you use MWE to drive your code generator, you need to add the following lines to your workflow file:
<bean class="org.eclipse.emf.mwe.utils.StandaloneSetup" platformUri="${runtimeProject}/.."> <registerGeneratedEPackage value="my.pack.SecretcompartmentPackage"/> </bean>
Using namespace URIs is typically only interesting when common Ecore models are used, such as Ecore itself or the UML meta model. If youre developing the EPackage together with the DSL but dont want to have it derived from the grammar for some reason, we suggest to use a resource URI.
If you want to mix generated and imported Ecore models youll have to configure the generator fragment in your MWE file responsible for generating the Ecore classes ( EcoreGeneratorFragment) with resource URIs that point to the genmodels for the referenced Ecore models. Example:
<fragment class="org.eclipse.xtext.generator.ecore.EcoreGeneratorFragment" genModels= "platform:/resource/project/src/my/pack/SecretCompartments.genmodel"/>
When referring to a type somewhere in the grammar you need to qualify the reference using that alias (example another::CoolType). Well 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.
Xtext 0.7
Example:
generate toBeGenerated 'http://www.eclipse.org/toBeGenerated' import 'http://www.eclipse.org/packContainingClassA' import 'http://www.eclipse.org/packContainingClassB'
With the declaration above 1. a reference to type ClassA would be linked to the EClass contained in http:// www.eclipse.org/packContainingClassA, 2. a reference to type ClassB would be linked to the EClass contained in http:// www.eclipse.org/packContainingClassB, 3. a reference to type NotYetDefined would be linked to a newly created EClass in http:// www.eclipse.org/toBeGenerated. 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.
2.2.3. Rules
The default parsing is based on a home-grown packrat parser. It is advised to substitute it by an ANTLR parser through the Xtext service mechanism. ANTLR is a sophisticated parser generator framework based on an LL(*) parsing algorithm, that works quite well for Xtext. Please download the plugin de.itemis.xtext.antlr (from update site http://download.itemis.com/updates/) and use the ANTLR Parser instead of the packrat parser (cf. Xtext Workspace Setup). 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 rules 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.
Xtext 0.7
10
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')+;
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 org.eclipse.xtext.common.Terminals for instance starts with a keyword:
terminal ID : '^'? .... ;
rule
in
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.
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 multiline 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 explanation mark:
terminal ML_COMMENT : '/*' (!'*/')+;
Xtext 0.7
11
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 QUALIFIED_NAME : ID ('.' ID)*;
Alternatives
Using alternatives one can state multiple different alternatives. For instance, the whitespace rule uses alternatives like this:
terminal WS : (' '|'\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');
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 types name equals the rules name. The type of the feature is infered 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
Xtext 0.7
12
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. 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] ; Event returns MyEvent : ....;
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 an 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.
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.
Xtext 0.7
13
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 ; MyOtherRule returns TypeB : "B" name = ID ;
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.
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.
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
Xtext 0.7
14
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 wouldnt get any of the nice IDE features as soon as there is one little error, if we hadnt 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 ;
In practice this is always the same pattern and therefore not that problematic. However, by simply applying the Xtext AST construction features weve covered so far, a grammar ...
Expression : {Operation} left=TerminalExpression (op='+' right=Expression)? ; TerminalExpression returns Expression: '(' Expression ')' | {IntLiteral} value=INT ;
... 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)? ; TerminalExpression returns Expression: '(' Expression ')' | {IntLiteral} value=INT ;
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-bereturned ( 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:
Xtext 0.7
15
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.
This looks similar to the terminal rule weve defined above in order to explain rule calls. However, the difference is that because it is a parser rule and therefore only valid in certain contexts, it wont 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")
Xtext 0.7
16
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. For conversion again value converters are responsible (cf. value converters).
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)?;
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 0.7
17
An optional alias as the third parameter allows to distinguish generated EPackages later. Only one generated package declaration per alias is allowed. an EClass for each return type of a parser rule. If a parser rule does not define a return type, an implicit one with the same name as the rule itself is assumed. You can specify more than one rule that return the same type but only one EClass will be generated. for each type defined in an action or a cross reference. an EEnum for each return type of an enum rule. an EDatatype for each return type of a terminal rule or a data type rule. All EClasses, EEnums and EDatatypes are added to the EPackage referred to by the alias provided in the type reference they were created from.
Xtext 0.7
18
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).
Specify an explicit return type to reuse such imported types. Note that this even works for terminal rules.
terminal INT returns ecore::EInt : ('0'..'9')+;
Xtext 0.7
19
grammar org.xtext.example.MyDsl with org.eclipse.xtext.common.Terminals generate myDsl 'http://www.xtext.org/example/MyDsl' ... some rules
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 "}"; grammar my.SubGrammar with my.SuperGrammar 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 0.7
20
Chapter 3. Configuration
3.1. The Generator
Xtext provides lots of generic implementations for your languages infrastructure but also uses code generation to generate some of the components. Those generated components are for instance the parser, the serializer, the Ecore model 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. Xtexts generator leverages the modeling workflow engine (MWE) from EMFT.
These couple of lines will, when interpreted by MWE, result in an object tree consisting of three instances of foo.Person:
The root element can have an arbitrary name, with one exception: If the name is workflow and no class attribute is provided, it is assumed that an instance of org.eclipse.emf.mwe.internal.core.Workflow shall be instantiated. This instance will be the root of a workflow model used in generator workflow configurations. However, as you can see in the example above one can instantiate arbitrary Java object models. This is conceptually very close to the dependency injection and the XML language in the Spring Framework. As explained above the element name ' x' is ignored in this case. The attribute class tells MWE which class to use in order to create the object node. The created object is populated according to the XML description: For each XML attribute MWE calls a corresponding setter or adder method passing in the value (there are configurable value converters, but usually Boolean and String is all you need). The same
Xtext 0.7
21
Configuration
procedure is applied for each child element. In the case of XML elements a single attribute value is used and interpreted as if it was an attribute in the parent element. That is:
<foo><name value="bar"/></foo>
Obviously the latter is far more readable and should be preferred. However, as soon as you want to add multiple values to the same adder method you will need to use the first syntax because you cannot define the same attribute twice in XML. If an element does not have an attribute value, the engine looks for an attribute called class. If it finds one, the class is instantiated by means of the default constructor (there is no support for factories as of now.). If not, the class is inferred by looking at the arguments type of the current setter method. Due to this shortcut it is valid to write:
<child name="Son"/>
The addChild method takes a foo.Person as an argument. As this is a concrete class which has a default constructor it can be instantiated. Tip Whenever you are in an *.mwe file and wonder what kind of configuration the underlying component may accept: Just use JDTs open type action (CTRL+Shift+T) open the source file of the class in question, use the quick outline view (CTRL+O, use CTRL+O twice to see inherited members as well) and type set or add and you will see the available modifiers. Note that we plan to replace the XML syntax with an Xtext-based implementation as soon as possible. This is the basic idea of the MWE 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 consult the MWE reference documentation (available through Eclipse help) for additional information.
Xtext 0.7
22
Configuration
AbstractGeneratorFragment, which by default delegates to an Xpand template with the same qualified name as the class and delegates some of the calls to Xpand template definitions. We suggest to have a look at the fragment we have written for label providers ( LabelProviderFragment). It is pretty trivial and at the same time uses the most important call backs. In addition, the structure is not cluttered with too much extra noise so that the whole package (as of Xtext 0.7.0) can serve as a template to write your own fragment.
3.1.2.2. Configuration
As already explained we use MWE 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 MWE configuration code:
<workflow> <property file="org/xtext/example/GenerateMyDsl.properties"/> <property name="runtimeProject" value="../${projectName}"/> <bean class="org.eclipse.emf.mwe.utils.StandaloneSetup" platformUri="${runtimeProject}/.."/> <component class="org.eclipse.emf.mwe.utils.DirectoryCleaner" directory="${runtimeProject}/src-gen"/> <component class="org.eclipse.emf.mwe.utils.DirectoryCleaner" directory="${runtimeProject}.ui/src-gen"/> <component class="org.eclipse.xtext.generator.Generator"> <pathRtProject value="${runtimeProject}"/> <pathUiProject value="${runtimeProject}.ui"/> <projectNameRt value="${projectName}"/> <projectNameUi value="${projectName}.ui"/> <language uri="${grammarURI}" fileExtensions="${file.extensions}"> <!-- Java API to access grammar elements (required by several other fragments) --> <fragment class= "org.eclipse.xtext.generator.grammarAccess.GrammarAccessFragment"/> <!-- a lot more simple fragments --> <!-- ... --> <!-- a sample fragment with a property --> <fragment class= "org.eclipse.xtext.generator.validation.JavaValidatorFragment"> <composedCheck value="org.eclipse.xtext.validation.ImportUriValidator"/> </fragment> <!-- more simple fragments --> <!-- ... --> </language> </component> </workflow>
Here the root element is a workflow which accepts bean s and component s. The <property/> element is a first class concept of MWEs configuration language and essentially acts as a preprocessor, which replaces all occurrences of ${propertyName} with the given value. Property declarations can be defined in-line ( <property name="foo" value="bar"/>) or by means of a property file import ( <property file="foo.properties"/>) which is performed before the actual tree is created. In this example we first import a properties file and after that declare a property runtimeProject which already uses a property imported from the previously imported file. The method Workflow.setBean() does nothing but provides a means to apply global side-effects, which unfortunately is required by some projects. In this example we do a so called EMF stand alone
Xtext 0.7
23
Configuration
setup. This class initializes a bunch of things for a non-OSGi environment that are otherwise configured by means of extension points, e.g. EMFs EPackage.Registry. Following the <bean/> element there are three <component/> elements. The Workflow.addComponent() method awaits instances of IWorkflowComponent, which is the primary concept of MWEs workflow model. Xtexts generator is an instance of IWorkflowComponent and can therefore be used within MWE workflows.
Important Due to IP-Problems with the code generator shipped with ANTLR 3 were not allowed to ship this fragment at Eclipse. Therefore youll have to download it separately from http://download.itemis.com or use the update site at http://download.itemis.com/updates/.
3.2.1. Services
The most parts of Xtext are implemented as services. A service is an object which implements a certain interface and which is instantiated and provided by Guice. Nearly every concept of the Xtext framework can be understood as this sort of service: The XtextEditor, the XtextResource, the IParser and even fine grained concepts as the PrefixMatcher for the content assist are configured and provided by Guice. Xtext ships with generic default implementations for most or the services or uses generator fragments to automatically generate service implementations for a grammar. Thereby, Xtext strives to provide
Xtext 0.7
24
Configuration
meaningful implementations out of the box and to allow customization wherever needed. Developers are encouraged to subclass existing services and configure them for their languages in their modules. When Guice instantiates an object, it also supplies this instance with all its dependent services. All a service does is to request some implementation for a certain interface using the @Inject-annotation. Based on the modules configuration Guice decides which class to instantiate or which object to reuse. For example, Guice can automatically initialize member variables with the needed services.
public class MyLanguageLinker extends Linker { @Inject private IScopeProvider scopeProvider; @Inject(optional=true) private IXtext2EcorePostProcessor postProcessor; (...) }
Furthermore, Guice can pass the needed services as method parameters or event into a constructor call.
public class MyLanguageGrammarAccess implements IGrammarAccess { private final GrammarProvider grammarProvider; private TerminalsGrammarAccess gaTerminals; @Inject public MyLanguageGrammarAccess(GrammarProvider grammarProvider, TerminalsGrammarAccess gaTerminals) { this.grammarProvider = grammarProvider; this.gaTerminals = gaTerminals; } (...) }
3.2.2. Modules
The configuration of services for a language built with Xtext is done via modules: Modules bind arbitrary Java interfaces to their implementation classes or directly to instances of their implementation classes. Such a binding is sort of a configurable mapping. A module itself is a plain Java class. Modules can inherit from each other and override bindings that are declared in super-modules. This concept is put on top of plain Guice modules by Xtext. In Xtext, there is a generic default module for all languages, there are automatically generated modules and there are modules which are intended to be customized manually. Furthermore, Xtext distinguishes between modules for runtime-services and modules related to services needed for the user interface. The UI module extends the runtime module. In total, this leads to five modules for a typical Xtext Language. They are visualized in the image below. The image is further explained in the following subsections.
Xtext 0.7
25
Configuration
Such a method will be interpreted as a binding from IFooService to MyFooServiceImpl.class. Note that you simply have to override a method from a super class (e.g. from the generated or default module) in order to change the respective binding. For example, in the picture above, the DefaultRuntimeModule configures the IFormatter to be implemented by the
Xtext 0.7
26
Configuration
OneWhitespaceFormatter. The AbstractMyLanguageModule overrides this binding by mapping the IFormatter to MyLanguageFormatter. The type to type binding will create a new instance of the given target type for each dependency. If you want to make it a singleton and thereby ensure only one instance to be created and reused for all dependencies you can add the following annotation:
@SingletonBinding public Class<? extends IFooService> bindIFooService() { return MyFooServiceImpl.class; }
In addition if the creation of the type causes any necessary side effects, so you want it to be instantiated eagerly, you can set the eager property to true. This is shown in the following snippet:
@SingletonBinding(eager=true) public Class<? extends IFooService> bindIFooService() { return MyFooServiceImpl.class; }
One more way of specify a binding is currently supported: If you need to control the way, the instance is created, you can declare a type to object mapping:
public IFooService bindIFooService() { return new MyFooServiceImpl(); }
Note that, although this is a convenient and simple way, you have of course also the full power of Guice, i.e. you can override the Guice method void configure(Binder) and use the afore mentioned fluent API to do whatever you want.
Xtext 0.7
27
4.3. 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 0.7
28
Runtime Concepts
to navigate through the model so that all installed EMF proxies get resolved. This is done automatically in the editor. Any unresolvable crosslinks will be reported and can be obtained through: org.eclipse.emf.ecore.resource.Resource.getErrors() org.eclipse.emf.ecore.resource.Resource.getWarnings()
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. Thats 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); } }
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 (FastChecks) or when triggering the validation explicitly (ExpensiveChecks). When using Check the example of the previous chapter could be written like this.
Xtext 0.7
29
Runtime Concepts
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 Xpands reference documentation which is shipped as Eclipse help.
4.4. 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
Example:
ReferringType : 'ref' referencedObject=[Entity|(ID|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 an ID or a STRING and the surrounding information in the current context (see scoping). Example: While parsing a given input string, say
ref Entity01
Xtext produces an instance of ReferringType. After this parsing step it enters the linking phase and tries to find an instance of 'Entity' using the parsed text Entity01. The input
ref "EntityWith"
would work analogously. This is not an ID (umlauts are not allowed), but a STRING (as it is apparent from the quotation marks).
Xtext 0.7
30
Runtime Concepts
public interface ILinkingService { /** * Returns all {@link EObject}s referenced by the given link text in the * given context. But does not set the references or modifies the passed * information somehow */ List<EObject> getLinkedObjects( EObject context, EReference reference, AbstractNode node) throws IllegalNodeException; /** * Returns the textual representation of a given object as it would be * serialized in the given context. * @return the text representation. */ String getLinkText(EObject object, EReference reference, EObject context); }
The method getLinkedObjects is directly related to this topic whereas getLinkText addresses complementary functionality: it is used for serialization. A simple implementation of the linking service (the DefaultLinkingService) is shipped with Xtext and used for any grammar per default. It uses the default implementation of IScopeProvider to compute the linking candidates.
the ref would be linked to the declared entity ( entity Entity01;). Nearly any aspect is configurable, especially the name of the identifying attribute may be overridden for a particular type.
Xtext 0.7
31
Runtime Concepts
Model : (imports+=Import)* (stuff+=(Ref|Entity))* ; Import : 'import' importURI=STRING ';' ; Ref : 'ref' referencedObject=[Entity|ID] ';' ; Entity : 'entity' name=ID ';' ;
It would be possible to write three files in that language where the first references the other two, like this:
//file model.dsl import "model1.dsl"; import "model2.dsl"; ref Foo; entity Bar; //file model1.dsl entity Stuff; //file model2.dsl entity Foo;
The linking candidates for the reference Foo will be Bar, Stuff and Foo in that order. They will be computed by the ScopeProvider.
4.5. Scoping
An IScopeProvider is responsible for providing an IScope for a given context EObject and EReference (declared or inherited by the objects EClass). The returned IScope should contain all target candidates for the given object and cross reference.
Xtext 0.7
32
Runtime Concepts
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. */ public IScope getScope(EObject context, EReference reference); /** * Returns a scope for a given context. The scope contains any visible, * type-compatible element. * @param context the element from which an element shall be referenced * @param type the (super)type of the elements. * @return {@link IScope} representing the inner most {@link IScope} for * the passed context and type. */ public IScope getScope(EObject context, EClass type); }
A single IScope represents an element of a linked list of scopes. That means that a scope can be nested within an outer scope. For instance Java has multiple kinds of scopes (object scope, type scope, etc.). For Java one would create the scope hierarchy as commented in the following example:
// file contents scope import static my.Constants.STATIC; public class ScopeExample { // class body scope private Object field = STATIC; private void method(String param) { // method body scope String localVar = "bar"; innerBlock: { // block scope String innerScopeVar = "foo"; Object field = innerScopeVar; // the scope hierarchy at this point would look like this: // blockScope{field,innerScopeVar}-> // methodScope{localVar, param}-> // classScope{field}-> ('field' is overlayed) // fileScope{STATIC}-> // classpathScope{'all qualified names of accessible static fields'} -> // NULLSCOPE{} // } field.add(localVar); } }
In fact the class path scope should also reflect the order of class path 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 default implementation would produce this hierarchy of scopes for the model from the last example in the previous chapter:
Xtext 0.7
33
Runtime Concepts
//file model.dsl import "model1.dsl"; import "model2.dsl"; ref Foo; entity Bar; //file model1.dsl entity Stuff; //file model2.dsl entity Foo; Scope (model.dsl) { parent : Scope (model1.dsl) { parent : Scope (model2.dsl) {} } }
When enumerating the scopes content, the first, most specialized scope would return Bar, its parent would provide Stuff and the outermost scope adds Foo. The linker will iterate the scope in that order and abort when it finds a matching ScopedElement.
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 references 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 which also corresponds to the type parameter. 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 objects 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. 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 (with the EClass parameter). 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, EClass type)
If no such method exists, the implementation will again try to find a method matching the context objects 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:
Xtext 0.7
34
Runtime Concepts
This scope can now be used for any cross references of type State for context objects owned by the state machine.
If you use the common terminals grammar org.eclipse.xtext.common.Terminals you should subclass DefaultTerminalConverters and override or add additional value converters by adding the respective methods. Imagine, you would want to add a rule BIG_DECIMAL creating BigDecimals, it would look like this one:
@ValueConverter(rule = "BIG_DECIMAL") public IValueConverter<BigDecimal> BIG_DECIMAL() { return new AbstractToStringConverter<BigDecimal>() { @Override protected BigDecimal internalToValue(String string, AbstractNode node) { return BigDecimal.valueOf(string); } }; }
Xtext 0.7
35
Runtime Concepts
4.7. 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 three steps: 1. Matching the model elements with the grammar rules and creating a stream of tokens. This is done by the parse tree constructor. 2. Mixing existing hidden tokens (whitespace, comments, etc.) into the token stream. This is done by the hidden token merger. 3. Adding needed whitespace or replacing all whitespace using a formatter. Serialization is invoked when calling XtextResource .save(...). Furthermore, SerializerUtil provides resource-independent support for serialization.
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.
This example introduces the constraint sval.size() == ival.size(). Models which violate this constraint are sort of valid EMF models, but they can not be serialized. To check whether a model complies with all constraints introduced by the grammar, the only way is currently to invoke the parse tree constructor. If this changes at some day, there will be news in bugzilla 239565. For the parse tree constructor, this can lead to the scenarios, where a model element can not be consumed. This can have the following reasons/solutions: The model element should not be stored in the model. The grammar needs an assignment which would consume the model element. The transient value service could be used to indicate that this model element should not be consumed. an assignment in the grammar has no corresponding model element. The parse tree constructor considers a model element not to be present 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.
Xtext 0.7
36
Runtime Concepts
The assignment in the grammar should be made optional. 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 constructors task is to find this path with the condition, that all model elements are consumed while walking this path. The parse tree constructors 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.
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 implementing the IUnassignedTextSerializer.
Xtext 0.7
37
Runtime Concepts
can be converted to a String using the TokenStringBuffer and to an OutputStream using the TokenOutputStream. Maybe there will be an implementation to reconstruct a node model as well at some point in the future. While providing fast output due to the stream pattern, token streams allow easy manipulation of the stream, such as mixing in whitespace or manipulating them.
public interface ITokenStream { public void close() throws IOException; public void writeHidden( EObject grammarElement, String value) throws IOException; public void writeSemantic( EObject grammarElement, String value) throws IOException; }
The generator fragment ResourceFactoryFragment registers a factory for the XtextResource to EMFs 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.
Xtext 0.7
38
Runtime Concepts
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 never use an Xtext-Editor on the same model instance as a self-synchronizing other editor, e.g. a canonical GMF editor. The Xtext parser replaces re-parsed subtrees of the AST rather than modifying it, so elements will become stale. Additional information, such as graphical properties in the case of GMF, attached to these elements are likely to be lost. As the Xtext editor continuously re-parses the model on changes, this will happen rather often. It is safer to synchronize editors on file changes. Implement an IFragmentProvider to make the XtextResource return stable fragments for its contained elements, e.g. based on composite names rather than order of appearance.
4.8.2. Fragment Provider (referencing Xtext models from other EMF artifacts)
Although inter-Xtext linking is not done by URIs, you may want to be able to reference your EObject from non-Xtext models. In those cases URIs are used, which are made up of a part identifying the resource. Each EObject contained in a resource can be identified by a so called fragment. A fragment is a part of an EMF URI and needs to be unique per resource. The generic XMI resource shipped with EMF provides a generic path-like computation of fragments. With an XMI or other binary-like serialization it is also common and possible to use UUIDs. However with a textual concrete syntax we want to be able to compute fragments out of the given information. We dont want to force people to use UUIDs (i.e. synthetic identifiers) or relative generic paths (very fragile), in order to refer to EObjects. Therefore one can contribute a so called IFragmentProvider per language.
public interface IFragmentProvider extends ILanguageService { /** * Computes the local ID of the given object. * @param obj * The EObject to compute the fragment for * @return the fragment, which can be an arbitrary string but must be * unique within a resource. Return null to use default * implementation */ String getFragment(EObject obj); /** * Locates an EObject in a resource by its fragment. * @return the EObject */ EObject getEObject(Resource resource, String fragment); }
Note that the currently available default fragment provider does nothing (i.e. falls back to the default behavior of EMF).
Xtext 0.7
39
5.1.1. DefaultLabelProvider
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 DefaultLabelProvider.
Xtext 0.7
40
IDE concepts
public class SampleLabelProvider extends DefaultLabelProvider { String text(RuleA rule) { return "Rule: " + rule.getName(); } String image(RuleA rule) { return "ruleA.gif"; } String image(RuleB rule) { return "ruleB.gif"; } }
The declarative implementation of the label itself is pretty straightforward. The image in turn is expected to be found in a file named icons/<result of image-method> in your plugin. This path is actually configurable by google guice. Have a look at the PluginImageHelper to learn about the customizing possibilities. 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 that is called name and try to use this one. If it cannot find a feature like this, 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. More advanced usage patterns of the DefaultLabelProvider include a dispatching to an error handler called String error_text(Object, Exception) and String error_image(Object, Exception) respectively.
5.2.1. ProposalProvider
public void complete[TypeName]_[FeatureName]( EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // clients may override } public void complete_[RuleName]( EObject model, RuleCall ruleCall, 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
Xtext 0.7
41
IDE concepts
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. 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 specialized parameters. 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 0.7
42
IDE concepts
By default Xtext registers ContextTypes for each Rule ( .[RuleName]) and for each keyword ( .kw_[keyword]), as long as the keywords are valid identifiers. If you dont like these defaults youll 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.
yields the text event => state and allows selecting any events and states using a drop down.
Xtext 0.7
43
IDE concepts
For example the following template (taken from the domainmodel example):
<template name="Operation" description="template for an Operation" id="org.eclipse.xtext.example.Domainmodel.Operation" context="org.eclipse.xtext.example.Domainmodel.Operation" enabled="true"> ${visibility:Enum('Visibility')} op ${name}(${cursor}): ${type:CrossReference('Operation.type')} </template>
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 Visibility EENumeration. Also, name and type are placeholders.
Xtext 0.7
44
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 0.7
45
IDE concepts
public class MyDslTransformer extends AbstractDeclarativeSemanticModelTransformer { /** * This method will be called by naming convention: * - method name must be createNode * - first param: subclass of EObject * - second param: ContentOutlineNode */ public ContentOutlineNode createNode( Attribute semanticNode, ContentOutlineNode parentNode) { ContentOutlineNode node = super.newOutlineNode(semanticNode, parentNode); node.setLabel("special " + node.getLabel()); return node; } public ContentOutlineNode createNode( Property semanticNode, ContentOutlineNode parentNode) { ContentOutlineNode node = super.newOutlineNode(semanticNode, parentNode); node.setLabel("pimped " + node.getLabel()); return node; } /** * 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(); } public List<EObject> getChildren(Property property) { return NO_CHILDREN; } }
To make sure Xtext picks up your new outline transformer, you have to register your implementation with your UI module:
public class MyDslUiModule extends AbstractMyDslUiModule { @Override public Class<? extends ISemanticModelTransformer> bindISemanticModelTransformer() { return MyDslTransformer.class; } ... }
5.4.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 0.7
46
IDE concepts
public class MyDslUiModule extends AbstractMyDslUiModule { @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 { public FilterFooAction(XtextContentOutlinePage outlinePage) { super("Filter Foo", outlinePage); setToolTipText("Show / hide foo"); setDescription("Show / hide foo"); setImageDescriptor(Activator.getImageDescriptor("icons/foo.gif")); setDisabledImageDescriptor( Activator.getImageDescriptor("icons/foo.gif")); } @Override protected String getToggleId() { return "FilterFooAction.isChecked"; } @Override protected ViewerFilter createFilter() { return new FooOutlineFilter(); } }
Xtext 0.7
47
IDE concepts
Register this class with your MyDslUiModule to make it available to your DSL editor:
public class MyDslUiModule extends AbstractMyDslUiModule { ... public Class<? extends IContentOutlineNodeAdapterFactory> bindIContentOutlineNodeAdapterFactory() { return org.example.myDSLContentOutlineNodeAdapterFactory.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.
Xtext 0.7
48
IDE concepts
Again, pay attention to the commandId attribute. The connection between your node type(s) and the menu contribution is made by the part <adapt type="org.example.mydsl.Attribute" />.
5.5. Hyperlinking
The Xtext editor provides hyperlinking support for any tokens corresponding to cross references in your grammar definition. This means that you can either control-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 youd 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.
Xtext 0.7
49
IDE concepts
public class MyDslUiModule extends AbstractMyDslUiModule { @Override public Class<? extends ILocationInFileProvider> bindILocationInFileProvider() { return MyDslLocationInFileProvider.class; } ... }
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).
Xtext 0.7
50
IDE concepts
The formatter has to implement the method configureFormatting(...) which is supposed to declaratively set up a FormattingConfig. The FormattingConfig consist general settings and a set of rules:
Xtext 0.7
51
IDE concepts
possible to use different colors and fonts according to the meaning of the different parts of your input file. One may want to use some decent colors for large blocks of comment while identifiers, keywords and strings should be colored differently to make it easier to distinguish between them. This kind of text decorating mark-up does not influence the semantics of the various sections but helps to understand the meaning and to find errors in the source code.
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 0.7
52
IDE concepts
public class DefaultLexicalHighlightingConfiguration implements ILexicalHighlightingConfiguration { public static final String KEYWORD_ID = "keyword"; public static final String COMMENT_ID = "comment"; public void configure(IHighlightingConfigurationAcceptor acceptor) { acceptor.acceptDefaultHighlighting(KEYWORD_ID, "Keyword", keywordTextStyle()); acceptor.acceptDefaultHighlighting(COMMENT_ID, "Comment", // ... // ... } public TextStyle keywordTextStyle() { TextStyle textStyle = new TextStyle(); textStyle.setColor(new RGB(127, 0, 85)); textStyle.setStyle(SWT.BOLD); return textStyle; } // ... }
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 efficiently 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 0.7
53
IDE concepts
public void provideHighlightingFor(XtextResource resource, IHighlightedPositionAcceptor acceptor) { if (resource == null) return; Iterable<AbstractNode> allNodes = NodeUtil.getAllContents( resource.getParseResult().getRootNode()); for (AbstractNode abstractNode : allNodes) { if (abstractNode.getGrammarElement() instanceof CrossReference) { acceptor.addPosition(node.getOffset(), node.getLength(), SemanticHighlightingConfiguration.CROSS_REF); } } }
This example refers to an implementation of the ISemanticHighlightingConfiguration that registers a style for a cross reference. It is pretty much the same implementation as for the previously mentioned sample of an ILexicalHighlightingConfiguration.
public class SemanticHighlightingConfiguration implements ISemanticHighlightingConfiguration { public final static String CROSS_REF = "CrossReference"; public void configure(IHighlightingConfigurationAcceptor acceptor) { acceptor.acceptDefaultHighlighting(CROSS_REF, "Cross References", crossReferenceTextStyle()); } public TextStyle crossReferenceTextStyle() { TextStyle textStyle = new TextStyle(); textStyle.setStyle(SWT.ITALIC); return textStyle; } }
The implementor of an ISemanticHighlightingCalculator should be aware of performance to ensure a good user experience. It is probably not a good idea to traverse everything of your model when you will only register a few highlighted ranges that can be found easier with some typed method calls. It is strongly advised to use purposeful ways to navigate your model. The parts of Xtexts core that are responsible for the semantic highlighting are pretty optimized in this regard as well. The framework will only update the ranges that actually have been altered, for example. This optimizes the redraw process. It will even move, shrink or enlarge previously announced regions based on a best guess before the next semantic highlighting pass has been triggered after the user has changed the document.
Xtext 0.7
54
Xtext 0.7
55
manage to come up with a good compatibility layer. So this is where most of the migration effort will go into if implemented customized linking. But we think the notion of scopes is such a valuable addition that it is worth the refactoring. Also, when looking at existing oAW Xtext projects we found that most projects either didnt change the default linking that much or they came up with their own linking framework anyway. However, if we have completely misunderstood the situation and your oAW Xtext project cannot be migrated in a reasonable amount of time, please tell us. We want to help you!
Xtext 0.7
56
as well. Additionally, the use of Google Collections reduces the pain when navigating over your model to extract information. With these techniques an ILabelProvider that handles your own EClasses Property and Entity can be written like this:
public class DomainModelLabelProvider extends DefaultLabelProvider { String label(Entity e) { return e.getName(); } String image(Property p) { return p.isMultiValue() ? "complexProperty.gif": "simpleProperty.gif"; } String image(Entity e) { return "entity.gif"; } }
As you can see this is very similar to the way one describes labels and icons in oAW Xtext, but has the advantage that it is easier to test and to debug, faster and can be used everywhere an ILabelProvider is expected in Eclipse.
6.3.4. Conclusion
Just to get it right, Xtend is a very powerful language and we still use it for its main purpose: code generation and model transformation. The whole generator in TMF Xtext is written in Xpand and Xtend and its performance is at least in our experience sufficient for that use case. Actually we were able to increase the runtime performance of Xpand by about 60% for the Galileo release of M2T Xpand. But still, live execution in the IDE and on typing is very critical and one has to think about every millisecond in this area. As an alternative to the Java APIs we also considered other JVM languages. We like static typing and think it is especially important when processing typed models (which evolve heavily). Thats why Groovy or JRuby were no alternatives. Using Scala would have been a very good match, but we didnt want to require knowledge of Scala so we didnt use it and stuck to Java.
6.4. Differences
In this section differences between oAW Xtext and TMF Xtext are outlined and explained. Well start from the APIs such as the grammar language and the validation and finish with the different hooks for customizing linking and several UI aspects, such as outline view and content assist. Well also try to map some of the oAW Xtext concepts to their counterparts in TMF Xtext.
In oAW Xtext this information was provided through the generator (actually it is contained in the *.properties file) but we found that these things are very important for a complete description of a
Xtext 0.7
57
grammar. Therefore we made that information becoming a part of the grammar language in order to have self-describing grammars and allow for sophisticated static analysis, etc.. Apart from the first two lines the grammar languages of both versions are more or less compatible. The syntax for all the different EBNF concepts (alternatives, groups, cardinalities) is similar. Also assignments are syntactically and semantically identical in both versions. However in TMF Xtext some concepts have been generalized and improved:
becomes
enum MyEnum : foo='foo' | bar='bar';
and because the name of the literal equals the literal value one can omit the right-hand side in this case and write:
enum MyEnum : foo | bar;
becomes
terminal FOO : 'f' 'o' 'o';
See the reference documentation for all the different expressions possible in terminal rules.
Xtext 0.7
58
Although this changes your Ecore model, one usually never used this reference explicitly as it was only there to be used by the default import mechanism. So we assume and hope that changing the reference is not a big deal for you.
This is a bit more verbose, but at the same time more readable. And as you dont have to write the return type in most situations, its good to have a more explicit, readable syntax.
6.4.2.2. Migration
We expect the migration of linking to be very simple if youve not changed the default semantics that much. Weve already migrated a couple of projects and it wasnt too hard to do so. If you have changed
Xtext 0.7
59
linking (and also content assist) a lot, youll have to translate the semantics to the IScopeProvider concept. This might be a bit of work, but it is worth the effort as this will clean up your code base and better separate concerns.
Xtext 0.7
60
Please note that when using Xtext models for code generation the checks of all three categories will be performed. Beside this it is now possible to add information about the feature which is validated.
context Entity#name ERROR "Name should start with a capital "+this.name+"." : this.name.toFirstUpper() == this.name;
If you add the name of a feature prepended by a hash (#) in Check, the editor will only mark the value of the feature (name), not the whole object (Entity). Both concepts, control over validation time as well as pointing to a specific feature, complement one another in Check and Java based validation.
Xtext 0.7
61
Xtext 0.7
62