SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Moritz Eysholdt, itemis AG
Serializing EMF
models with Xtext
Xtextcon 2014!
Kiel, Germany
Agenda
❖ Parsing vs. Serializing!
❖ Use Cases!
❖ Generating vs. Serializing!
❖ Challenges!
❖ The Contract!
❖ Architecture!
❖ Hooks!
❖ Advice
The New and the Old Serializer
org.eclipse.xtext.serializer	
•The New Serializer. This presentation is about it.
org.eclipse.xtext.parsetree.reconstr	
•The Old Serializer. Don’t used it.!
•Cryptic Error Messages!
•Bad Performance for Large Models!
•marked @Deprecated
Parser vs. Serializer
XtextResource
ModelModelTextual!
Model
Parser
Serializer
load()
save()
Parser vs. Serializer
XtextResource
ModelModelTextual!
Model
AST
Parser
Serializer
load()
save()
Use Cases
Quickfix
Refactoring
Non-Textual !
Editors
Non-Textual!
Persistence
Generators
Use Cases
Quickfix
Refactoring
Non-Textual !
Editors
Non-Textual!
Persistence
Generators
Use Cases
Quickfix
Non-Textual !
Editors
Non-Textual!
Persistence
Generators
Refactoring
Use Cases
Quickfix
Non-Textual!
Persistence
Generators
Refactoring
Non-Textual !
Editors
EMF Store
<?XML?>
<?XMI?>
Use Cases
Quickfix
Non-Textual!
Persistence
Generators
Refactoring
Non-Textual !
Editors
Read
Transform
Serialize
Generate, Transpile, Compile, Migrate…
Why Serialize?
❖ object model usually easier to modify than
its textual representation!
❖ guaranteed syntactical correctness!
❖ automatic handling of comments!
❖ automatic handling of whitespace
…when I have Xtend, THE language for generators
When not to Serialize
❖ Avoid serializing models that are broken due
to parse errors.!
❖ Template languages are simpler when
writing out large text chunks that never
change.
The hard Contract
Parsing a serialized Model must result !
in a model equal to the original.
Model original = createModel()	
String serialized = serialize(original)	
Model parsed = parse(serialized)	
assertEqual(original, parsed)
…enables textual models as persistence format
The soft Contract
Serializing a model that has been modified after parsing!
should only change the smallest number of characters necessary.
…keep diffs small
String originalDoc = loadDocument()	
Model parsed = parse(originalDoc)	
Model modified = applyModifications(parsed)	
String newDoc = serialize(modified)	
int numberOfChars = diff(originalDoc, newDoc).size()
1. Keep textual diffs small.!
2. Strictly comply with the semantic model!
3. Loosely comply with the node model
Challenges
❖ unassigned elements!
❖ ambiguous mapping from EStructuralFeatures to Assignments!
❖ ambiguous mapping from EClasses to ParserRules and Actions
…because the AST is actually abstract, as in “lack of information”
API Frontends #1
package org.eclipse.xtext.resource;	
!
public class XtextResource extends ResourceImpl {	
!
	 (…)	
!
	 public void save(Map<?, ?> options) 	
	 	 throws IOException {}	
!
	 public final void save(OutputStream outputStream, Map<?, ?> options) 	
	 	 throws IOException {}	
}
API Frontends #2
package org.eclipse.xtext.serializer;	
!
@ImplementedBy(Serializer.class)	
public interface ISerializer {	
	 public String serialize(EObject obj);	
	 public String serialize(EObject obj, SaveOptions options);	
	 public void serialize(EObject obj, Writer writer, SaveOptions options)	
	 	 throws IOException;	
	 public ReplaceRegion serializeReplacement(EObject obj, SaveOptions options);	
}
Options:!
- format: !
- true: format all!
- false: format regions without whitespace information!
- validate: don’t use, it’s an old algorithm.
Before Serialization
Create one State Machine per Context per EClass
Root:	
	 "optional"? ID children+=(List | Path);	
!
List returns Child:	
	 "list" item+=ID ("," item+=ID)*;	
!
Path returns Child:	
	 "path" seg=ID ({Segment.parent=current} seg=ID)+;
Context EClass
Root Root
List Child
Path Segment
Path_Segment_2_0 Child
Path_Segment_2_0 Segment
During Serialization #1
Find right state machines and !
find right path through them
Root:	
"optional"? ID children+=(List | Path);	
!
List returns Child:	
"list" item+=ID ("," item+=ID)*;
Context EClass
Root Root
Context EClass
List Child
optional Foo list a, b, cOutput:
Architecture #3
Context EClass
Root Root
Context EClass
List Child
Context EClass
Root Root
Context EClass
List Child
Semantic!
assigned grammar elements
Syntactic!
unassigned grammar elements
optional Foo list a, b, cOutput:
Architecture #4: Observer
Semantic!
Sequencer
Syntactic!
Sequencer
HiddenToken!
Sequencer
Formatter Writer
Events
Listens To
assigend!
* RuleCalls!
* Terminals!
* DataTypes!
* Keywords!
* CrossRefs
unassigned!
* RuleCalls!
* Terminals!
* DataTypes!
* Keywords
* whitespace!
* comments
modifies!
whitespace
writes to !
stream
Output: /*X*/ Foo list a
Serializer HiddenTokenSequencerSyntacticSequencerSemanticSequencer
createSequence
(Root, Root)
enter
AssignedParserRuleCall
(children=List)
enter
AssignedParserRuleCall
(children=List)
createSequence
(List, Children)
accept
UnassignedRuleCall
(ID)
accept
AssignedTerminalRuleCall
(itemi=ID)
accept
Keyword
("list")
accept
AssignedTerminalRuleCall
(itemi=ID)
leave
AssignedParserRuleCall
(children=List)
leave
AssignedParserRuleCall
(children=List)
Formatter Writer
enterAssignedParserRuleCall()
acceptWhitespace()
acceptWhitespace()
acceptComment(/*X*/)
acceptUnassignedRuleCall()
acceptKeyword()
acceptWhitespace()
acceptAssignedTerminalRuleCall()
acceptWhitespace()
enterAssignedParserRuleCall()
Root:	
"optional"? ID children+=(List | Path);
List returns Child:	
"list" item+=ID ("," item+=ID)*;
SerializerFragment
fragment = serializer.SerializerFragment auto-inject {	
generateStub = true	
// generateDebugData = true	
}
•SerializerFragment not required to use serializer!!
•Only purpose of SerializerFragment is to generate convenience API!
•generateDebugData to generate pretty state machine diagrams (graphviz dot)
Hooks #1: ITransientValueService
•selectively exclude model-objects and -values from serialization!
•transient == NOT serialized!
•Default setting from Ecore model: EStructuralFeature.isTransient()
public interface ITransientValueService {	
!
	 enum ListTransient {	
	 	 NO, SOME, YES	
	 }	
!
	 enum ValueTransient {	
	 	 NO, PREFERABLY, YES	
	 }	
!
	 public ListTransient isListTransient(EObject semanticObject, EStructuralFeature feature);	
!
	 public boolean isValueInListTransient(EObject semanticObject, int index, EStructuralFeature feature);	
!
	 public ValueTransient isValueTransient(EObject semanticObject, EStructuralFeature feature);	
}
Hooks #2: Token Serialization
public interface ICrossReferenceSerializer {	
	 boolean isValid(EObject context, CrossReference crossref, EObject target, INode node);	
	 String serializeCrossRef(EObject context, CrossReference crossref, EObject target, INode node);	
}
public interface IKeywordSerializer {	
	 boolean isValid(EObject context, Keyword keyword, Object value);	
	 String serializeAssignedKeyword(EObject context, Keyword keyword, Object value, INode node);	
}
public interface IValueSerializer {	
	 boolean isValid(EObject context, RuleCall ruleCall, Object value);	
	 String serializeAssignedValue(EObject context, RuleCall ruleCall, Object value, INode node);	
}
public interface IEnumLiteralSerializer {	
	 boolean isValid(EObject context, RuleCall ruleCall, Object value);	
	 String serializeAssignedEnumLiteral(EObject context, RuleCall ruleCall, Object value, INode node);	
}
Hooks #3: SemanticSequencer
class SerSipSemanticSequencer extends AbstractSerSipSemanticSequencer {	
!
	 @Inject SerSipGrammarAccess grammarAccess;	
!
	 /**	
	 * Constraint:	
	 * (children+=Path | children+=List)	
	 */	
	 override protected sequence_Root(EObject context, Root semanticObject) {	
	 	 val feeder = createSequencerFeeder(semanticObject)	
	 	 for (child : semanticObject.children) {	
	 	 	 if (child.seg != null) {	
	 	 	 	 feeder.accept(grammarAccess.rootAccess.childrenPathParserRuleCall_2_0_0, child)	
	 	 	 } else {	
	 	 	 	 feeder.accept(grammarAccess.rootAccess.childrenListParserRuleCall_2_0_1, child)	
	 	 	 }	
	 	 }	
	 	 feeder.finish()	
	 }	
}	
Root:	
	 "optional"? ID children+=(Path | List);	
!
List returns Child:	
	 "list" item+=ID ("," item+=ID)*;	
!
Path returns Child:	
	 "path" seg=ID ({Segment.parent=current} seg=ID)+;
Hooks #4: SyntacticSequencer
class SerSipSyntacticSequencer extends AbstractSerSipSyntacticSequencer {	
!
	 /**	
	 * terminal ID 		 : '^'?('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*;	
	 */	
	 override getIDToken(EObject semanticObject, RuleCall ruleCall, INode node) {	
	 	 if (node != null)	
	 	 	 return getTokenText(node);	
	 	 return "";	
	 }	
!
	 /**	
	 * Syntax:	
	 * 'optional'?	
	 */	
	 override emit_Root_OptionalKeyword_0_q(EObject semanticObject, ISynNavigable transition, List<INode> nodes) {	
	 	 acceptNodes(transition, nodes);	
	 }	
}
Root:	
	 "optional"? ID children+=(Path | List);
Understanding Ambiguities
•A grammar is ambiguous for the serializer if there can be more
than one textual syntax for a given model.!
!
•A grammar is ambiguous for the parser if there can be more than
one model for a given textual syntax1.
R1:	
foo=ID | bar=ID;
R2:	
(“foo” val=ID) | 	
(“bar” val=ID);
Does “a” parse
to or ?foo=a bar=b
Does serialize to
“foo b” or “bar b”?
val=b
parseserialize
1. that is not completely correct. A grammar is ambiguous when there is more than one path to
consume a given input. That, however, usually leads to different models.
Understanding Ambiguities
Root: 	
(foos=Foo | bars=Bar)*;	
!
Foo: 	
“foo” foo=ID;	
!
Bar: 	
“bar” bar=ID;
(1) . 	
(2) bar b foo a	
(3) foo a bar b
Root
foo=a bar=b
Does (1) serialize
to (2) or (3)?
Avoiding Ambiguities
Analysis: Grammars can be ambiguous for the serializer.!
!
Example:
Root: 	
(foos=Foo | bars=Bar)*;	
!
Foo: 	
“foo” foo=ID;	
!
Bar: 	
“bar” bar=ID;
Root: 	
members+=Member;	
!
Member:	
Foo | Bar;	
!
Foo: 	
“foo” foo=ID;	
!
Bar: 	
“bar” bar=ID;
•Single “member” list to maintain order!
•“Foo” and “Bar” extend “Member”!
•implement getFoo() and getBar() as filters on getMembers()
Avoid Unserializeable Models
The Xtext grammar can imply constraints on your model. !
!
Serialization is only possible if the model complies with theses
constraints because the grammar does not define syntax for models that
don’t comply. Examples:
GRAMMAR CONSTRAINT
R1: name=ID; name != null
R2: (name=ID | title=STING); (name != null) ^ (title != null)
R3: items+=ID+; items.size() >= 1
R4: (a+=ID b+=ID)*; a.size() == b.size()
Avoid Unserializeable Models
Solution:!
!
a) Ensure your grammar does not imply constraints. !
b) Ensure your TransientValueService prevents constraint violations.!
Implement Xtext Validation to enforce constraints.!
!
This will also improve your error messages but may make content assist
too chatty.
RESTRICTIVE SAFE
R1: name=ID;
R1: name=ID?;	
R1: (name=ID | “?”);
R2: (name=ID | title=STING); R2: name=ID? title=STING?;
R3: items+=ID+; R3: items+=ID*;
R4: (a+=ID b+=ID)*;
R4: (a+=ID b+=ID)*	
(“spareA={“ a+=ID+ “}”)?	
(“spareB={“ b+=ID+ “}”)?;
Configure Your Scope Right
You can (and need) to configure global scoping for a ResourceSet!
XtextLiveScopeResourceSetProviderXtextResourceSetProvider
ResourceSet
Dirty Editor State
Index
(default) (what you need)
<shadows>
<shadows>
Dirty Editor State
Index
<shadows>
Happy Serializing!

Weitere ähnliche Inhalte

Was ist angesagt?

Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipesKnoldus Inc.
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom ManipulationMohammed Arif
 
Test-Driven Development of Xtext DSLs
Test-Driven Development  of Xtext DSLsTest-Driven Development  of Xtext DSLs
Test-Driven Development of Xtext DSLsmeysholdt
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJWORKS powered by Ordina
 
CRX2Oak - all the secrets of repository migration
CRX2Oak - all the secrets of repository migrationCRX2Oak - all the secrets of repository migration
CRX2Oak - all the secrets of repository migrationTomasz Rękawek
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxMalla Reddy University
 
Cross-domain requests with CORS
Cross-domain requests with CORSCross-domain requests with CORS
Cross-domain requests with CORSVladimir Dzhuvinov
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideNascenia IT
 
Oracle APEX Interactive Grid Essentials
Oracle APEX Interactive Grid EssentialsOracle APEX Interactive Grid Essentials
Oracle APEX Interactive Grid EssentialsKaren Cannell
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPwahidullah mudaser
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery FundamentalsGil Fink
 
Introduction to java beans
Introduction to java beansIntroduction to java beans
Introduction to java beansHitesh Parmar
 
Express JS Rest API Tutorial
Express JS Rest API TutorialExpress JS Rest API Tutorial
Express JS Rest API TutorialSimplilearn
 

Was ist angesagt? (20)

Javascript validating form
Javascript validating formJavascript validating form
Javascript validating form
 
Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipes
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
Test-Driven Development of Xtext DSLs
Test-Driven Development  of Xtext DSLsTest-Driven Development  of Xtext DSLs
Test-Driven Development of Xtext DSLs
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
CRX2Oak - all the secrets of repository migration
CRX2Oak - all the secrets of repository migrationCRX2Oak - all the secrets of repository migration
CRX2Oak - all the secrets of repository migration
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
Cross-domain requests with CORS
Cross-domain requests with CORSCross-domain requests with CORS
Cross-domain requests with CORS
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation Guide
 
Oracle APEX Interactive Grid Essentials
Oracle APEX Interactive Grid EssentialsOracle APEX Interactive Grid Essentials
Oracle APEX Interactive Grid Essentials
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
Introduction to java beans
Introduction to java beansIntroduction to java beans
Introduction to java beans
 
laravel.pptx
laravel.pptxlaravel.pptx
laravel.pptx
 
Express JS Rest API Tutorial
Express JS Rest API TutorialExpress JS Rest API Tutorial
Express JS Rest API Tutorial
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Scoping
ScopingScoping
Scoping
 

Andere mochten auch

Codegeneration Goodies
Codegeneration GoodiesCodegeneration Goodies
Codegeneration Goodiesmeysholdt
 
Parsing Expression With Xtext
Parsing Expression With XtextParsing Expression With Xtext
Parsing Expression With XtextSven Efftinge
 
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
 
Turning Ideas Into Code Faster
Turning Ideas Into Code FasterTurning Ideas Into Code Faster
Turning Ideas Into Code Fastermeysholdt
 
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
 
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
 
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
 
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
 
ARText - Driving Developments with Xtext
ARText - Driving Developments with XtextARText - Driving Developments with Xtext
ARText - Driving Developments with XtextSebastian Benz
 
Language Engineering With Xtext
Language Engineering With XtextLanguage Engineering With Xtext
Language Engineering With XtextSven Efftinge
 

Andere mochten auch (20)

Codegeneration Goodies
Codegeneration GoodiesCodegeneration Goodies
Codegeneration Goodies
 
Parsing Expression With Xtext
Parsing Expression With XtextParsing Expression With Xtext
Parsing Expression With Xtext
 
Future of Xtext
Future of XtextFuture of Xtext
Future of Xtext
 
Xtext Best Practices
Xtext Best PracticesXtext Best Practices
Xtext Best Practices
 
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
 
Turning Ideas Into Code Faster
Turning Ideas Into Code FasterTurning Ideas Into Code Faster
Turning Ideas Into Code Faster
 
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 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
 
Enhancing Xtext for General Purpose Languages
Enhancing Xtext for General Purpose LanguagesEnhancing Xtext for General Purpose Languages
Enhancing Xtext for General Purpose Languages
 
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
 
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
 
ARText - Driving Developments with Xtext
ARText - Driving Developments with XtextARText - Driving Developments with Xtext
ARText - Driving Developments with Xtext
 
Xtext, diagrams and ux
Xtext, diagrams and uxXtext, diagrams and ux
Xtext, diagrams and ux
 
Language Engineering With Xtext
Language Engineering With XtextLanguage Engineering With Xtext
Language Engineering With Xtext
 
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
 

Ähnlich wie Serializing EMF models with Xtext

Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesJamund Ferguson
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the ASTJarrod Overson
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607Kevin Hazzard
 
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)Eugene Yokota
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CAlexis Gallagher
 
MongoDB Munich 2012: MongoDB for official documents in Bavaria
MongoDB Munich 2012: MongoDB for official documents in BavariaMongoDB Munich 2012: MongoDB for official documents in Bavaria
MongoDB Munich 2012: MongoDB for official documents in BavariaMongoDB
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development IntroLuis Azevedo
 
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
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Ramamohan Chokkam
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Java Intro
Java IntroJava Intro
Java Introbackdoor
 
Moving to modules
Moving to modulesMoving to modules
Moving to modulesSean Mize
 

Ähnlich wie Serializing EMF models with Xtext (20)

Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax Trees
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 
Swift core
Swift coreSwift core
Swift core
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
Gcrc talk
Gcrc talkGcrc talk
Gcrc talk
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
 
MongoDB Munich 2012: MongoDB for official documents in Bavaria
MongoDB Munich 2012: MongoDB for official documents in BavariaMongoDB Munich 2012: MongoDB for official documents in Bavaria
MongoDB Munich 2012: MongoDB for official documents in Bavaria
 
Es.next
Es.nextEs.next
Es.next
 
Java
JavaJava
Java
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development Intro
 
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
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Java Intro
Java IntroJava Intro
Java Intro
 
Moving to modules
Moving to modulesMoving to modules
Moving to modules
 

Kürzlich hochgeladen

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Serializing EMF models with Xtext

  • 1. Moritz Eysholdt, itemis AG Serializing EMF models with Xtext Xtextcon 2014! Kiel, Germany
  • 2. Agenda ❖ Parsing vs. Serializing! ❖ Use Cases! ❖ Generating vs. Serializing! ❖ Challenges! ❖ The Contract! ❖ Architecture! ❖ Hooks! ❖ Advice
  • 3. The New and the Old Serializer org.eclipse.xtext.serializer •The New Serializer. This presentation is about it. org.eclipse.xtext.parsetree.reconstr •The Old Serializer. Don’t used it.! •Cryptic Error Messages! •Bad Performance for Large Models! •marked @Deprecated
  • 11. Why Serialize? ❖ object model usually easier to modify than its textual representation! ❖ guaranteed syntactical correctness! ❖ automatic handling of comments! ❖ automatic handling of whitespace …when I have Xtend, THE language for generators
  • 12. When not to Serialize ❖ Avoid serializing models that are broken due to parse errors.! ❖ Template languages are simpler when writing out large text chunks that never change.
  • 13. The hard Contract Parsing a serialized Model must result ! in a model equal to the original. Model original = createModel() String serialized = serialize(original) Model parsed = parse(serialized) assertEqual(original, parsed) …enables textual models as persistence format
  • 14. The soft Contract Serializing a model that has been modified after parsing! should only change the smallest number of characters necessary. …keep diffs small String originalDoc = loadDocument() Model parsed = parse(originalDoc) Model modified = applyModifications(parsed) String newDoc = serialize(modified) int numberOfChars = diff(originalDoc, newDoc).size() 1. Keep textual diffs small.! 2. Strictly comply with the semantic model! 3. Loosely comply with the node model
  • 15. Challenges ❖ unassigned elements! ❖ ambiguous mapping from EStructuralFeatures to Assignments! ❖ ambiguous mapping from EClasses to ParserRules and Actions …because the AST is actually abstract, as in “lack of information”
  • 16. API Frontends #1 package org.eclipse.xtext.resource; ! public class XtextResource extends ResourceImpl { ! (…) ! public void save(Map<?, ?> options) throws IOException {} ! public final void save(OutputStream outputStream, Map<?, ?> options) throws IOException {} }
  • 17. API Frontends #2 package org.eclipse.xtext.serializer; ! @ImplementedBy(Serializer.class) public interface ISerializer { public String serialize(EObject obj); public String serialize(EObject obj, SaveOptions options); public void serialize(EObject obj, Writer writer, SaveOptions options) throws IOException; public ReplaceRegion serializeReplacement(EObject obj, SaveOptions options); } Options:! - format: ! - true: format all! - false: format regions without whitespace information! - validate: don’t use, it’s an old algorithm.
  • 18. Before Serialization Create one State Machine per Context per EClass Root: "optional"? ID children+=(List | Path); ! List returns Child: "list" item+=ID ("," item+=ID)*; ! Path returns Child: "path" seg=ID ({Segment.parent=current} seg=ID)+; Context EClass Root Root List Child Path Segment Path_Segment_2_0 Child Path_Segment_2_0 Segment
  • 19. During Serialization #1 Find right state machines and ! find right path through them Root: "optional"? ID children+=(List | Path); ! List returns Child: "list" item+=ID ("," item+=ID)*; Context EClass Root Root Context EClass List Child optional Foo list a, b, cOutput:
  • 20. Architecture #3 Context EClass Root Root Context EClass List Child Context EClass Root Root Context EClass List Child Semantic! assigned grammar elements Syntactic! unassigned grammar elements optional Foo list a, b, cOutput:
  • 21. Architecture #4: Observer Semantic! Sequencer Syntactic! Sequencer HiddenToken! Sequencer Formatter Writer Events Listens To assigend! * RuleCalls! * Terminals! * DataTypes! * Keywords! * CrossRefs unassigned! * RuleCalls! * Terminals! * DataTypes! * Keywords * whitespace! * comments modifies! whitespace writes to ! stream
  • 22. Output: /*X*/ Foo list a Serializer HiddenTokenSequencerSyntacticSequencerSemanticSequencer createSequence (Root, Root) enter AssignedParserRuleCall (children=List) enter AssignedParserRuleCall (children=List) createSequence (List, Children) accept UnassignedRuleCall (ID) accept AssignedTerminalRuleCall (itemi=ID) accept Keyword ("list") accept AssignedTerminalRuleCall (itemi=ID) leave AssignedParserRuleCall (children=List) leave AssignedParserRuleCall (children=List) Formatter Writer enterAssignedParserRuleCall() acceptWhitespace() acceptWhitespace() acceptComment(/*X*/) acceptUnassignedRuleCall() acceptKeyword() acceptWhitespace() acceptAssignedTerminalRuleCall() acceptWhitespace() enterAssignedParserRuleCall() Root: "optional"? ID children+=(List | Path); List returns Child: "list" item+=ID ("," item+=ID)*;
  • 23. SerializerFragment fragment = serializer.SerializerFragment auto-inject { generateStub = true // generateDebugData = true } •SerializerFragment not required to use serializer!! •Only purpose of SerializerFragment is to generate convenience API! •generateDebugData to generate pretty state machine diagrams (graphviz dot)
  • 24. Hooks #1: ITransientValueService •selectively exclude model-objects and -values from serialization! •transient == NOT serialized! •Default setting from Ecore model: EStructuralFeature.isTransient() public interface ITransientValueService { ! enum ListTransient { NO, SOME, YES } ! enum ValueTransient { NO, PREFERABLY, YES } ! public ListTransient isListTransient(EObject semanticObject, EStructuralFeature feature); ! public boolean isValueInListTransient(EObject semanticObject, int index, EStructuralFeature feature); ! public ValueTransient isValueTransient(EObject semanticObject, EStructuralFeature feature); }
  • 25. Hooks #2: Token Serialization public interface ICrossReferenceSerializer { boolean isValid(EObject context, CrossReference crossref, EObject target, INode node); String serializeCrossRef(EObject context, CrossReference crossref, EObject target, INode node); } public interface IKeywordSerializer { boolean isValid(EObject context, Keyword keyword, Object value); String serializeAssignedKeyword(EObject context, Keyword keyword, Object value, INode node); } public interface IValueSerializer { boolean isValid(EObject context, RuleCall ruleCall, Object value); String serializeAssignedValue(EObject context, RuleCall ruleCall, Object value, INode node); } public interface IEnumLiteralSerializer { boolean isValid(EObject context, RuleCall ruleCall, Object value); String serializeAssignedEnumLiteral(EObject context, RuleCall ruleCall, Object value, INode node); }
  • 26. Hooks #3: SemanticSequencer class SerSipSemanticSequencer extends AbstractSerSipSemanticSequencer { ! @Inject SerSipGrammarAccess grammarAccess; ! /** * Constraint: * (children+=Path | children+=List) */ override protected sequence_Root(EObject context, Root semanticObject) { val feeder = createSequencerFeeder(semanticObject) for (child : semanticObject.children) { if (child.seg != null) { feeder.accept(grammarAccess.rootAccess.childrenPathParserRuleCall_2_0_0, child) } else { feeder.accept(grammarAccess.rootAccess.childrenListParserRuleCall_2_0_1, child) } } feeder.finish() } } Root: "optional"? ID children+=(Path | List); ! List returns Child: "list" item+=ID ("," item+=ID)*; ! Path returns Child: "path" seg=ID ({Segment.parent=current} seg=ID)+;
  • 27. Hooks #4: SyntacticSequencer class SerSipSyntacticSequencer extends AbstractSerSipSyntacticSequencer { ! /** * terminal ID : '^'?('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*; */ override getIDToken(EObject semanticObject, RuleCall ruleCall, INode node) { if (node != null) return getTokenText(node); return ""; } ! /** * Syntax: * 'optional'? */ override emit_Root_OptionalKeyword_0_q(EObject semanticObject, ISynNavigable transition, List<INode> nodes) { acceptNodes(transition, nodes); } } Root: "optional"? ID children+=(Path | List);
  • 28. Understanding Ambiguities •A grammar is ambiguous for the serializer if there can be more than one textual syntax for a given model.! ! •A grammar is ambiguous for the parser if there can be more than one model for a given textual syntax1. R1: foo=ID | bar=ID; R2: (“foo” val=ID) | (“bar” val=ID); Does “a” parse to or ?foo=a bar=b Does serialize to “foo b” or “bar b”? val=b parseserialize 1. that is not completely correct. A grammar is ambiguous when there is more than one path to consume a given input. That, however, usually leads to different models.
  • 29. Understanding Ambiguities Root: (foos=Foo | bars=Bar)*; ! Foo: “foo” foo=ID; ! Bar: “bar” bar=ID; (1) . (2) bar b foo a (3) foo a bar b Root foo=a bar=b Does (1) serialize to (2) or (3)?
  • 30. Avoiding Ambiguities Analysis: Grammars can be ambiguous for the serializer.! ! Example: Root: (foos=Foo | bars=Bar)*; ! Foo: “foo” foo=ID; ! Bar: “bar” bar=ID; Root: members+=Member; ! Member: Foo | Bar; ! Foo: “foo” foo=ID; ! Bar: “bar” bar=ID; •Single “member” list to maintain order! •“Foo” and “Bar” extend “Member”! •implement getFoo() and getBar() as filters on getMembers()
  • 31. Avoid Unserializeable Models The Xtext grammar can imply constraints on your model. ! ! Serialization is only possible if the model complies with theses constraints because the grammar does not define syntax for models that don’t comply. Examples: GRAMMAR CONSTRAINT R1: name=ID; name != null R2: (name=ID | title=STING); (name != null) ^ (title != null) R3: items+=ID+; items.size() >= 1 R4: (a+=ID b+=ID)*; a.size() == b.size()
  • 32. Avoid Unserializeable Models Solution:! ! a) Ensure your grammar does not imply constraints. ! b) Ensure your TransientValueService prevents constraint violations.! Implement Xtext Validation to enforce constraints.! ! This will also improve your error messages but may make content assist too chatty. RESTRICTIVE SAFE R1: name=ID; R1: name=ID?; R1: (name=ID | “?”); R2: (name=ID | title=STING); R2: name=ID? title=STING?; R3: items+=ID+; R3: items+=ID*; R4: (a+=ID b+=ID)*; R4: (a+=ID b+=ID)* (“spareA={“ a+=ID+ “}”)? (“spareB={“ b+=ID+ “}”)?;
  • 33. Configure Your Scope Right You can (and need) to configure global scoping for a ResourceSet! XtextLiveScopeResourceSetProviderXtextResourceSetProvider ResourceSet Dirty Editor State Index (default) (what you need) <shadows> <shadows> Dirty Editor State Index <shadows>