Presentation is loading. Please wait.

Presentation is loading. Please wait.

MOF Model to Text Transformation - MOFScript

Similar presentations

Presentation on theme: "MOF Model to Text Transformation - MOFScript"— Presentation transcript:

1 MOF Model to Text Transformation - MOFScript
This material is intended for in lecturing University courses, such as the INF-5120 course at the Univ. of Oslo. It is assumed that the students are familiar with: MOF QVT The present courseware has been elaborated in the context of the MODELWARE European IST FP6 project ( June 2006

2 Background: Model to text transformation
Outline Background: Model to text transformation Introducing the MOFScript language MOFScript and the relation to MOF/QVT/OCL Details of the MOFScript language: Concrete syntax Examples: From UML class diagrams to Java MOFScript advanced features The MOFScript tool

3 Context of this work The present courseware has been elaborated in the context of the MODELWARE European IST FP6 project ( Co-funded by the European Commission, the MODELWARE project involves 19 partners from 8 European countries. MODELWARE aims to improve software productivity by capitalizing on techniques known as Model-Driven Development (MDD). To achieve the goal of large-scale adoption of these MDD techniques, MODELWARE promotes the idea of a collaborative development of courseware dedicated to this domain. The MDD courseware provided here with the status of open source software is produced under the EPL 1.0 license.

4 Why do we need model-to-text transformation?
Motivation Why do we need model-to-text transformation? Raise the level of abstraction Systems are getting more complex Raise of abstraction has proven useful (for instance: Assembly to COBOL) Automation of the software development process Decrease development time Increase software quality Focus on the creative part Automatic generation of new artefacts from your models Java, EJB, JSP, C# SQL Scripts HTML Test cases Model documentation

5 Motivation - Alternatives
What are the alternatives? Programming languages (e.g Java), Template/scripting languages (e.g XSLT, Velocity Template Language, Eclipse Java Emitter Templates - JET), Model Transformation Languages (e.g. ATLAS Transformation Language (ATL)), proprietary UML-based script languages, DSL-based approaches, Other MOF-based text/code generators Properties of the alternatives: Neither programming languages nor scripting languages tend to take advantage of source metamodels. However, it can be done programmatically in Java (e.g. using Eclipse Modelling Framework (EMF)) Model 2 Model Transformation languages such as ATL is metamodel-based, but is not designed with text generation in mind. However, it can be done also in ATL UML tool script languages are tied to both UML and a vendor, and are not based on standards. DSLs provides the flexibility of metamodel-based tools; they typically hard code code generation for each domain-specific language. The difference between a MOF-based approach and a DSL is not significant, as transformations in MOF-based approaches also will depend on a particular metamodel. Other MOF-based text generators have not been available, but will emerge. Domain Specific Languages (DSL): Proprietary meta-language, often only one tool vendor, has a smaller community than a standard, need to learn a new language for each new system family. It is possible to make DSLs based on UML Profile (light weight) or MOF (heavy weight), generation of modeling environment is however not quite there yet compared to proprietary alternatives like for instance MetaCase. We expect to see good alternatives on the Eclipse Platform (EMF, GEF and GMF)

6 OMG Request for Proposal for a model-to-text transformation language
OMG RFP Issued in 2004 Mandatory Requirements: Generation from MOF 2.0 models to text Reuse (if applicable) existing OMG specifications, in particular QVT Transformations should be defined at the metalevel of the source model Support for string conversion of model data String manipulation Combination of model data with hard coded output text Support for complex transformations Multiple MOF models as input (multiple source models) Optional Requirements round-trip engineering detection/protection of hand-made changes for re-generation traceability is a (possible) means of supporting the last two. Model-to-text is one of the three main model transformation types which OMG attempts to standardize. The other two are: model-to-model (QVT) and text-to-model (ADM- Architecture-Driven Modernization) Some of the requirements are concerned with making the new standard fit into the OMG family of standards (MOF and QVT compliance).

7 What is MOFScript? The MOFScript language is an initial proposal to the OMG model-to-text RFP. The MOFScript tool is an implementation of the MOFScript model to text transformation language An Eclipse plug-in Developed by SINTEF ICT in the EU-supported MODELWARE project Ongoing standardization process within OMG OMG RFP MOF Model to Text Transformation process MOFScript tool and language was part of this process Was in a merging process with other proposal toward the final OMG standard (MOF2Text) Four initial submissions targeted the OMG model-to-text RFP, and MOFScript was one of the two final ones. All submissions have now been merged into a single one: MOF2Text, which also will need further refinement. The current merged MOF2Text proposal does not have not kept many MOFScript syntactical elements. Then OMG will accept or reject the proposal, which normally ends up with an OMG recommendation possibly after some required updates or changes.

8 MOFScript in action UML Java, C#, … RDBMS Documentation MOFScript BPMN
MOF MODELS Textual output UML Java, C#, … RDBMS Documentation MOFScript BPMN SQL The input is any MOF model. The output is any text document. The pink box represents the MOFScript tool execution of a model-to-text transformation defined in the MOFScript language. There might be multiple input MOF models, and there might be multiple output text documents. WSDL XML, HTML… A x B Public class a extends x ……………….. B.wsdl ……………… Z association type Simple c.Html y D C d

9 MOFScript placed in the 4-layer architecture
Source Metamodel Source model MOFScript language MOFScript transformation Target text MOFScript tool engine executed by input output conforms to based on M1 M2 M3 This figure shows the relationship of different metalevels of the OMG MOF Architecture (M1 = Metalevel 1, M2..., M3 indicated on the left side) The abstract syntax of the MOFScript language conforms to MOF A MOFScript transformation is written based on the source metamodel and is executed by the MOFScript tool on a source model at one metalevel lower. The target text does not have an explicitly defined metamodel or any correspondence in the MOF hierarchy.

10 MOFScript - background
Usability Ease of use: Writing and understanding Few constructs End user recognizability Similar to programming and scripting languages Imperatively oriented Sequential execution semantics Rules are called explicitly (except the main() rule) Explicit starting point Contents of rules is executed sequentially Compatibility Alignment with QVT standard and OCL Important design decisions were to: make the language look like the most commonly used programming languages such as Java be aligned with QVT Note that all methods are called explicitly, except the main() method

11 MOFScript extends QVT Mappings
Relations Operational Mappings Core This shows the relationship with MOFScript and the QVT language. MOFScript is a refinement of QVT Operational Mappings --- A MOFScript Text Transformation refines QVT Operational Mapping transformation, and can only contain MOFScript rules. MOFScipt rules specializes QVT Operational Mappings (on the metamodel level). While QVT may be used in three different styles, MOFScript has only one. Side-effects refers to the possibility to update and change variables. MOFScript imperative procedural optional typing side-effects uni-directional object-oriented OCL-based textual

12 MOFScript relates to QVT
MOFScript is strongly influenced by OMGs Query/Views/ Transformations (QVT) OMGs standard for model 2 model transformation QVT is reuses and specialises OCL (adds new expressions) MOFScript specialises QVT Similar notation, reuse of metamodel concepts. Reused by MOFScript Notational changes Not in MS Although the abstract specification claims that it inherits from QVT and OCL, the implementation and the concrete MOFScript syntax is not true inheritance, since some things are not implemented and some things are used but with modifications. This slide shows the correspondence. Examples: Not in MofScript: relations, core, reduced the rule template body part (is shown in a later slide) Reused by MofScript: some parts of a mapping rule, main(), OCL expressions Notational changes: the explicit mapping keyword is left out from QVT rules, forEach() replaces forAll() MofScript additions: string library, white space handling, XML etc... MOFScript additions ”Inheritance” OCL QVT QVT MOFScript MOFScript

13 MOFScript - A text transformation language
Built around a set of rules that are called explicitly: rules appear as methods The language structure is “flat”: A transformation consists of a set of rules/methods Transformations cannot be nested Rules cannot be nested But control structures (if statement and loops) can be nested. Transformations may be imported or subtyped for reusing rules and redefining rules Data types: String, Integer, Real, Boolean, List, Hashtable, Object Variables and constants Global or local, which are optionally typed Untyped variables will assume the type of its assignments variables can be modified That a variable is optionally typed means that you can choose to include the type e.g. var myNumber: Integer, or just say var myNumber = 40. A variable that is not typed will assume the type of its assignments.

14 Function libraries String library Collection library Utility library
size, substring, subStringBefore|After, toLower, toUpper, indexOf, trim, normalizeSpace, endsWith, startsWith, replace, equals, equalsIgnoreCase, charAt, isLowerCase, isUpperCase Collection library Hashmap: put, get, clear, size, keys, values, isEmpty, forEach, List: add, size, clear, isEmpty, first, last, forEach Utility library generateID, time, date, getenv, setenv, indent, tab, space, position, count UML2 Operations m.hasStereoType (“stereotype”): Boolean m.getAppliedStereotypes () : Collection m.getAppliedStereotype (“named stereotype”) : Stereotype m.getValue (stereoType, “property name”), hasValue (stereoType, “prop name”) Most of the string built-in methods are taken from Java or XSLT and are directly supported by MOFScript. The collection types are inspired by Java with the new forEach added. Utility: generateID returns a unique ID for each source model element, getenv/setenv deals with environment properties (global to all transformations in a tool), position and count works within the forEach iterator context. UML2 Operations: Operations available when UML2 models are loaded. Support for one particular source metamodel expected to be commonly used. getAppliedStereotypes() : List (Stereotype) getAppliedStereotype (String name) : Stereotype hasStereotype (String name) : Boolean hasValue (StereoType st, String valueName): Object | hasValue (String stName, String valueName): Object getValue (StereoType st, String valueName):Object   | getValue (String stName, String valueName): Object

15 MOFScript: Concrete syntax
The help menu in Eclipse provides an language reference section where the syntax can be examined in more detail. (In Eclipse with MOFScript help, help contents, MOFScript )

16 Texttransformation Rules Files Escaped output Textual syntax
texttransformation UML2Java (in myMod:uml2) myMod.Package::mapPackage () { 'package ' ';' } textmodule is a synonym and alternative keyword that can be used in place of texttransformation texttransformation defines the input model on which the transformation operates. (What meta-model your model conforms to, in this case the uml2 meta-model). The metamodel reference is given either as the name of the metamodel, or the URI reference of the metamodel. The MOFScript Eclispe plugin provides user help (a metamodel popup) when defining input parameters to a transformation. Your own defined meta-models can be placed in a directory and pointed to from the: Window-prefferences-MOFScript drop-down menu in Eclipse (meta-model repository) Rules are the main equipment to define the transformation The main output device is file There are two ways to generate output/target code: print/println vs. escaped output Notice that the “end of statement” delimiter is optional in MOFScript “ ; ” file f2 ( + “.java”) ' package '';' f2.println (“public class” + 'public class ' ' extends Serializable {'

17 Syntax of a text mapping operation (text transformation rule)
Template abstract? <metamodelContextType>::methodName(Type1 p1, Type2 p2,...) : returnType when { … } { // Main body } metamodelContextType is a source metamodel element. when is a boolean expression, often ocl expressions, that acts as a guard to when the method is actually invoked. Example uml.Class::classToJava(String classPrefix) when {self.getStereotype() = ‘Entity’ } { //body }

18 Simplification of the QVT rule template
mapping <dirkind0> <metamodelContextType>::methodName (<dirkind1> p1:P1, <dirkind2> p2:P2) : r1:R1, r2:R2 when { … } where { … } { init { … } population { … } end { … } } abstract Only one (unnamed) returnType allowed Changed notation: p1:P1  P1 p1 abstract rules are non-existing in QVT. The init and end sections deals with output result instantiation which is left out in MOFScript. This is not so relevant when we do not populate a target metamodel such as in QVT.

19 Textual syntax Entry point rule Iterator (forEach) While loops
myMod.Model::main () { // code for entry point } Entry point rule Iterator (forEach) While loops Conditional statements self.ownedMember->forEach (c:myMod.Class) '<class name=”' ' “/>' } Note that the main() rule is implicitly invoked for each model element corresponding to the context type. The forEach iterator is quite powerful as it applies to strings, integers, model types, collection types. While statement is also supported while (myCounter > 0) { ‘counter value : ‘ counter } if (self.hasStereotype(“Feature”) { ' This is a feature type ' } else if (self.hasStereotype(“Product”)) { ' This is a product type ' } else { ' this is neither ' }

20 Collections Textual syntax var packageNames_List:List
var packageName_Hashtable:Hashtable self.ownedMember->forEach(p:uml.Package) { packageNames_List.add ( packageName_Hashtable.put (, } if (packageName_Hashtable.size () > 0) { ' Listing the package names which do not start with ‘S’ ' packageName_Hashtable->forEach (name:String | not(name.startsWith(“S”)) { ' Package: ' + name The available collection types are: List and Hashtable (basically the same as in Java). Dictionary can be used synonymously to Hashtable. The forEach operator is new to the collection methods in Java. The “->” symbol indicates that this is a collection. Typing “.” after a collection type will automatically insert the “->” symbol (e.g. ownedMember, Hashtable) Strings and expressions can be concatenated using a ‘+’ operator. They will also concatenate using only a sequence of expressions: (‘Package ‘ name  ‘Package ‘ + name) Passing null to a list or hashtable is ignored as an action.

21 Invoking rules Return results Textual syntax
uml.Package::interfacePackages () { if (self.getStereotype() = “Service”){ file ( + ".wsdl") self.wsdlHeader() self.wsdlTypes() self.ownedMember->forEach(i:uml.Interface) { i.wsdlMessages() i.wsdlPortType() i.wsdlBindings() i.wsdlService() } self.wsdlFooter() Invoking rules Return results Rules are explicitly invoked (except for main() ) result is a keyword and acts as a predefined variable of the type given in the rule declaration, (String in the example) result can be reassigned or updated during the entire execution of the rule, and its value will be returned when the rule is finished executing. uml.Package::getPackageNameToLower(): String { result = }

22 Printing to files - example
Scope of file f1 rule1() { file f1 (“”); println(“first output from rule 1”); rule2(); ... f1.println(“second output from rule 1”); } rule2() { println(“first output from rule 2”); file f2 (“”); println(“second output from rule 2”); A file declaration may have a name, as in the example (file f1(“”)). It can, however, also be nameless. All output statements (prints) occurring after a file declaration defaults to the last declared file, unless a file prefix (such as f1) is used. The execution scope of the stream implied by a file (such as f1) is valid through the full lifetime of the execution of the declaring rule (e.g. rule1()). The declared reference for the file (f1) would however not be visible outside the block scope of the declaring structure. Any output statements occurring in invoked rules (such as rule2()) that is not preceded by a file declaration, will use the “current” runtime stream. In the example, it is assumed that execution starts in rule1. This illustrates the use of the current file for the anonymous print statements, and that f1 is available outside of traditional scope. Scope of file f2 The current output stream in the runtime stack will be applied to this statement

23 Properties and variables
Textual syntax Properties and variables property aProperty:String = “myProp” var packageNames:List var packageIdList:Hashtable self.ownedMember->forEach(p:uml.Package) { packageNames.add ( packageIdList.put (, } if (packageIdList.size () > 0) { ' Listing the package names which do not start with S ' packageIdList->forEach (s:String | not(s.startsWith(“S”)) { ' Package: ' s Variables/properties are optionally typed. Properties are constants. Properties/variables can be defined globally for a single transformation (module) or locally within a rule. In addition there are environment properties that apply globally to all transformations. Notice that the concatenations of strings are implicit, but using the “ + ” symbol might improve readability and do also work. (‘Package: ‘ + s)

24 Helper rules / functions
How to define helper rules that do not have a context type? Use the keyword module instead of context type in a transformation rule (or ignore the context type altogether) Helper methods may be defined in a separate MOFScript file to be imported and reused in multiple MOFScript files. module does not mean much. It does not indicate any modularization further than belonging to the current MOFScript transformation definition. Template (module::)? ruleName(Type1 p1, Type2 p2,...) : returnType { // Main body } Example module::factorial(integer n) : integer { if (n = 1) result = 1; else result = n * factorial (n – 1); }

25 Output Files (Output devices)
The built-in stdout keyword represents console output. This is used if no other output device is currently active. The specification shows only how to use files or standard console as output, but describes that other may be defined (SQL db, CVS/SVN etc.). How to use these are not further described. print/println may have an explicit file which overrides and replaces the current one: f1.print() Current output file: Applies to anonymous print/println or escaped output The default file has dynamic scope and will be in scope until the defining file rule is finished executing. The scoping rules for output device is very different from traditional scoping rules. The notion of a current output device is provided to ease the output instructions, which tend to happen often when generating text.

26 Configuration properties: TextMappingDescriptor
Configuration properties that applies to the whole transformation. White space handling, file paths, comment delimiters fileOverWrite (always | never | merge). Defines the strategy when a file already exists. Not implemented in the current MOFScript tool.

27 Examples: From UML class diagrams to Java

28 Uml2Java Example: Class and attributes
//Context class self.ownedAttribute->forEach(p : uml.Property | p.association = null) { p.attributeGetterSetters() } // Generate Getter and Setters uml.Property::attributeGetterSetters () { 'public ' ' get' ' () {\n' ‘\treturn ' ';\n }\n' 'public void set' '(' ' input ) {\n ' ‘\t'self .name ' = input; \n }\n ' Notice that the transformation definition operates on the source metamodel (attribute instead of bookTitle/numberOfPages). Illustrates usage of forEach, escaped output indicated in blue color in the MOFScript code. Target Source public String getBookTitle(){ return bookTitle; } public void setBookTitle(String input){ bookTitle = input; public Integer getNumberOfPages(){ return numberOfPages; public void setNumberOfPages(Integer input){ numberOfPages = input;

29 UML2Java example: Generalization property
uml.Class::outputGeneralization(){ self.generalization->forEach(g: uml.Generalization){ if(not{>forEach(c: uml.Class){ stdout.println("Generalization target name: "+ ) } // forEach }//if target if(not g.source.isEmpty()){ g.source->forEach(c:uml.Class){ stdout.println("Generalization source name: " }//g.source forEach }//if source }//self.generalization }//outputGeneralization() It seems that the two inner forEach are unnecessary, but this is due to the metamodel where a source and target in a single UML.Generalization is a collection. Generalization target name: Individual Generalization source name: Male

30 MOFScript advanced features

31 Transformation inheritance
texttransformation TestInheritanceSub (in ecmodel:ecore) extends TestInheritanceSuper { ecmodel.EPackage::main() { self.printMe() } ecmodel.EPackage::printMe() { stdout.println ("TestInheritanceSub::printMe begin") super.printMe(); stdout.println ("TestInheritanceSub::printMe end") New methods with the same name and context type as in the super are overriding the existing super definition: The code in the same super method will then be ignored, but may be explicitly called by using the super keyword. Multiple inheritance is not allowed

32 Black-box transformations – Integration with Java
A MOFScript transformation can execute externally defined java class methods. Static methods or java classes with a default constructor Method signature The ”Method signature” shows the general form The example below shows the method signature in an external file on the right, and the actual call to this method on the left. Initializing Java classes with non-default constructors (w/parameters) is not possible. java (String className, String methodName, List/Something parameters, String classpath) Example: Compute the factorial of 6 java ("org.test.MathClass", ”factorial”, 6, "c:/Working/TestJava/") MathClass.Java class MathClass { public static integer factorial (Integer n) {..}

33 Using external Java methods w/ advanced parameters
Example: Multiple parameters List parameterList; // Insert parameters to this list ... java ("org.test.SomeClass", ”calculate”, parameterList, "c:/Working/TestJava/") An illustration of more advanced use of alternative 2 with calling external Java methods. Multiple parameters: It does not work if the external Java method takes a List as a parameter. (It can be achieved by sending this List inside a List with a single element). model elements as parameter: self points to a uml.Class which is sent as parameter. Example: source model element as parameter class SomeClass { public static printClass (uml.Class class) {...} } uml.Class::classToJava(String classPrefix) when {} { java ("org.test.SomeClass", ”printClass”, self, "c:/Working/TestJava/") }

34 Proposed metamodel for handling:
Change management Proposed metamodel for handling: Links from a model toward code blocks Traces from a model to text blocks Controlled by user unprotect { ' // User writes code here ' } The resulting code will be generated with protected blocks Identifying the start and end of the section Code is protected by user-defined tags E.g. comment tags A block is a continuous, identifiable structure in a file. An ID is the identifier, or the start position and end position of files that are not manually changed. By default all generated code is protected, that is no manual changes may be performed. unprotect is used to indicate areas where the user may do manual changes and still use the traceability, regeneration features. Reverse-transformation and round-trip engineering is not supported.

35 Traceability model The traceability model allows for viewing and report explicit links between individual elements of the source model and the target text. This facility is expected to evolve and get more support in the MOFScript tool at a later stage.

36 The MOFScript tool

37 Developed at SINTEF ICT
The MOFScript tool An Eclipse plug-in Developed at SINTEF ICT Does not implement the whole specification, particularly with respect to the inheritance from QVT/OCL Supports EMF meta-models and models as input UML2, Ecore, or your own based on EMF

38 MOFScript architecture
MOFScript Architecture Overview: Shows the set of high-level components that make up the MOFScript tool.

39 MOFScript a model to text tool
Editing, compiling and executing Code-completion drop-down box Source code tree outline and colored layout MOFScript console File properties

40 The main steps of using the MOFScript tool
Task: Define a transformation from source model A to text t. (At) Import or define the source metamodel for A. Write the MOFScript to transform A to t in the MOFScript editor Compile the transformation. Any errors in the transformation will be presented. Fix errors, if any Load a source model corresponding to A’s metamodel. Using the Eclipse plugin, this is prompted by the tool when trying to execute. Execute the MOFScript in the MOFScript tool. The transformation is executed. Output text / files are produced.

41 OMG Standard for model-to-text
MOF2Text: A merge of the different model to text proposals, where MOFScript was one of several The only candidate left in the OMG standardization process (model-to-text) Many similarities with MOFScript: imperative language w/ explicit rule calls reusing selected parts of QVT/OCL Differs from MOFScript: Mainly syntactical Context type does not have its own slot, inserted in the parameter list More traditional for-statements instead of forEach Escaping direction is flexible: The transformation code can be escaped, or the output text can be escaped (as in MOFScript). Flexible Escaping Direction provides the possibility to use escaping for the part which is least used in the transformation code.

42 OMG Standard. Example: MOF2Text Templates
[template public ClassToTable(c: Class)] CREATE TABLE [] ( ['_id'/] NUMBER; ); ALTER TABLE [] ADD ( CONSTRAINT ['_pky'/] PRIMARY KEY (['_id'/]); [/template] For the class ‘Person’ the following text will be generated: CREATE TABLE Person ( Person_id NUMBER; ALTER TABLE Person ADD ( CONSTRAINT Person_pky PRIMARY KEY (Person_id); WYSIWYG: Two different colours showing escaped code area (pink) and non-escaped direct output area (green). template is the main tool equipment acting as the transformation rules. The first parameter (or only parameter) will normally correspond to the context parameter of MOFScript Notice that hard coded output can be produced in two ways: string literals inside the escaped code area (‘pky’) or outside the code area (CONSTRAINT).

43 OMG MOF Model to Text Transformation RFP MOFScript submission
References OMG MOF Model to Text Transformation RFP MOFScript submission MOFScript tool

Download ppt "MOF Model to Text Transformation - MOFScript"

Similar presentations

Ads by Google