SlideShare a Scribd company logo
1 of 32
Download to read offline
Xtext Grammar Language
Jan Köhnlein
2014, Kiel
grammar org.xtextcon.Statemachine 	
with org.eclipse.xtext.common.Terminals	
!
generate statemachine 	
"http://www.xtextcon.org/Statemachine"	
!
Statemachine:	
name=STRING	
elements+=Element*;	
!
Element:	
	 Event | State;	
	 	
Event:	
	 name=ID description=STRING?;	
!
State:	
	 'state' name=ID	
	 transitions+=Transition*;	
!
Transition:	
	 event=[Event] '=>' state=[State];
Precedences
Action, Assignment, Keyword, 

RuleCall, Parenthesized
Cardinalities *, +, ?

Predicates =>, ->
Group <blank>
Unordered Group &
Alternative |
AssignmentFirst:	
	 name=ID?;	
//	(name=ID)?;	
!
CardinalityFirst:	
	 'a' 'b'?;	
//	'a' ('b'?);	
!
PredicateFirst:	
	 =>'a' 'b';	
//	(=>'a') 'b';	
!
GroupFirst:	
	 'a' | 'b' 'c';	
//	'a' | ('b' 'c');
Syntactic Aspects
grammar org.xtextcon.Statemachine 	
with org.eclipse.xtext.common.Terminals	
!
generate statemachine 	
"http://www.xtextcon.org/Statemachine"	
!
Statemachine:	
name=STRING	
	 ('events' events+=Event+)?	
	 states+=State*;	
!
Event:	
	 name=ID description=STRING?;	
!
State:	
	 'state' name=ID	
	 transitions+=Transition*;	
!
Transition:	
	 event=[Event|ID] '=>' state=[State|ID];
Lexing
Lexer
Splits document text into tokens
Works before and independent of the parser
Token matching
First match wins
Precedence
All keywords
Local terminal rules
Terminal rules from super grammar
As last resort you can define a custom lexer
Lexing
// Examplen	
’Lamp’	
n	
events button_pressed	
n	
state on	
nt	
button_pressed => off	
n	
state off	
nt	
button_pressed => light
SL_COMMENT	
STRING 	
WS	
events WS ID 	
WS	
state ID 	
WS	
ID WS => WS ID 	
WS	
state ID 	
WS	
ID WS => WS ID
events

state

=>

ID

STRING

ML_COMMENT

SL_COMMENT	
WS	
ANY_OTHER
Tokens
Token StreamChar Stream
Terminal Rules
grammar org.eclipse.xtext.common.Terminals hidden(WS, ML_COMMENT, SL_COMMENT)	
	 	 	 	 	 	 	 	 	 	 	 	
import "http://www.eclipse.org/emf/2002/Ecore" as ecore	
!
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'|'u'|'"'|"'"|'') | !(''|'"') )* '"' |	
	 	 	 "'" ( '' ('b'|'t'|'n'|'f'|'r'|'u'|'"'|"'"|'') | !(''|"'") )* "'";	
	
terminal ML_COMMENT	: '/*' -> '*/';	
terminal SL_COMMENT : '//' !('n'|'r')* ('r'? 'n')?;	
!
terminal WS	 	 	 : (' '|'t'|'r'|'n')+;	
!
terminal ANY_OTHER	 : .;
Terminals in the Parser
Hidden Terminals
Are ignored by the parser inside the respective scope
Can be defined on grammar or rule level (inherited)



grammar org.eclipse.xtext.common.Terminals 

hidden(WS, ML_COMMENT, SL_COMMENT)
or on parser rules



QualifiedName hidden(): // strictly no whitespace	
ID ('.' ID)*;
Datatype Rules
Return a value (instead of an EObject)
Are processed by the parser
Superior alternative to terminal rules
Examples



Double returns ecore::EDouble hidden():

'-'? INT '.' INT ('e'|'E' '-'? INT)?;



QualifiedName: // returns ecore::EString (default)

ID ('.' ID)*;



ValidID:

ID | 'keyword0' | 'keyword1';
Transforms textual representation to value and back
For terminal and datatype rules
e.g. strips quotes (STRINGValueConverter)

remove leading ^ (IDValueConverter)
EMF defaults are often sufficient (EFactory)
Value Converter
class MyValueConverterService extends AbstractDeclarativeValueConverterService {	
	 	
	 @Inject MyValueConverter myValueConverter;	
!
	 @ValueConverter(rule = "MY_TERMINAL") def MY_TERMINAL() {	
	 	 return myValueConverter	
	 }	
}
Ambiguities
Example
Expression:	
	 If;	
	 	
If:	
	 Variable | 	
	 'if' condition=Expression 	
	 'then' then=Expression 	
	 ('else' else=Expression)?;	
	 	
Variable:	
	 name=ID;
warning(200): ...: Decision can match input such as "'else'" using multiple alternatives: 1, 2	
As a result, alternative(s) 2 were disabled for that input	
warning(200): ...: Decision can match input such as "'else'" using multiple alternatives: 1, 2	
As a result, alternative(s) 2 were disabled for that input
if cond1 then	
if cond2 then 	
foo	
else // dangling	
bar
Ambiguity Analysis
In the workflow, add
!
AntlrWorks www.antlr3.org/works/
fragment = DebugAntlrGeneratorFragment {	
	 options = auto-inject {}	
}
Ambiguity Resolution
Add keywords
Use syntactic predicates:

“If the predicated element matches in the current
decision, decide for it.”
plain

(=>'else' else=Expression)?; 

=>('else' else=Expression)?; // not so good
first-set

->('else' else=Expression)?;
Correspondence to Ecore
grammar org.xtextcon.Statemachine 	
with org.eclipse.xtext.common.Terminals	
!
generate statemachine 	
"http://www.xtextcon.org/Statemachine"	
!
Statemachine returns Statemachine:	
name=STRING	
	 ('events' events+=Event+)?	
	 states+=State*;	
!
Event returns Event:	
	 name=ID description=STRING?;	
!
State returns State:	
	 'state' name=ID	
	 transitions+=Transition*;	
!
Transition returns Transition:	
	 event=[Event|ID] '=>' state=[State|ID];
statemachine
name : String
Statemachine
name : String
Transition
name : String
State
name : String
description: String
Event
*
* *states events
transitions
event1
1
state
Supertypes
... 	
!
Element:	
	 Event | State;	
!
Event returns Event:	
	 name=ID description=STRING?;	
!
State returns State:	
	 'state' name=ID	
	 transitions+=Transition*;	
!
...
description: String
EventState
name : String
Element
name : String
Transition
Common features are promoted to the super type
Dispatcher rule Element needs not to be called
A rule can return a subtype of the specified return type
Imported EPackage
Workflow {	
bean = StandaloneSetup {	
	...	
	registerGeneratedEPackage =

“org.xtextcon.statemachine.StatemachinePackage”	
	registerGenModelFile = 

“platform:/resource/<path-to>/Statemachine.genmodel"	
}	
//generate statemachine "http://www.xtextcon.org/Statemachine"	
import "http://www.xtextcon.org/Statemachine"
AST Creation
EObject Creation
The current pointer
Points to the EObject returned by a parser rule call
Is set to null when entering the rule
On the first assignment the EObject is created and
assigned to current
Further assignments go to current
EObject Creation
Type :	
(Class | DataType) 'is' visibility=('public' |'private');	
	
DataType :	
'datatype' name=ID;	
	
Class :	
'class' name=ID;
datatype A is public
Type current = null;	
current = new DataType();	
current.setName(“A”);	
current.setVisibility(“public”);	
return current;
Actions
Alternative without assignment -> no returned object





Actions make sure an EObject is created
Specified type must be compatible with return type
Created element is assigned to current
BooleanLiteral:	
	 value?='true' | 'false';
BooleanLiteral returns Expression:	
	 {BooleanLiteral} (value?=‘true’ | ‘false');
The rule 'BooleanLiteral' may be consumed without object instantiation.
Add an action to ensure object creation, e.g. '{BooleanLiteral}'.
Left Recursion
Expression :	
  Expression '+' Expression |	
  Number;	
!
Number :	
value = INT;
The rule 'Expression' is left recursive.
Left Factoring
Expression:	
{Addition} left=Number ('+' right=Number)*;	
	
Number:	
value = INT;
1
// model	
Addition {	
	 left = Number {	
	 	 value = 1	
}	
}
Assigned Action
Addition returns Expression:	
Number ({Sum.left = current} '+' right=Number)*;	
	
Number:	
value = INT;
1
Expression current = null;	
current = new Number();	
current.setValue(1);	
return current;
// model	
Number {	
	 value = 1	
}
Assigned Action II
Addition returns Expression:	
Number ({Sum.left = current} '+' right=Number)*;	
	
Number:	
value = INT;
1 + 2
Expression current = null;	
current = new Number();	
current.setValue(1);	
Expression temp = new Sum();	
temp.setLeft(current);	
current = temp;	
…	
current.right = <second Number>;	
return current;
// model	
Addition {	
	 left = Number {	
	 	 value = 1	
}	
	 right = Number {	
	 	 value = 2	
	 }	
}
Assigned Action III
Creates a new element
makes it the parent of current
and sets current to it
Needed
normalizing left-factored grammars
infix operators
Best Practices
Best Practices
Use nsURIs for imported EPackages
Prefer datatype rules to terminal rules
Use syntactic predicates instead of backtracking
Be sloppy in the grammar but strict in validation

More Related Content

What's hot

Jetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on AndroidJetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on AndroidNelson Glauber Leal
 
The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)Scott Wlaschin
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with XtextHolger Schill
 
Compose Camp - Jetpack Compose for Android Developers Introduction Session De...
Compose Camp - Jetpack Compose for Android Developers Introduction Session De...Compose Camp - Jetpack Compose for Android Developers Introduction Session De...
Compose Camp - Jetpack Compose for Android Developers Introduction Session De...JassGroup TICS
 
Xtext beyond the defaults - how to tackle performance problems
Xtext beyond the defaults -  how to tackle performance problemsXtext beyond the defaults -  how to tackle performance problems
Xtext beyond the defaults - how to tackle performance problemsHolger Schill
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeRamon Ribeiro Rabello
 
Building Reusable SwiftUI Components
Building Reusable SwiftUI ComponentsBuilding Reusable SwiftUI Components
Building Reusable SwiftUI ComponentsPeter Friese
 
Xtext's new Formatter API
Xtext's new Formatter APIXtext's new Formatter API
Xtext's new Formatter APImeysholdt
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Building Your Own DSL with Xtext
Building Your Own DSL with XtextBuilding Your Own DSL with Xtext
Building Your Own DSL with XtextGlobalLogic Ukraine
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Scott Wlaschin
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch APIXcat Liu
 
Serializing EMF models with Xtext
Serializing EMF models with XtextSerializing EMF models with Xtext
Serializing EMF models with Xtextmeysholdt
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy stepsprince Loffar
 
Hello, ReactorKit 
Hello, ReactorKit Hello, ReactorKit 
Hello, ReactorKit Suyeol Jeon
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hookPiyush Jamwal
 

What's hot (20)

Jetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on AndroidJetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on Android
 
The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)
 
Scoping
ScopingScoping
Scoping
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
Using Xcore with Xtext
Using Xcore with XtextUsing Xcore with Xtext
Using Xcore with Xtext
 
Compose Camp - Jetpack Compose for Android Developers Introduction Session De...
Compose Camp - Jetpack Compose for Android Developers Introduction Session De...Compose Camp - Jetpack Compose for Android Developers Introduction Session De...
Compose Camp - Jetpack Compose for Android Developers Introduction Session De...
 
Xtext beyond the defaults - how to tackle performance problems
Xtext beyond the defaults -  how to tackle performance problemsXtext beyond the defaults -  how to tackle performance problems
Xtext beyond the defaults - how to tackle performance problems
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
 
Building Reusable SwiftUI Components
Building Reusable SwiftUI ComponentsBuilding Reusable SwiftUI Components
Building Reusable SwiftUI Components
 
Xtext's new Formatter API
Xtext's new Formatter APIXtext's new Formatter API
Xtext's new Formatter API
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Building Your Own DSL with Xtext
Building Your Own DSL with XtextBuilding Your Own DSL with Xtext
Building Your Own DSL with Xtext
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 
Serializing EMF models with Xtext
Serializing EMF models with XtextSerializing EMF models with Xtext
Serializing EMF models with Xtext
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy steps
 
Hello, ReactorKit 
Hello, ReactorKit Hello, ReactorKit 
Hello, ReactorKit 
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
 

Viewers also liked

Parsing Expression With Xtext
Parsing Expression With XtextParsing Expression With Xtext
Parsing Expression With XtextSven Efftinge
 
Recipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with XtendRecipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with XtendKarsten Thoms
 
Xtend - A Language Made for Java Developers
Xtend - A Language Made for Java DevelopersXtend - A Language Made for Java Developers
Xtend - A Language Made for Java DevelopersSebastian Zarnekow
 
Graphical Views For Xtext With FXDiagram
Graphical Views For Xtext With FXDiagramGraphical Views For Xtext With FXDiagram
Graphical Views For Xtext With FXDiagramDr. Jan Köhnlein
 
Jazoon 2010 - Building DSLs with Eclipse
Jazoon 2010 - Building DSLs with EclipseJazoon 2010 - Building DSLs with Eclipse
Jazoon 2010 - Building DSLs with EclipsePeter Friese
 
Eclipse DemoCamp in Paris: Language Development with Xtext
Eclipse DemoCamp in Paris: Language Development with XtextEclipse DemoCamp in Paris: Language Development with Xtext
Eclipse DemoCamp in Paris: Language Development with XtextSebastian Zarnekow
 
Enhancing Xtext for General Purpose Languages
Enhancing Xtext for General Purpose LanguagesEnhancing Xtext for General Purpose Languages
Enhancing Xtext for General Purpose LanguagesUniversity of York
 
ARText - Driving Developments with Xtext
ARText - Driving Developments with XtextARText - Driving Developments with Xtext
ARText - Driving Developments with XtextSebastian Benz
 
From Stairway to Heaven onto the Highway to Hell with Xtext
From Stairway to Heaven onto the Highway to Hell with XtextFrom Stairway to Heaven onto the Highway to Hell with Xtext
From Stairway to Heaven onto the Highway to Hell with XtextKarsten Thoms
 
Language Engineering With Xtext
Language Engineering With XtextLanguage Engineering With Xtext
Language Engineering With XtextSven Efftinge
 
Pragmatic DSL Design with Xtext, Xbase and Xtend 2
Pragmatic DSL Design with Xtext, Xbase and Xtend 2Pragmatic DSL Design with Xtext, Xbase and Xtend 2
Pragmatic DSL Design with Xtext, Xbase and Xtend 2Dr. Jan Köhnlein
 
Codegeneration Goodies
Codegeneration GoodiesCodegeneration Goodies
Codegeneration Goodiesmeysholdt
 
Executable specifications for xtext
Executable specifications for xtextExecutable specifications for xtext
Executable specifications for xtextmeysholdt
 

Viewers also liked (20)

Parsing Expression With Xtext
Parsing Expression With XtextParsing Expression With Xtext
Parsing Expression With Xtext
 
Recipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with XtendRecipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with Xtend
 
EMF - Beyond The Basics
EMF - Beyond The BasicsEMF - Beyond The Basics
EMF - Beyond The Basics
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
Xtend - A Language Made for Java Developers
Xtend - A Language Made for Java DevelopersXtend - A Language Made for Java Developers
Xtend - A Language Made for Java Developers
 
DSLs for Java Developers
DSLs for Java DevelopersDSLs for Java Developers
DSLs for Java Developers
 
Graphical Views For Xtext With FXDiagram
Graphical Views For Xtext With FXDiagramGraphical Views For Xtext With FXDiagram
Graphical Views For Xtext With FXDiagram
 
Graphical Views For Xtext
Graphical Views For XtextGraphical Views For Xtext
Graphical Views For Xtext
 
Jazoon 2010 - Building DSLs with Eclipse
Jazoon 2010 - Building DSLs with EclipseJazoon 2010 - Building DSLs with Eclipse
Jazoon 2010 - Building DSLs with Eclipse
 
Eclipse DemoCamp in Paris: Language Development with Xtext
Eclipse DemoCamp in Paris: Language Development with XtextEclipse DemoCamp in Paris: Language Development with Xtext
Eclipse DemoCamp in Paris: Language Development with Xtext
 
Enhancing Xtext for General Purpose Languages
Enhancing Xtext for General Purpose LanguagesEnhancing Xtext for General Purpose Languages
Enhancing Xtext for General Purpose Languages
 
ARText - Driving Developments with Xtext
ARText - Driving Developments with XtextARText - Driving Developments with Xtext
ARText - Driving Developments with Xtext
 
From Stairway to Heaven onto the Highway to Hell with Xtext
From Stairway to Heaven onto the Highway to Hell with XtextFrom Stairway to Heaven onto the Highway to Hell with Xtext
From Stairway to Heaven onto the Highway to Hell with Xtext
 
Xtext, diagrams and ux
Xtext, diagrams and uxXtext, diagrams and ux
Xtext, diagrams and ux
 
What's Cooking in Xtext 2.0
What's Cooking in Xtext 2.0What's Cooking in Xtext 2.0
What's Cooking in Xtext 2.0
 
Language Engineering With Xtext
Language Engineering With XtextLanguage Engineering With Xtext
Language Engineering With Xtext
 
Scoping Tips and Tricks
Scoping Tips and TricksScoping Tips and Tricks
Scoping Tips and Tricks
 
Pragmatic DSL Design with Xtext, Xbase and Xtend 2
Pragmatic DSL Design with Xtext, Xbase and Xtend 2Pragmatic DSL Design with Xtext, Xbase and Xtend 2
Pragmatic DSL Design with Xtext, Xbase and Xtend 2
 
Codegeneration Goodies
Codegeneration GoodiesCodegeneration Goodies
Codegeneration Goodies
 
Executable specifications for xtext
Executable specifications for xtextExecutable specifications for xtext
Executable specifications for xtext
 

Similar to The Xtext Grammar Language

Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationIvan Dolgushin
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxpriestmanmable
 
IntroToCSharpcode.ppt
IntroToCSharpcode.pptIntroToCSharpcode.ppt
IntroToCSharpcode.pptpsundarau
 
Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using RoomNelson Glauber Leal
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the ASTJarrod Overson
 
Scala in practice
Scala in practiceScala in practice
Scala in practicepatforna
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Heiko Behrens
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1saydin_soft
 
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdfjavascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdfAlexShon3
 
ActionScript3 collection query API proposal
ActionScript3 collection query API proposalActionScript3 collection query API proposal
ActionScript3 collection query API proposalSlavisa Pokimica
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScriptryanstout
 

Similar to The Xtext Grammar Language (20)

Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
 
Controle de estado
Controle de estadoControle de estado
Controle de estado
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
 
IntroToCSharpcode.ppt
IntroToCSharpcode.pptIntroToCSharpcode.ppt
IntroToCSharpcode.ppt
 
Java Script Workshop
Java Script WorkshopJava Script Workshop
Java Script Workshop
 
Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using Room
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
 
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdfjavascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
 
ActionScript3 collection query API proposal
ActionScript3 collection query API proposalActionScript3 collection query API proposal
ActionScript3 collection query API proposal
 
Json
JsonJson
Json
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
Why Our Code Smells
Why Our Code SmellsWhy Our Code Smells
Why Our Code Smells
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
 

More from Dr. Jan Köhnlein

The Eclipse Layout Kernel sirius con 2017
The Eclipse Layout Kernel   sirius con 2017The Eclipse Layout Kernel   sirius con 2017
The Eclipse Layout Kernel sirius con 2017Dr. Jan Köhnlein
 
A New Approach Towards Web-based IDEs
A New Approach Towards Web-based IDEsA New Approach Towards Web-based IDEs
A New Approach Towards Web-based IDEsDr. Jan Köhnlein
 
Diagram Editors - The FXed Generation
Diagram Editors - The FXed GenerationDiagram Editors - The FXed Generation
Diagram Editors - The FXed GenerationDr. Jan Köhnlein
 
Eclipse Diagram Editors - An Endangered Species
Eclipse Diagram Editors - An Endangered SpeciesEclipse Diagram Editors - An Endangered Species
Eclipse Diagram Editors - An Endangered SpeciesDr. Jan Köhnlein
 
A fresh look at graphical editing
A fresh look at graphical editingA fresh look at graphical editing
A fresh look at graphical editingDr. Jan Köhnlein
 
A fresh look at graphical editing
A fresh look at graphical editingA fresh look at graphical editing
A fresh look at graphical editingDr. Jan Köhnlein
 
A fresh look at graphical editing
A fresh look at graphical editingA fresh look at graphical editing
A fresh look at graphical editingDr. Jan Köhnlein
 
Android tutorial - Xtext slides
Android tutorial - Xtext slidesAndroid tutorial - Xtext slides
Android tutorial - Xtext slidesDr. Jan Köhnlein
 
Combining Text and Graphics in Eclipse-based Modeling Tools
Combining Text and Graphics in Eclipse-based Modeling ToolsCombining Text and Graphics in Eclipse-based Modeling Tools
Combining Text and Graphics in Eclipse-based Modeling ToolsDr. Jan Köhnlein
 
Combining Graphical and Textual
Combining Graphical and TextualCombining Graphical and Textual
Combining Graphical and TextualDr. Jan Köhnlein
 
Domain Specific Languages With Eclipse Modeling
Domain Specific Languages With Eclipse ModelingDomain Specific Languages With Eclipse Modeling
Domain Specific Languages With Eclipse ModelingDr. Jan Köhnlein
 
Domänenspezifische Sprachen mit Xtext
Domänenspezifische Sprachen mit XtextDomänenspezifische Sprachen mit Xtext
Domänenspezifische Sprachen mit XtextDr. Jan Köhnlein
 

More from Dr. Jan Köhnlein (20)

The Eclipse Layout Kernel sirius con 2017
The Eclipse Layout Kernel   sirius con 2017The Eclipse Layout Kernel   sirius con 2017
The Eclipse Layout Kernel sirius con 2017
 
A New Approach Towards Web-based IDEs
A New Approach Towards Web-based IDEsA New Approach Towards Web-based IDEs
A New Approach Towards Web-based IDEs
 
Responsiveness
ResponsivenessResponsiveness
Responsiveness
 
Getting rid of backtracking
Getting rid of backtrackingGetting rid of backtracking
Getting rid of backtracking
 
XRobots
XRobotsXRobots
XRobots
 
Diagrams, Xtext and UX
Diagrams, Xtext and UXDiagrams, Xtext and UX
Diagrams, Xtext and UX
 
Diagram Editors - The FXed Generation
Diagram Editors - The FXed GenerationDiagram Editors - The FXed Generation
Diagram Editors - The FXed Generation
 
Code Generation With Xtend
Code Generation With XtendCode Generation With Xtend
Code Generation With Xtend
 
Eclipse Diagram Editors - An Endangered Species
Eclipse Diagram Editors - An Endangered SpeciesEclipse Diagram Editors - An Endangered Species
Eclipse Diagram Editors - An Endangered Species
 
Java DSLs with Xtext
Java DSLs with XtextJava DSLs with Xtext
Java DSLs with Xtext
 
A fresh look at graphical editing
A fresh look at graphical editingA fresh look at graphical editing
A fresh look at graphical editing
 
A fresh look at graphical editing
A fresh look at graphical editingA fresh look at graphical editing
A fresh look at graphical editing
 
A fresh look at graphical editing
A fresh look at graphical editingA fresh look at graphical editing
A fresh look at graphical editing
 
Android tutorial - Xtext slides
Android tutorial - Xtext slidesAndroid tutorial - Xtext slides
Android tutorial - Xtext slides
 
Eclipse meets e4
Eclipse meets e4Eclipse meets e4
Eclipse meets e4
 
Combining Text and Graphics in Eclipse-based Modeling Tools
Combining Text and Graphics in Eclipse-based Modeling ToolsCombining Text and Graphics in Eclipse-based Modeling Tools
Combining Text and Graphics in Eclipse-based Modeling Tools
 
Combining Graphical and Textual
Combining Graphical and TextualCombining Graphical and Textual
Combining Graphical and Textual
 
Domain Specific Languages With Eclipse Modeling
Domain Specific Languages With Eclipse ModelingDomain Specific Languages With Eclipse Modeling
Domain Specific Languages With Eclipse Modeling
 
Domänenspezifische Sprachen mit Xtext
Domänenspezifische Sprachen mit XtextDomänenspezifische Sprachen mit Xtext
Domänenspezifische Sprachen mit Xtext
 
Workshop On Xtext
Workshop On XtextWorkshop On Xtext
Workshop On Xtext
 

Recently uploaded

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 

Recently uploaded (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 

The Xtext Grammar Language

  • 1. Xtext Grammar Language Jan Köhnlein 2014, Kiel
  • 2. grammar org.xtextcon.Statemachine with org.eclipse.xtext.common.Terminals ! generate statemachine "http://www.xtextcon.org/Statemachine" ! Statemachine: name=STRING elements+=Element*; ! Element: Event | State; Event: name=ID description=STRING?; ! State: 'state' name=ID transitions+=Transition*; ! Transition: event=[Event] '=>' state=[State];
  • 3. Precedences Action, Assignment, Keyword, 
 RuleCall, Parenthesized Cardinalities *, +, ?
 Predicates =>, -> Group <blank> Unordered Group & Alternative | AssignmentFirst: name=ID?; // (name=ID)?; ! CardinalityFirst: 'a' 'b'?; // 'a' ('b'?); ! PredicateFirst: =>'a' 'b'; // (=>'a') 'b'; ! GroupFirst: 'a' | 'b' 'c'; // 'a' | ('b' 'c');
  • 5. grammar org.xtextcon.Statemachine with org.eclipse.xtext.common.Terminals ! generate statemachine "http://www.xtextcon.org/Statemachine" ! Statemachine: name=STRING ('events' events+=Event+)? states+=State*; ! Event: name=ID description=STRING?; ! State: 'state' name=ID transitions+=Transition*; ! Transition: event=[Event|ID] '=>' state=[State|ID];
  • 7. Lexer Splits document text into tokens Works before and independent of the parser Token matching First match wins Precedence All keywords Local terminal rules Terminal rules from super grammar As last resort you can define a custom lexer
  • 8. Lexing // Examplen ’Lamp’ n events button_pressed n state on nt button_pressed => off n state off nt button_pressed => light SL_COMMENT STRING WS events WS ID WS state ID WS ID WS => WS ID WS state ID WS ID WS => WS ID events
 state
 =>
 ID
 STRING
 ML_COMMENT
 SL_COMMENT WS ANY_OTHER Tokens Token StreamChar Stream
  • 9. Terminal Rules grammar org.eclipse.xtext.common.Terminals hidden(WS, ML_COMMENT, SL_COMMENT) import "http://www.eclipse.org/emf/2002/Ecore" as ecore ! 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'|'u'|'"'|"'"|'') | !(''|'"') )* '"' | "'" ( '' ('b'|'t'|'n'|'f'|'r'|'u'|'"'|"'"|'') | !(''|"'") )* "'"; terminal ML_COMMENT : '/*' -> '*/'; terminal SL_COMMENT : '//' !('n'|'r')* ('r'? 'n')?; ! terminal WS : (' '|'t'|'r'|'n')+; ! terminal ANY_OTHER : .;
  • 11. Hidden Terminals Are ignored by the parser inside the respective scope Can be defined on grammar or rule level (inherited)
 
 grammar org.eclipse.xtext.common.Terminals 
 hidden(WS, ML_COMMENT, SL_COMMENT) or on parser rules
 
 QualifiedName hidden(): // strictly no whitespace ID ('.' ID)*;
  • 12. Datatype Rules Return a value (instead of an EObject) Are processed by the parser Superior alternative to terminal rules Examples
 
 Double returns ecore::EDouble hidden():
 '-'? INT '.' INT ('e'|'E' '-'? INT)?;
 
 QualifiedName: // returns ecore::EString (default)
 ID ('.' ID)*;
 
 ValidID:
 ID | 'keyword0' | 'keyword1';
  • 13. Transforms textual representation to value and back For terminal and datatype rules e.g. strips quotes (STRINGValueConverter)
 remove leading ^ (IDValueConverter) EMF defaults are often sufficient (EFactory) Value Converter class MyValueConverterService extends AbstractDeclarativeValueConverterService { @Inject MyValueConverter myValueConverter; ! @ValueConverter(rule = "MY_TERMINAL") def MY_TERMINAL() { return myValueConverter } }
  • 15. Example Expression: If; If: Variable | 'if' condition=Expression 'then' then=Expression ('else' else=Expression)?; Variable: name=ID; warning(200): ...: Decision can match input such as "'else'" using multiple alternatives: 1, 2 As a result, alternative(s) 2 were disabled for that input warning(200): ...: Decision can match input such as "'else'" using multiple alternatives: 1, 2 As a result, alternative(s) 2 were disabled for that input if cond1 then if cond2 then foo else // dangling bar
  • 16. Ambiguity Analysis In the workflow, add ! AntlrWorks www.antlr3.org/works/ fragment = DebugAntlrGeneratorFragment { options = auto-inject {} }
  • 17. Ambiguity Resolution Add keywords Use syntactic predicates:
 “If the predicated element matches in the current decision, decide for it.” plain
 (=>'else' else=Expression)?; 
 =>('else' else=Expression)?; // not so good first-set
 ->('else' else=Expression)?;
  • 19. grammar org.xtextcon.Statemachine with org.eclipse.xtext.common.Terminals ! generate statemachine "http://www.xtextcon.org/Statemachine" ! Statemachine returns Statemachine: name=STRING ('events' events+=Event+)? states+=State*; ! Event returns Event: name=ID description=STRING?; ! State returns State: 'state' name=ID transitions+=Transition*; ! Transition returns Transition: event=[Event|ID] '=>' state=[State|ID]; statemachine name : String Statemachine name : String Transition name : String State name : String description: String Event * * *states events transitions event1 1 state
  • 20. Supertypes ... ! Element: Event | State; ! Event returns Event: name=ID description=STRING?; ! State returns State: 'state' name=ID transitions+=Transition*; ! ... description: String EventState name : String Element name : String Transition Common features are promoted to the super type Dispatcher rule Element needs not to be called A rule can return a subtype of the specified return type
  • 21. Imported EPackage Workflow { bean = StandaloneSetup { ... registerGeneratedEPackage =
 “org.xtextcon.statemachine.StatemachinePackage” registerGenModelFile = 
 “platform:/resource/<path-to>/Statemachine.genmodel" } //generate statemachine "http://www.xtextcon.org/Statemachine" import "http://www.xtextcon.org/Statemachine"
  • 23. EObject Creation The current pointer Points to the EObject returned by a parser rule call Is set to null when entering the rule On the first assignment the EObject is created and assigned to current Further assignments go to current
  • 24. EObject Creation Type : (Class | DataType) 'is' visibility=('public' |'private'); DataType : 'datatype' name=ID; Class : 'class' name=ID; datatype A is public Type current = null; current = new DataType(); current.setName(“A”); current.setVisibility(“public”); return current;
  • 25. Actions Alternative without assignment -> no returned object
 
 
 Actions make sure an EObject is created Specified type must be compatible with return type Created element is assigned to current BooleanLiteral: value?='true' | 'false'; BooleanLiteral returns Expression: {BooleanLiteral} (value?=‘true’ | ‘false'); The rule 'BooleanLiteral' may be consumed without object instantiation. Add an action to ensure object creation, e.g. '{BooleanLiteral}'.
  • 27. Left Factoring Expression: {Addition} left=Number ('+' right=Number)*; Number: value = INT; 1 // model Addition { left = Number { value = 1 } }
  • 28. Assigned Action Addition returns Expression: Number ({Sum.left = current} '+' right=Number)*; Number: value = INT; 1 Expression current = null; current = new Number(); current.setValue(1); return current; // model Number { value = 1 }
  • 29. Assigned Action II Addition returns Expression: Number ({Sum.left = current} '+' right=Number)*; Number: value = INT; 1 + 2 Expression current = null; current = new Number(); current.setValue(1); Expression temp = new Sum(); temp.setLeft(current); current = temp; … current.right = <second Number>; return current; // model Addition { left = Number { value = 1 } right = Number { value = 2 } }
  • 30. Assigned Action III Creates a new element makes it the parent of current and sets current to it Needed normalizing left-factored grammars infix operators
  • 32. Best Practices Use nsURIs for imported EPackages Prefer datatype rules to terminal rules Use syntactic predicates instead of backtracking Be sloppy in the grammar but strict in validation