programmer machine code. Business. Problem solution by model-based
development ... Eclipse Modeling is the umbrella project for all things about
modeling ...... 95. Outline – Metamodeling Process. 1. Domain modeling (abstract
syntax). 2.
07/11/12
October, 2012
Business Problem
A Tutorial about Metamodeling
Business Problem
Business Problem
software modeler
Using OMG Norms and Eclipse Modeling
2
A Tutorial about Metamodeling © Benoit Combemale
programmer
Benoit Combemale University of Rennes 1 (IRISA & ESIR)
model
software modeler
domain-specific
model
programmer
code
machine
http://www.combemale.fr/mde
solution by programmable machine
code
machine
code
machine
solution by solution by model-based development model-driven development From Gregor Engels (Universität Paderborn, Germany) Panel "When will Code become Irrelevant?", MoDELS 2011.
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
3
Model Driven Engineering
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
4
Model Driven Engineering
Security
Distribution
Fault tolerance
Functional behavior
Use case model borrow return deliver
Platform Model
setDamaged
Design Model
reser ve
Book User state : String
Change one Aspect and Automatically Re-Weave: From AORE, SPL to DAS
De « L'ingénierie dirigée par les modèles. Au-delà du MDA. » FAVRE Jean-Marie, ESTUBLIER Jacky, BLAY-FORNARINO Mireille Hermes Science Publications, 2006.
A metaphor for Model Driven Engineering, J. Haan,Code 2009.
Model
1
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
5
Modeling and Metamodeling
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
6
Metamodeling Editors (textuals, graphicals, …)
Checkers (static & dynamics)
Documentation generators
Compilers
Test generators
Translators
Simulators
Code generators
Analyzers Refactoring
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Metamodeling
Building a tool-supported DSL with the Kermeta Workbench
7
October, 2012
Etc.
A Tutorial about Metamodeling © Benoit Combemale
8
Metamodeling: Norms and Tools • Norms (OMG): MOF, OCL, QVT, fUML, ALF…
MOF/Ecore + OCL
Abstract Syntax *
(+ static semantics)
*
Concrete syntax xText, EMFText, GMF, Topcased, Antlr…
Dynamic
QVT*, Semantics Kermeta AL, Java EMF…
• Metamodeling environments: • Eclipse Modeling (e.g., Ecore, OCL Tools…), Kermeta • MS DSL Tools • Vanderbilt GME • Etc.
2
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
9
October, 2012
10
A Tutorial about Metamodeling © Benoit Combemale
Eclipe Modeling: Overview
Eclipe Modeling: Overview
• Eclipse Modeling is the umbrella project for all things about
The answer to "What is Eclipse Modeling?" depends on who you ask!
modeling that happen on the Eclipse platform:
The Eclipse Modeling Project (EMP) focuses on the evolution and promotion of model-based development technologies within the Eclipse community by providing a unified set of modeling frameworks, tooling, and standards implementations. • Eclipse Modeling is not formally related to OMG, but implements
several of their standards.
A set of Eclipse projects dedicated to… • … Modeling: modeling tools • Model Development Tools (UML2, OCL, SysML, MARTE, BPMN2, etc.)
• … Metamodeling: workbench for language design and
implementation
• Abstract Syntax Development (EMF)
• It is fair to say that many leading edge modeling tools are hosted/
developed at Eclipse Modeling.
• Concrete Syntax Development (GMP, TMF) • Model Transformation (M2M, M2T)
Mac
Abstract Syntax (AS)
Concrete Syntax
Mas
(CS)
Semantics Domain
• See http://www.eclipse.org/modeling
• Everything Open Source under the Eclipse Public License
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
11
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Eclipe Modeling: Overview
EMF: Overview
See the Eclipse Modeling tool at http://eclipse.org/downloads/packages … and many other tools (Install Modeling Components):
• What is it? • MetaModeling (think of UML/OCL) • Interoperability (think of XMI) • Editing tool support (think Eclipse) • Code generation (think of MDA)
Other Eclipse Modeling Components
(SD)
12
• EMF serves as the foundation: It provides the Ecore meta-
metamodel, and frameworks and tools around it for tasks such as • • • • •
But the cornerstone stills….
Editing Transactions Validation Query Distribution/Persistence (CDO, Net4j, Teneo)
• See http://www.eclipse.org/modeling/emf
3
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
13
DIY with LOGO programs
Case Study: Building a Programming Environment for Logo
15
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
16
Model Driven Language Engineering : the Process
• Featuring • Edition in Eclipse • On screen simulation
14
; righthilbert to righthilbert :level :size if :level != 0 [ right 90 lefthilbert :level-1 :size forward :size left 90 righthilbert level-1 :size forward :size righthilbert :level-1 :size left 90 forward :size lefthilbert :level-1 :size right 90 ] end
; lefthilbert to lefthilbert :level :size if :level != 0 [ left 90 righthilbert :level-1 :size forward :size right 90 lefthilbert :level-1 :size forward :size lefthilbert :level-1 :size right 90 forward :size righthilbert :level-1 :size left 90 ] end
to square :width repeat 4 [ forward :width right 90 ] end pendown square 10
A Tutorial about Metamodeling © Benoit Combemale
A Tutorial about Metamodeling © Benoit Combemale
Fractals in LOGO
• Consider LOGO programs of the form: repeat 3 [ pendown forward 3 penup forward 4 ]
October, 2012
October, 2012
Syntaxe abstraite (Définition ou évolution)
Syntaxe concrète (Définition ou évolution)
Sémantique statique ou évolution)
Editeur
(Définition
• Compilation for a Lego
Mindstorms robot
Sémantique comportementale (Définition ou évolution)
Vérificateur statique
Simulateur, compilateur, animateur Métamodèle Domaine métier
Transformations utilitaires (Définition ou évolution) Refactoring, analyseur, générateurs de documentation, de test, ...
4
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
17
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
18
Outline – Metamodeling Process
Outline – Metamodeling Process
1. Domain modeling (abstract syntax)
1. Domain modeling (abstract syntax)
2. Model edition (concrete syntax)
2. Model edition (concrete syntax)
3. Model serialization (concrete syntax)
3. Model serialization (concrete syntax)
4. Model checker (static semantics)
4. Model checker (static semantics)
5. Simulator implementation (behavioral semantics)
5. Simulator implementation (behavioral semantics)
6. Compiler implementation (behavioral semantics)
6. Compiler implementation (behavioral semantics)
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
19
OMG (Essential) MOF • Provides language constructs for specifying a DSL
metamodel
• mainly based on Object-Oriented constructs: package, classes,
properties (attribute and reference), and (multiple) inheritance. • specificities: composition, opposite… • Defined as a model, called metametamodel: NamedElement name: String
Type
type 1
TypedElement
DataType
Property
Class isAbstract: Boolean = false
Boolean String
Natural
0..* superClass
A Tutorial about Metamodeling © Benoit Combemale
20
Ecore: a metamodel for metamodels • Ecore is an implementation proposed by EMF, and aligned to
EMOF
• Provides a language to build languages • A metamodel is a model; and its metamodel is Ecore. • So a metamodel is an Ecore model! • Ecore has concepts like: • Class – inheritance, have properties • Property – name, multiplicity, type
lower: Natural owner
=1 upper : Natural = 1 isOrdered : Boolean = false
October, 2012
{ordered} 0..* isComposite: Boolean = false ownedAttribute default: String = ""
• Essentially this is a simplified version of class modeling in UML
0..1 opposite
5
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
21
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
22
Ecore Diagram
Supported by a lot of (meta) tools (e.g., graphical editor, code generator…)
ECORE.ecore From the « Essential EMF Refcardz »
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Meta-Modeling LOGO programs
23
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
24
LOGO metamodel
• Let’s build a meta-model for LOGO • Concentrate on the abstract syntax • Look for concepts: instructions, expressions… • Find relationships between these concepts • It’s like UML modeling!
• Defined as an ECore model • Using EMF tools and editors
ASMLogo.ecore
6
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
25
LOGO metamodel
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
26
Implementation with Java MOF
The UML metamodel
How it works?
A UML Model
A Specific phenomenon corresponding to a UML Model
ASMLogo.ecore
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
EMF
27
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
28
Implementation with Java • EMF is a software (E)framework • Model driven….
…but implemented using a programming language!
An Ecore model and its sources (from EMF: Eclipse Modeling Framework 2nd)
• Reification MDE → Java: • Metamodels are represented with EClasses • Models are represented with EObjects
7
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
29
Implementation with Java
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
30
EMF Toolset from 30.000 Feet • The EMF Generator do not work on the .ecore
MOF
Ecore …. ?M
Ecore MM
The UML metamodel
UML M
• EMF defines a .gemodel in parallel: • New/ Other/ Eclipse Modeling Framework/ EMF Model • We can customize the code generator! • The IDE takes care of maintaining the consistency (or not!)
PROMOTION
(EMF Generator) UML MM
A UML Model
A UML model
…. ?
A Specific phenomenon corresponding to a UML Model
From "Mastering Eclipse Modeling Framework", V. Bacvanski and P. Graff
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
31
EMF Toolset from 30.000 Feet
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
32
EMF Toolset from 30.000 Feet Actions available on the metamodel: 1. Generate Model Code: Java Classes corresponding to the metamodel 2. Generate Edit Code: Plugin supporting the edition 3. Generate Editor Code: Plugin for a tree based model editor 4. Generate Test Code: Plugin for unit testing Actions available from the .genmodel, and into an EMF Project.
From "Mastering Eclipse Modeling Framework", V. Bacvanski and P. Graff
From "Mastering Eclipse Modeling Framework", V. Bacvanski and P. Graff
8
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
33
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
34
EMF: open the box
EOperation Implementation
• The EMF.edit separates the GUI from the business model
Localization of the methods in the generated code 1. In the subpackage graph.impl! 2. In the class GraphImpl! 3. Scattered in the code automatically generated by EMF…
• To understand the EMF.edit plug-in, it is essential to
understand three basic design patterns • Observer pattern • Command pattern
/**! * @generated NOT! */! public int order () {! !return this.getEdges().size();! }!
• Adapter pattern
Do not forget to mark (@generated NOT) to prevent crushing!
From "Mastering Eclipse Modeling Framework", V. Bacvanski and P. Graff
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
35
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Outline – Metamodeling Process
Default EMF Editor
1. Domain modeling (abstract syntax)
• EMF’s default reflective editor can be used out of the
2. Model edition (concrete syntax) 3. Model serialization (concrete syntax)
36
box to create instances of any meta model • Generic, • But not very usable or scalable
4. Model checker (static semantics) 5. Simulator implementation (behavioral semantics) 6. Compiler implementation (behavioral semantics)
9
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
37
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
EMF as cornerstone for the other projects
The GMP and TMF Eclipse Projects
The underlying framework for many many other tools
• GMP (Graphical Modeling Project): • generative components and runtime infrastructures for developing graphical editors based on EMF and GEF • See http://www.eclipse.org/modeling/gmp/
EMF-based Tools (68 matches in September, 2012)
38
• TMF (Textual Modeling Framework): • tools and frameworks for developing textual syntaxes and corresponding editors based on EMF • See http://www.eclipse.org/modeling/tmf/
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Building Model Editors Domain Model (abstract syntax)
Configuration Model (mapping)
39
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
40
GMP: Overview Textual or Graphical Representation (concrete syntax)
• Mainly composed of GMF (Graphical Modeling Framework) • Define custom graphical editors for your metamodel • Use the editor to “draw” instances of the metamodel
compilation or interpretation
textual or graphical editor
10
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
41
GMP: Overview
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
42
GMP: Overview • An example of a GMF graphical editor:
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
43
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
TMF: Overview
TMF: Overview
• Mainly composed of xText
• An example of an xText textual editor:
44
• Xtext is a framework/tool for development of external textual
DSLs.
• Based on an EBNF grammar, xText generates • ANTLR3-based parser • EMF-based metamodel • Eclipse editor with • • • • •
syntax highlighting code completion customizable outline code folding real-time constraint checking
11
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
45
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Outline – Metamodeling Process
XMI (XML Metadata Interchange)
1. Domain modeling (abstract syntax)
• XMI is XML standard for meta-data interchange
46
• If the metamodel can be expressed in MOF, its meta-data
2. Model edition (concrete syntax)
can be serialised as XMI
3. Model serialization (concrete syntax)
• Ecore models are stored/shared in XMI
4. Model checker (static semantics)
• Ecore diagrams are in XMI
5. Simulator implementation (behavioral semantics)
• EMF generator models are in XMI!
6. Compiler implementation (behavioral semantics)
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
XMI (XML Metadata Interchange)
47
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
48
Outline – Metamodeling Process 1. Domain modeling (abstract syntax)
PetriNet
2. Model edition (concrete syntax)
name: EString arcs 0..*
nodes 0..*
outgoings 1 source 0..*
Node name: EString
1 target
Transition tmin: EInt tmax: EInt 0..*
Place marking: EInt
Arc weight: EInt kind: ArcKind
3. Model serialization (concrete syntax)
0..* ingoings ArcKind
normal readArc
4. Model checker (static semantics)
prioritize
5. Simulator implementation (behavioral semantics) 6. Compiler implementation (behavioral semantics)
12
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
49
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
50
Contracts in OO languages
Static Semantics with OCL • Complementing a metamodel with Well-Formedness Rules,
aka contracts or context conditions, e.g.; •
• Inspired by the notion of Abstract Data Type
A procedure is called with the same number of arguments as specified in its declaration
• Specification = Signature + • Preconditions • Postconditions • Class Invariants
⇒ Design-by-Contract applied at the meta-level • Expressed with the OCL (Object Constraint Language) • The OCL is a language of typed expressions. • A constraint is a valid OCL expression of type Boolean. • A constraint is a restriction on one or more values of (part of) an object-oriented model or system.
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
• Behavioral contracts are inherited in subclasses
51
OCL • Can be used at both • M1 level (constraints on Models) • aka Design-by-Contract (Meyer)
• M2 level (constraints on Meta-Models) • aka Static semantics(aka. context conditions or well-formedness rules)
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
52
Simple constraints Customer name: String title: String age: Integer isMale: Boolean
• Let’s overview it with M1 level exemples title = if isMale then ‘Mr.’ else ‘Ms.’ endif age >= 18 and age < 66 name.size < 100
13
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
53
Non-local contracts: navigating associations • Each association is a navigation path • The context of an OCL expression is the starting point • Role names are used to select which association is to be traversed (or target class name if only one)
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
54
Navigation of 0..* associations • Through navigation, we no longer get a scalar but a collection
of objects
• OCL defines 3 sub-types of collection • Set : when navigation of a 0..* association • Context Person inv: ownings return a Set[Car] • Each element is in the Set at most once
1 owner
Person
ownership
ownings *
• Bag : if more than one navigation step • An element can be present more than once in the Bag
Car
• Sequence : navigation of an association {ordered} • It is an ordered Bag
Context Car inv: self.owner.age >= 18
• Many predefined operations on type collection Syntax:: Collection->operation
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Collection hierarchy
55
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
56
Basic operations on collections • isEmpty • true if collection has no element
Collection
Context Person inv: ageisEmpty
Set minus symmetricDifference asSequence asBag
Bag asSequence asSet
Sequence first last at(int) append prepend asBag asSet
• notEmpty • true if collection has at least one element • size • Number of elements in the collection • count (elem) • Number of occurrences of element elem in the collection
14
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
57
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Operation select!
Operation forAll!
• possible syntax • collection->select(elem:T | expr) • collection->select(elem | expr) • collection->select(expr)
• possible syntax • collection->forall(elem:T | expr) • collection->forall(elem | expr) • collection->forall(expr)
• Selects the subset of collection for which property expr
• True iff expr holds for each element of the collection
holds • e.g.
• e.g. context Person inv: ownings->forall(v: Car | v.mileageselect(v: Car | v.mileagenotEmpty
• shortcut:
• shortcut:
context Person inv: ownings->forall(mileageselect(mileagenotEmpty
October, 2012
58
A Tutorial about Metamodeling © Benoit Combemale
Operations on Collections!
59
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
60
Static Semantics for LOGO • No two formal parameters of a procedure may have
the same name:
• A procedure is called with the same number of
arguments as specified in its declaration:
15
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
61
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Static Semantics for LOGO
OCL Tools
• No two formal parameters of a procedure may have
• Il existe de nombreux outils qui permettent de vérifier la
the same name: context ProcDeclaration inv unique_names_for_formal_arguments : args -> forAll ( a1 , a2 | a1. name = a2.name implies a1 = a2 )
62
syntaxe, la sémantique et d’évaluer une expression OCL : • EMF MDT, http://www.eclipse.org/modeling/mdt/?project=ocl • Use 2.3, http://www.db.informatik.uni-bremen.de/projects/USE • Dresden OCL Toolkit 2.0, http://dresden-ocl.sourceforge.net • LCI OCL Evaluator OCLE 2.0.4, http://lci.cs.ubbcluj.ro/ocle • The Kent OCL library v1, http://www.cs.kent.ac.uk/projects/ocl
• A procedure is called with the same number of
• Octopus OCL, http://octopus.sourceforge.net
arguments as specified in its declaration: context ProcCall inv same_number_of_formals_and_actuals : actualArgs -> size = declaration .args -> size
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
OCL Tools - Kermeta • Use AOM to weave your
static semantics into your metamodel! • If the boolean statement
is evaluated to false then the pre or post condition is violated and an exception ConstraintViolatedPre or
63
• Topcased, http://www.topcased.org • Kermeta, http://www.kermeta.org • etc.
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
64
OCL Tools - Kermeta Two methods to check the WFR: • checkInvariants, check only the current model element • checkAllInvariants, checks recursively the element being a containment link with the checked element
ConstraintViolatedPost
is raised.
16
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
65
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
66
Breathing life into metamodels
Outline – Metamodeling Process
• A model
1. Domain modeling (abstract syntax) 2. Model edition (concrete syntax)
• Its metamodel
3. Model serialization (concrete syntax) 4. Model checker (static semantics) 5. Simulator implementation (behavioral semantics) 6. Compiler implementation (behavioral semantics)
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Metadata languages • (E)MOF => Only data structures • classes, properties, associations, ... • operations : only signatures • Not sufficient to operate on models • Constraints • Actions • Transformations • ...
67
• Adding Operational Semantics to OO Metamodels
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
68
From Metamodels to Languages How do these things relate? MOF EMOF ECore Infra Etc.
Generic Syntax (HUTN)
Abstract Syntax Concrete Concrete Syntax Concrete Syntax Syntax
Semantic Specification
Semantics The language I want to build
17
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
69
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
70
What is “meta”-executability?
Typical example (excerpted from MOF spec) • Operation isInstance(element : Element) : Boolean
“Returns true if the element is an instance of this type or a subclass of this type. Returns false if the element is null”. A natural language specification
operation isInstance (element : Element) : Boolean is do // false if the element is null if element == void then result := false else // true if the element is an instance of this type // or a subclass of this type result := element.getMetaClass == self or element.getMetaClass.allSuperClasses.contains(self) end end
M
• Basic CRUD Operations
Definition
• Merge, Composition… M-1
Execution
► Simply
an (object-oriented) program that manipulates model elements
“Program = Data Structure + Algorithm”, Niklaus Wirth
MetaExecutability
=
Meta-Data
+
Meta-Actions
An operational specification
October, 2012
Context Mac
Abstract Syntax (AS)
Concrete Syntax
Mas
(CS)
Semantics Domain
A Tutorial about Metamodeling © Benoit Combemale
71
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
72
Kermeta Rationale • Model, meta-model, meta-metamodel, DSLs… • Meta-bla-bla too complex for the normal engineer
(SD)
• On the other hand, engineers are familiars with • OO programming languages (Java,C#,C++,..) • UML (at least class diagram) • May have heard of Design-by-Contract • Kermeta leverages this familiarity to make Meta-modeling
easy for the masses
18
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
73
Breathing life into Meta-Models
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
74
Kermeta, a Kernel to Meta Kermeta Actions
// MyKermetaProgram.kmt // An E-MOF metamodel is an OO program that does nothing
require "StateMachine.ecore" // to import it in Kermeta
// Kermeta lets you weave in aspects // Contracts (OCL WFR)
require “StaticSemantics.ocl”
Context FSM inv: ownedState->forAll(s1,s2| s1.name=s2.name implies s1=s2)
Metadata
// Method bodies (Dynamic semantics) require “DynamicSemantics.kmt”
// Transformations
Constraints
aspect class FSM { operation reset() : Void { currentState := initialState }}
Transformations
class Minimizer { operation minimize (source: FSM):FSM {…} }
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Kermeta workbench snapshot
75
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
76
Kermeta: a Kernel metamodeling language • Seamless integration with Ecore and EMF-based
tools
• Statically Typed • Generics, Function types (for OCL-like iterators) • Object-Oriented • Multiple inheritance / dynamic binding / reflection • Model-Oriented • Associations / Compositions • Models are first class citizens, notion of model type • Aspect-Oriented • Simple syntax for static introduction • Arbitrary complex aspect weaving as a framework
• Still “kernel” language • Seamless import of Java classes in Kermeta for GUI/IO etc. Benoît Combemale
19
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
77
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Types & opérateurs usuels
Classes, opérations et méthodes
• Types scalaires très restreints • Integer, String, Boolean
• Déclaration de classes à la Java (class C { }) • Classes abstraites (abstract), généricité (class A) • Héritage (inherits), multiple ou non • Constructions : pas de constructeur ! (MyClass.new) • Variables de classes : Attributs & Référence • attribute a: String ⇒ a est contenue par composition () • reference r: String ⇒ r est référencée • self représente l'instance courante • Absence de visibilité : tout est public • Méthode d'instance : Opérations & Méthodes • operation name(arg1: T): OutputType is do ... end • Redéfinition par héritage : operation → method • Variable locale : var tmp: String init String.new • Retour : pas de return ! On utilise la variable result • Pas de surcharge dans le langage (simplification)
• Opérateurs : • Affectation : := (naïve), ?= (cast) • Arithmétique : +,-,/,* • Comparaison : ==, !=, = • Logique : and, or, not • Collections : fondées sur la définition d'OCL
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
79
EMOF óKermeta
class FSM { attribute ownedState : State[0..*]#owningFSM reference initialState : State[1..1] reference currentState : State operation run() : kermeta::standard::~Void is do end operation reset() : kermeta::standard::~Void is do end }
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
78
80
Assignment semantics
class State{ reference owningFSM : FSM[1..1]#ownedState attribute name : String attribute outgoingTransition : Transition[0..*]#source reference incomingTransition : Transition#target operation step(c : String) : kermeta::standard::~Void is do end } class Transition{ reference source : State[1..1]#outgoingTransition reference target : State[1..1]#incomingTransition attribute input : String attribute output : String operation fire() : String is do end }
20
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
81
Fermetures & λ-fonctions: les itérateurs
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
82
Example
• Effectuer une action ∀e ∈ C each • f.each{ n | stdio.write( n.toString + " ") } • Vérifier une condition ∀e ∈ C forAll • var b: Boolean init f.forAll{ n | n < 250 } • Sélection d'un sous-ensemble (filter) select • var f2: Sequence init f.select{n | n < 100} • Exclusion d'un sous-ensemble reject • var f3: Sequence init f.reject{n | n < 100}
operation fire() : String
• Mapping de fonction collect • var f4: Sequence init fib.collect{n | n + 1}
source.owningFSM.currentState := target result := output
• Détection d'un élément detect • var x: Integer init fib.detect{n | n > 47} • Existence d'un élément exists • var b2: Boolean init fib.exists{n | n > 47 }
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
operation step(c : String) : String // Get the valid transitions var validTransitions : Collection validTransitions := outgoingTransition.select { t |
t.input.equals(c) } // Check if there is one and only one valid transition if validTransitions.empty then raise NoTransition.new end if validTransitions.size > 1 then
raise NonDeterminism.new end // fire the transition result := validTransitions.one.fire
83
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
84
operation run() : Void from var str : String until str == "exit" loop
stdio.writeln("current state is " + currentState.name)
str := stdio.read("Enter an input string or 'exit'
to exit simulation : ")
stdio.writeln(str)
if str != "exit" then
do
stdio.writeln("Output string : " + currentState.step(str))
rescue (ex : FSMException)
stdio.writeln("ERROR : " + ex.toString)
end
end end stdio.writeln("* END OF SIMULATION *")
21
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
85
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
86
Operational Semantics for LOGO • Expressed as a mapping from a meta-model to a virtual
machine (VM) • LOGO VM ? • Concept of Turtle, Lines, points… • Let’s Model it ! • (Defined as an Ecore meta-model)
/** * Load a sample FSM from a xmi2 file */ operation loadFSM() : FSM is do var repository : EMFRepository init EMFRepository.new var resource : EMFResource resource ?= repository.createResource("../models/fsm_sample1.xmi", "../metamodels/fsm.ecore") resource.load // Load the fsm (we get the main instance) result ?= resource.instances.one end
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
87
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
88
Virtual Machine - Semantics
Virtual Machine - Model VMLogo.ecore
require "VMLogo.ecore" require "TurtleGUI.kmt" LogoVMSemantics.kmt
aspect class Point { method toString() : String is do result := "[" + x.toString + "," + y.toString + "]" end }
aspect class Turtle { operation setPenUp(b : Boolean) is do penUp := b end operation rotate(angle : Integer) is do heading := (heading + angle).mod(360) end }
⇒ Defined as an Ecore meta-model
22
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
89
Map Instructions to VM Actions • Weave an interpretation
aspect into the metamodel • add an eval() method into
each class of the LOGO MM
October, 2012
aspect class PenUp { eval (ctx: Context) { ctx.getTurtle().setPenUp(true) } … aspect class Clear { eval (ctx: Context) { ctx.getTurtle().reset() }
• Simple approach using
the Kermeta VM to « ground » the semantics of basic operations • Or reify it into the LOGO VM • Using eg a stack-based
machine
kermeta though
A Tutorial about Metamodeling © Benoit Combemale
Handling control structures • Block • Conditional • Repeat • While
90
Meta-level Anchoring
• Ultimately grounding it in
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
91
October, 2012
… aspect class Add { eval (ctx: Context) : Integer { result = lhs.eval(ctx) + rhs.eval(ctx) } … aspect class Add { eval (ctx: Context) { lhs.eval(ctx) // put result on top of ctx stack rhs.eval(ctx) // idem ctx.getMachine().add() }
A Tutorial about Metamodeling © Benoit Combemale
//
92
Operational semantics LogoDynSemantics.kmt require "ASMLogo.ecore" require "LogoVMSemantics.kmt"
aspect class If { operation eval(context : Context) : Integer is do if condition.eval(context) != 0 then result := thenPart.eval(context) else result := elsePart.eval(context) end
end }
aspect class Right { operation eval(context : Context) : Integer is do context.turtle.rotate(angle.eval(context)) end }
23
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
93
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Handling function calls
Getting an Interpreter
• Use a stack frame • Owned in the Context
• Glue that is needed to load models • ie LOGO programs
94
• Vizualize the result • Print traces as text • Put an observer on the LOGO VM to graphically display the resulting figure
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Simulator • Execute the operational semantics
95
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
96
Outline – Metamodeling Process 1. Domain modeling (abstract syntax) 2. Model edition (concrete syntax) 3. Model serialization (concrete syntax) 4. Model checker (static semantics) 5. Simulator implementation (behavioral semantics) 6. Compiler implementation (behavioral semantics)
24
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
97
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
98
Specific platform
Implementing a model-driven compiler
• Lego Mindstorms Turtle Robot • Two motors for wheels • One motor to control the pen
• Map a LOGO program to Lego Mindstroms • The LOGO program is like a PIM • The target program is a PSM • => model transformation • Kermeta to weave a « compilation » aspect into the logo
meta-model aspect class PenUp { compile (ctx: Context) { … } } … aspect class Clear { }
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
99
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Model-to-Text vs. Model-to-Model
Model-to-Text Approaches
• Model-to-Text Transformations • For generating: code, xml, html, doc. • Should be limited to syntactic level transcoding
• For generating: code, xml, html, doc.
100
• Visitor-Based Approaches: • Some visitor mechanisms to traverse the internal representation of a
model and write code to a text stream
• Model-to-Model Transformations • To handle more complex, semantic driven transformations
• Iterators, Write ()
• Template-Based Approaches • A template consists of the target text containing slices of meta-code to
access information from the source and to perform text selection and iterative expansion • The structure of a template resembles closely the text to be generated • Textual templates are independent of the target language and simplify the generation of any textual artefacts
25
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
101
Classification of Model-to-Model Transformation Techniques
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
102
Logo to NXC Compiler • Step 1 – Model-to-Model transformation
1. General purpose programming languages •
Java/C#...
2. Generic transformation tools •
Graph transformations, XSLT…
NXC.ecore
ASMLogo.ecore
K.xmi
K.nxc.xmi
Logo2NXC.kmt
3. CASE tools scripting languages •
Objecteering, Rose…
• Step 2 – Code generation with template
4. Dedicated model transformation tools •
OMG QVT style
NXC.ecore
5. Meta-modeling tools •
Metacase, Xactium, Kermeta… K.nxc.xmi
October, 2012
Execution
A Tutorial about Metamodeling © Benoit Combemale
103
October, 2012
NXC.ket
K.nxc
A Tutorial about Metamodeling © Benoit Combemale
104
Summary
Abstract Syntax.ecore
Concrete Syntax.sts
StaticSemantics.ocl
Semantic Domain.ecore
BehavioralSemantics.kmt
26
07/11/12
October, 2012
105
A Tutorial about Metamodeling © Benoit Combemale
Logo Summary (1) ASMLogo.ecore
106
• Integrate all aspects coherently • syntax / semantics / tools • Use appropriate languages • MOF for abstract syntax • OCL for static semantics • Kermeta for dynamic semantics • Java for simulation GUI • ...
TurtleGUI.kmt LogoStaticSem.ocl
Editor.java TurtleControler.kmt NXC.ecore LogoVMSemantics.kmt
NXC.ket
A Tutorial about Metamodeling © Benoit Combemale
Logo Summary (2) TurtleGUI.java VMLogo.ecore
logo.sts
October, 2012
• Keep separation between concerns • For maintainability and evolutions
Logo2NXC.kmt LogoDynSemantics.kmt
LogoSimulator.kmt
LogoNXCCompiler.kmt
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
Do It Yourself ! • Source code of the Logo demo: • https://gforge.inria.fr/scm/viewvc.php/trunk/kmlogo_projects/?
107
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
108
Based on Eclipse/EMF Open Source
root=kermeta • Kermeta (http://www.kermeta.org/):
► Download
it now!
• reference documentation: http://www.kermeta.org/documents • formation supports:
https://gforge.inria.fr/scm/viewvc.php/integration/training_projects/? root=openembedd • More information: • Eclipse Modeling (EMF, GMF...): http://www.eclipse.org/modeling/ • OMG (UML, OCL, MOF...): http://www.omg.org/
• Home page
A statically typed object-oriented executable meta-language
• http://www.kermeta.org • Development page
• Webpage of this talk:
• http://kermeta.gforge.inria.fr/
• http://www.combemale.fr/mde/
27
07/11/12
October, 2012
A Tutorial about Metamodeling © Benoit Combemale
109
References • Eclipse Modeling website: • http://www.eclipse.org/modeling/ • EMF Refcardz "Essential EMF": • http://refcardz.dzone.com/refcardz/essential-emf • Books: • "Eclipse Modeling Framework" (2nd edition), Budinsky et al, Addison Wesley • "Ingénierie Dirigée par les Modèles : des concepts a la
pratique", Jézéquel et al., Ellipses
28