revised submission for mof 2.0 …mlaguna/cd/05-03-02.pdf · query/view/transformation rfp...

191
Revised submission for MOF 2.0 Query/View/Transformation RFP (ad/2002-04-10) QVT-Merge Group version 2.0 ad/2005-03-02 Submitted by: Adaptive, Alcatel, UMTP, Compuware, DSTC, IBM, Interactive Objects, Kennedy Carter, Softeam, Sun Microsystems, Tata Consultancy Services, Thales, TNI- Valiosys Supported by: Artisan Software, CEA, France Telecom, INRIA, King's College London, LIFL, Sodifrance, University of Paris VI, University of York, Xactium, Codagen Technologies Corp MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , MARCH 21, 2005

Upload: dinhbao

Post on 11-Jun-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

Revised submission for

MOF 2.0Query/View/Transformation

RFP (ad/2002-04-10)

QVT-Merge Group

version 2.0

ad/2005-03-02

Submitted by:Adaptive, Alcatel, UMTP, Compuware, DSTC, IBM,Interactive Objects, Kennedy Carter, Softeam, SunMicrosystems, Tata Consultancy Services, Thales, TNI-ValiosysSupported by:Artisan Software, CEA, France Telecom, INRIA, King'sCollege London, LIFL, Sodifrance, University of ParisVI, University of York, Xactium, Codagen TechnologiesCorp

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , MARCH 21, 2005

2

Copyright ©2005 Kings College LondonCopyright ©2005 Tata Consultancy ServicesCopyright ©2005 University of YorkCopyright ©2005 France TelecomCopyright ©2005 ThalesCopyright ©2005 Codagen Technologies CorpCopyright ©2005 SofteamCopyright ©2005 Sun MicrosystemsCopyright ©2005 CompuwareCopyright ©2005 TNI-ValiosysCopyright ©2005 University of Paris VICopyright ©2005 INRIACopyright ©2005 IBMCopyright ©2005 Interactive ObjectsCopyright ©2005 DSTC

The companies and individuals listed above hereby grants a royalty-free license to the ObjectManagement Group, Inc. (OMG) for worldwide distribution of this document or any derivative worksthereof within OMG and to OMG members for evaluation purposes, so long as the OMG reproduces thecopyright notices and the below paragraphs on all distributed copies. The companies and individuals listed above have granted to the Object Management Group, Inc. (OMG) anonexclusive, royalty-free, paid up, worldwide license to copy and distribute this document and to modifythis document and distribute copies of the modified version.The copyright holders listed above have agreed that no person shall be deemed to have infringed thecopyright, in the included material of any such copyright holder by reason of having used the specificationset forth herein or having conformed any computer software to the specification. NOTICE: The information contained in this document is subject to change with notice. The material inthis document details a submission to the Object Management Group for evaluation in accordance withthe license and notices set forth on this page. This document does not represent a commitment toimplement any portion of this specification by the submitter. WHILE THE INFORMATION IN THISPUBLICATION IS BELIEVED TO BE ACCURATE, THE OBJECT MANAGEMENT GROUP ANDTHE COMPANIES AND INDIVIDUALS LISTED ABOVE MAKE NO WARRANTY OF ANY KINDWITH REGARD TO THIS MATERIAL INCLUDING, BUT NOT LIMITED TO THE IMPLIEDWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. The Object Management Group and the companies and individuals listed above shall not be liable forerrors contained herein or for incidental or consequential damages in connection with the furnishing,performance or use of this material. The copyright holders listed above acknowledge that the Object Management Group (acting itself orthrough its designees) is and shall at all times be the sole entity that may authorize developers, suppliersand sellers of computer software to use certification marks, trademarks or other special designations toindicate compliance with these materials. This document contains information that is patented which is protected by copyright. All Rights Reserved.No part of the work covered by copyright hereon may be reproduced or used in any form or by any means-- graphic, electronic, or mechanical, including photocopying, recording, taping, or information storageand retrieval systems -- without permission of the copyright owners. All copies of this document mustinclude the copyright and other information contained on this page. The copyright owners grant member companies of the OMG permission to make a limited number ofcopies of this document (up to fifty copies) for their internal use as part of the OMG evaluation process.RESTRICTED RIGHTS LEGEND. Use, duplication, or disclosure by government is subject torestrictions as set forth in subdivision (c) (1) (ii) of the Right in Technical, Data and Computer SoftwareClause at DFARS 252.227.7013.OMG is a registered trademark of the Object Management Group, Inc.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

3

Table of Contents

1 PREFACE........................................................................................................ 6

1.1Submitters and Contact Points..................................................................................6

1.2Resolution of RFP Requirements.............................................................................. 7

2SCOPE............................................................................................................ 18

3CONFORMANCE............................................................................................ 19

3.1Conformance Points................................................................................................. 19

3.2Language Dimension................................................................................................ 19

3.3Interoperability Dimension......................................................................................20

4NORMATIVE REFERENCES......................................................................... 21

5TERMS AND DEFINITIONS........................................................................... 22

5.1Glossary..................................................................................................................... 22

6SYMBOLS....................................................................................................... 25

7ADDITIONAL INFORMATION........................................................................ 26

7.1Changes to Adopted OMG Specifications..............................................................26

7.2Structure of the Specification.................................................................................. 26

8QVT OVERVIEW............................................................................................. 27

8.1Two Level Decalarative Architecture..................................................................... 27

8.2Imperative Implementations....................................................................................28

8.3Execution Scenarios..................................................................................................29

8.4MOF Metamodels..................................................................................................... 29

9THE RELATIONS LANGUAGE...................................................................... 31

9.1Transformations and Typed Models...................................................................... 31

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

4

9.2Relations and Domains.............................................................................................31

9.3Check and Enforce................................................................................................... 31

9.4Pattern Matching......................................................................................................33

9.5Checking semantics.................................................................................................. 35

9.6Enforcement semantics............................................................................................ 37

9.7Change propagation semantics................................................................................40

9.8Pattern Matching Semantics....................................................................................40

9.9Restrictions on expressions used in the relational language.................................44

9.10Integrating black-box operations with relations................................................. 44

9.11In-place transformations........................................................................................45

9.12Abstract Syntax and Semantics.............................................................................45

9.13Standard Library....................................................................................................55

9.14Concrete Syntax......................................................................................................55

10OPERATIONAL MAPPINGS........................................................................ 65

10.1Overview..................................................................................................................65

10.2Abstract Syntax and Semantics.............................................................................80

10.3Standard Library..................................................................................................118

10.4Concrete Syntax....................................................................................................121

11THE CORE LANGUAGE............................................................................. 129

11.1Transformations and directions..........................................................................129

11.2Patterns..................................................................................................................130

11.3Bindings................................................................................................................. 131

11.4Binding dependencies...........................................................................................131

11.5Guards................................................................................................................... 132

11.6Checking................................................................................................................132

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

5

11.7Enforcement.......................................................................................................... 133

11.8Mapping refinement............................................................................................. 136

11.9Mapping composition...........................................................................................136

11.10Functions............................................................................................................. 136

11.11Abstract Syntax and Semantics.........................................................................137

11.12Concrete Syntax..................................................................................................141

12RELATIONS TO CORE TRANSFORMATION............................................ 143

12.1Mapping approach............................................................................................... 143

12.2Mapping rules....................................................................................................... 144

12.3Relational Expression of Relations To Core Transformation..........................152

A.ADDITIONAL EXAMPLES.......................................................................... 170

A.RELATIONS EXAMPLES............................................................................ 170

B.UML TO RDBMS MAPPING....................................................................... 170

C.OPERATIONAL MAPPING EXAMPLES..................................................... 177

D.BOOK TO PUBLICATION EXAMPLE........................................................ 177

E.ENCAPSULATION EXAMPLE ................................................................... 177

F.UML TO RDBMS......................................................................................... 178

G.SPEM UML PROFILE TO SPEM METAMODEL........................................ 180

H.CORE EXAMPLES...................................................................................... 182

I.UML TO RDBMS MAPPING ........................................................................ 182

B.OCL METAMODEL ADAPTATION............................................................. 189

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

6

1 Preface1.1 SUBMITTERS AND CONTACT POINTS

For information about this submission, contact:

Keith DuddyDSTC Pty LtdGeneral Purpose SouthUniversity of QueenslandQueensland 4072Australiaphone: +61 7 3365 4310fax: +61 7 3365 4311email: [email protected]

Sreedhar ReddyTata Consultancy Services Limited54B, Hadapsar Industrial EstateHadapsarPune 411 013Indiaphone: +91 20 5604 2402 fax: +91 20 5604 2399email: [email protected]

Mariano BelaundeFrance Telecom R&DTechnopole Anticipa2 avenue Pierre MarzinLannion 22FrancePhone: +33 2 96 05 15 63Fax: +33 2 96 05 39 45Email: [email protected]

Wim BastCompuware Europe B.V.Hoogoorddreef 5, PO Box 129331100 AX AmsterdamThe Netherlandsphone: +31 20 311 6368email: [email protected]

Submitters

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

7

This document is submitted by the following OMG members:Adaptive, Alcatel, UMTP, Compuware, DSTC, IBM, Interactive Objects, Softeam, SunMicrosystems, Tata Consultancy Services, Thales, TNI-Valiosys.

SupportersThis document is supported by the following companies:Artisan Software, CEA, Colorado State University, France Telecom, INRIA, KennedyCarter, Kinetium, King's College London, LIFL, University of Paris VI, University ofYork, Xactium, Codagen Technologies Corp

Submission teamThe following people have been chiefly responsible for the work involved in thisversion of the submission:

CompuwareWim Bast, Michael Murphree

DSTCMichael Lawley, Keith Duddy

France Telecom R&DMariano Belaunde

IBMCatherine Griffin, Shane Sendall

INRIADidier Vojtisek, Jim Steel

Interactive Objects Simon Helsen

King's College LondonLaurence Tratt

Tata Consultancy ServicesSreedhar Reddy, R. Venkatesh

University of Paris VIXavier Blanc

AcknowlegementsMany other people have made contributions to the ideas in this submission. This is anincomplete list:

Michel Brassard, Eric Brière, Tracy Gardner, Alan Kennedy, Kerry Raymond, AnnaGerber, Laurent Rioux, Madeleine Faugère, Benoit Langlois, Jens Rommel, PhilippeDesfray, Biju Appukuttan, Tony Clark, Andy Evans, Girish Maskeri, Paul Sammut,James Willans, Jim Rumbaugh, Jean Bézivin, Frédéric Jouault, Erwan Breton, MartinMatula, Pete Rivett, Ed Willink.

1.2 RESOLUTION OF RFP REQUIREMENTS

1.2.1 Mandatory Requirements

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

8

1. Proposals shall define a language for querying models. The query language shallfacilitate ad-hoc queries for selection and filtering of model elements, as well as for theselection of model elements that are the source of a transformation.This submission largely uses OCL 2.0 as its query language. Some additional subtypesof OCL metamodel elements are introduced in the QVT models. These can be found inthe Abstract Syntax and Semantics sections: 9.12, 10.2, and 11.11.

No explicit support for ad-hoc query results management is provided in thisspecification.

2. Proposals shall define a language for transformation definitions. Transformationdefinitions shall describe relationships between a source MOF metamodel S, and atarget MOF metamodel T, which can be used to generate a target model instanceconforming to T from a source model instance conforming to S. The source and targetmetamodels may be the same metamodel.The concept of source and target models has been generalised to support multi-directional transformation definitions in the Relations Language (Section 8.3) and theCore Language (Section 11.1). The concept of a Domain, introduced in the QVTBasepackage (Section 9.12.1) has a reference typedModel. This refers to a TypedModelmetaclass which defines a name for each potential source or target model, and restrictsthe types found in that model to those defined in certain MOF packages.

Operational Mappings specifications always have a direction defined in terms of a targetTypedModel. Relations and Core specifications allow for the nomination of aTypedModel at runtime which defines which direction the transformation will executein.

3. The abstract syntax for transformation, view and query definition languages shall bedefined as MOF (version 2.0) metamodels.All QVT packages are defined using EMOF from MOF 2.0, and extend the MOF 2.0and OCL 2.0 specifications.

4. The transformation definition language shall be capable of expressing all informationrequired to generate a target model from a source model automatically. This is possible with Relations, Operational Mappings and Core specifications. Inaddition there is an optional capability to define some parts of a transformation usingblack-box Operation implementations. If this feature is used, portability oftransformation descriptions is not guaranteed, but without its use transformationsdescriptions will be capable of expressing all information required to generate a targetmodel from a source model automatically. They will also be portable amongimplementations that support the same conformance points. See the Conformancestatement in Section 3.

5. The transformation definition language shall enable the creation of a view of ametamodel.Views are not supported by this specification.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

9

6. The transformation definition language shall be declarative in order to supporttransformation execution with the following characteristic:

• Incremental changes in a source model may be transformed into changes in a targetmodel immediately.The Relations and Core languages support this mode of execution. The details can befound in Section 8.3 – Execution Scenarios.

7. All mechanisms specified in Proposals shall operate on model instances of metamodelsdefined using MOF version 2.0.This is the case.

1.2.2 Optional Requirements

1. Proposals may support transformation definitions that can be executed in twodirections. There are two possible approaches:

• Transformations are defined symmetrically, in contrast to transformations that aredefined from source to target.

• Two transformation definitions are defined where one is the inverse of the other.The Relations and Core languages support the former approach, while the OperationalMappings Language supports the latter.

2. Proposals may support traceability of transformation executions made between sourceand target model elements. Trace classes are implicitly generated from Relations to trace executions of Relationaltransformations, and Operational Mapping transformations. These are made explicitwhen mapping Relations to their equivalent Core representation. See Section 12 fordetails.

In the Core Language trace classes are explicitly created and/or matched bytransformations in the same way as any other class instance, however there is adistinguished part of Mappings that facilitates their special role as the bridge betweenthe models being transformed. See Section 11.1.1 for further explanation.

3. Proposals may support mechanisms for reusing and extending generic transformationdefinitions. For example: Proposals may support generic definitions of transformationsbetween general metaclasses that are automatically valid for all specialized metaclasses.This may include the overriding of the transformations defined on base metaclasses.Another solution could be support for transformation templates or patterns. Transformations are defined using MOF polymorphism, and so naturally supportspecialisations such as those suggested. Transformation Rules in all Languages definedin this specification have extension and overriding capabilities, which may be based onspecialized class matching, or any other OCL constraint.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

10

Patterns are available in the Relations language, and in a less sophisticated form in theCore language, but these are not used as the basis for Rule specialization.

4. Proposals may support transactional transformation definitions in which parts of atransformation definition are identified as suitable for commit or rollback duringexecution. We anticipate that these facilities will be made available to all MOF tools via theforthcoming MOF facilities specifications. Transactions are not dealt with specificallyin this specification.

5. Proposals may support the use of additional data, not contained in the source model, asinput to the transformation definition, in order to generate a target model. In additionproposals may allow for the definition of default values for this data.Transformations may include MOF Tags for name/value pairs known at the time oftransformation specification. For data required in order to execute a transformation, theMOF Class base type of the Transformation metaclass allows for the defininition ofproperties which must be given appropriately typed values at runtime. See Section9.12.1.1 which defines the Transformation metaclass.

6. Proposals may support the execution of transformation definitions where the targetmodel is the same as the source model; i.e. allow transformation definitions to defineupdates to existing models. For example a transformation definition may describe howto calculate values for derived model elements. This is not an explicitly required capability in any compliance point, however, someguidance is given in Section 9.11.

1.2.3 Issues to be discussed

1. The OMG CWM specification already has a defined transformation model that is beingused in data warehousing. Submitters shall discuss how their transformationspecifications compare to or reuse the support of mappings in CWM. It was considered more appropriate to reuse MOF and OCL as the basis of QVT, whichprecluded CWM as a basis for this specification. There is no explicit reuse of CWM.However, the placeholder for definitions of transformations in CWM may well be filledby some implementations of that standard by QVT definitions.

2. The OMG Action Semantics specification already has a mechanism for manipulatinginstances of UML model elements. Submitters shall discuss how their transformationspecifications compare to or reuse the capabilities of the UML Action Semantics.UML Action semantics was considered too fine grained and too imperative for reuse byQVT. In addition it explicitly defines actions for UML, and not for MOF. QVT mustnecessarily be more generic. OCL expressions have been reused as they provide a moredeclarative language for the query and selection of model elements.

3. How is the execution of a transformation definition to behave when the source model isnot well-formed (according to the applicable constraints?).

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

11

This is not explicitly stated in this specification. Different tools and engines will providedifferent styles of support to users to get their models into a well-formed state. Modelssupplied as sources, or partially completed targets to the execution of a transformationmust be well-formed to achieve expected results.

Also should transformation definitions be able to define their own preconditions. Inthat case: What's the effect of them not being met? There are several kinds of relationships between transformations and their source andtarget models specified in this document. Firstly, each Rule in a transformation mayhave guard conditions which must be met before that Rule is applied to any modelelements. In this case, there is no effect when the guard is not met.

Also, Rules can be written for the purpose of checking that certain conditions hold overa model, or between models without changing the models. In this case a tool must reportthat the specified relationship does not hold.

In other cases Rules can be enforced, which may result in the creation or deletion ofobjects and values. When the Rule is a hybrid between declarative and imperative thedeclarative part may have postconditions which are also checked, and if they do nothold, an error is reported.

What if a transformation definition applied to a well-formed model does not produce awell-formed output model (that meets the constraints applicable to the targetmetamodel)? The usual rule, Garbage In Garbage Out, applies... it is possible in any language towrite inconsistent programs. An implementation of this standard may choose toimplement various kinds of transformation checking, or model checking, but thisstandard assumes that a complete and consistent transformation is applied to well-formed models.

4. Proposals shall discuss the implications of transformations in the presence ofincremental changes to the source and/or target models. The scenario of multi-directional transformations which may support incremental re-application of transformations is explicitly supported by the Core Language, and henceby the Relations Language, which is defined in terms of the Core semantics. See Section8.3 – Execution Scenarios.

However, the ability to support sophisticated incremental evaluation, perhaps based onnotifications of changes to MOF models, although facilitated by the specification, is notrequired by the Conformance Points (found in Section 3). This is an opportunity forvendor and product differentiation.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

12

1 PREFACE........................................................................................................ 7

1.1Submitters and Contact Points..................................................................................7

1.2Resolution of RFP Requirements.............................................................................. 91.2.1Mandatory Requirements............................................................................ 91.2.2Optional Requirements.............................................................................. 101.2.3Issues to be discussed.............................................................................. 11

2SCOPE............................................................................................................ 20

3CONFORMANCE............................................................................................ 21

3.1Conformance Points................................................................................................. 21

3.2Language Dimension................................................................................................ 21

3.3Interoperability Dimension......................................................................................22

4NORMATIVE REFERENCES......................................................................... 23

5TERMS AND DEFINITIONS........................................................................... 24

5.1Glossary..................................................................................................................... 24

6SYMBOLS....................................................................................................... 27

7ADDITIONAL INFORMATION........................................................................ 28

7.1Changes to Adopted OMG Specifications..............................................................28

7.2Structure of the Specification.................................................................................. 28

8QVT OVERVIEW............................................................................................. 29

8.1Two Level Decalarative Architecture..................................................................... 298.1.1Relations .................................................................................................. 298.1.2Core........................................................................................................... 308.1.3Virtual Machine Analogy............................................................................ 30

8.2Imperative Implementations....................................................................................308.2.1Operational Mappings Language.............................................................. 308.2.2Black Box Implementations....................................................................... 31

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

13

8.3Execution Scenarios..................................................................................................31

8.4MOF Metamodels..................................................................................................... 31

9THE RELATIONS LANGUAGE...................................................................... 33

9.1Transformations and Typed Models...................................................................... 33

9.2Relations and Domains.............................................................................................33

9.3Check and Enforce................................................................................................... 339.3.1Where and When Clauses........................................................................ 34

9.4Pattern Matching......................................................................................................359.4.1Keys and Object Creation using Patterns................................................. 37

9.5Checking semantics.................................................................................................. 37

9.6Enforcement semantics............................................................................................ 39

9.7Change propagation semantics................................................................................42

9.8Pattern Matching Semantics....................................................................................429.8.1Introduction................................................................................................ 429.8.2Pattern infrastructure................................................................................. 439.8.3QVT Template Expressions...................................................................... 44

9.9Restrictions on expressions used in the relational language.................................46

9.10Integrating black-box operations with relations................................................. 47

9.11In-place transformations........................................................................................47

9.12Abstract Syntax and Semantics.............................................................................489.12.1QVTBase Package.................................................................................. 489.12.2Function................................................................................................... 519.12.3FunctionParameter.................................................................................. 519.12.4QVTTemplate Package........................................................................... 529.12.5QVTRelation Package............................................................................. 559.12.6Key.......................................................................................................... 58

9.13Standard Library....................................................................................................58

9.14Concrete Syntax......................................................................................................589.14.1Relations Textual Syntax Grammar........................................................ 589.14.2Expressions syntax (extensions to OCL).................................................599.14.3Graphical Syntax..................................................................................... 60

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

14

10OPERATIONAL MAPPINGS........................................................................ 68

10.1Overview..................................................................................................................6810.1.1Operational transformations.................................................................... 6810.1.2Query Libraries........................................................................................ 6910.1.3Mapping operations as refinements of relations..................................... 7010.1.4Structure of the body of a mapping......................................................... 7110.1.5Supporting object orientation and class extension.................................. 7110.1.6Object creation and object population..................................................... 7210.1.7Inlining of mapping operations................................................................ 7410.1.8Using constructor operations................................................................... 7510.1.9Helpers and intermediate data................................................................ 7510.1.10Updating objects and resolving object references.................................7610.1.11Reuse facilities: importing transformations and libraries....................... 7810.1.12Dynamic definition and invocation of transformations........................... 7910.1.13Reuse facilities: mapping extension...................................................... 8010.1.14Disjunction of mapping operations........................................................ 8110.1.15Typedefs............................................................................................... 8210.1.16Imperative expressions......................................................................... 8210.1.17Pre-defined variables: this, self and result............................................ 8410.1.18Null........................................................................................................ 84

10.2Abstract Syntax and Semantics.............................................................................8410.2.1OperationalTransformation..................................................................... 9110.2.2Library..................................................................................................... 9510.2.3LibraryUsage........................................................................................... 9610.2.4TransformationUsage.............................................................................. 9710.2.5ModelParameter...................................................................................... 9710.2.6ModelType............................................................................................... 9810.2.7DirectionKind......................................................................................... 10010.2.8TransformationExp................................................................................ 10010.2.9ContextualOperation............................................................................. 10110.2.10Helper.................................................................................................. 10210.2.11EntryOperation.................................................................................... 10310.2.12MappingOperation............................................................................... 10310.2.13Constructor.......................................................................................... 10610.2.14ContextualProperty.............................................................................. 10710.2.15VarParameter...................................................................................... 10710.2.16MappingParameter.............................................................................. 10710.2.17MappingCallExp.................................................................................. 10810.2.18ConstructorCallExp............................................................................. 10910.2.19ResolveExp......................................................................................... 10910.2.20ResolveInExp...................................................................................... 11010.2.21CloneExp............................................................................................. 11110.2.22MappingBody...................................................................................... 11110.2.23MappingSection................................................................................... 11310.2.24ObjectExp............................................................................................ 11310.2.25BlockExp............................................................................................. 114

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

15

10.2.26DoExp.................................................................................................. 11410.2.27WhileExp............................................................................................. 11510.2.28ForEachExp......................................................................................... 11510.2.29SwitchExp............................................................................................ 11610.2.30AltExp.................................................................................................. 11710.2.31VariableInitExp.................................................................................... 11710.2.32AssignExp........................................................................................... 11810.2.33UnlinkExp............................................................................................ 11910.2.34TryExp................................................................................................. 12010.2.35RaiseExp............................................................................................. 12010.2.36ReturnExp........................................................................................... 12010.2.37BreakExp............................................................................................. 12110.2.38ContinueExp........................................................................................ 12110.2.39TupleExp............................................................................................. 12110.2.40TypeExp.............................................................................................. 12110.2.41NullLiteralExp...................................................................................... 12210.2.42Typedef............................................................................................... 12210.2.43AnyType.............................................................................................. 122

10.3Standard Library..................................................................................................12310.3.1Virtual operations for marking .............................................................. 12310.3.2stereotypedBy....................................................................................... 12310.3.3_parent.................................................................................................. 12310.3.4_localId.................................................................................................. 12310.3.5_globalId................................................................................................ 12310.3.6format.................................................................................................... 12310.3.7repr........................................................................................................ 12410.3.8assert..................................................................................................... 12410.3.9debug.................................................................................................... 12410.3.10ModelType operations......................................................................... 12410.3.11Transformation class operations......................................................... 12410.3.12Predefined tags................................................................................... 125

10.4Concrete Syntax....................................................................................................12510.4.1EBNF..................................................................................................... 12510.4.2Mapping from concrete notation to abstract syntax...............................131

11THE CORE LANGUAGE............................................................................. 134

11.1Transformations and directions..........................................................................13411.1.1Mappings............................................................................................... 134

11.2Patterns..................................................................................................................135

11.3Bindings................................................................................................................. 136

11.4Binding dependencies...........................................................................................136

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

16

11.5Guards................................................................................................................... 137

11.6Checking................................................................................................................137

11.7Enforcement.......................................................................................................... 13811.7.1Enforcement with black-box operations................................................ 141

11.8Mapping refinement............................................................................................. 142

11.9Mapping composition...........................................................................................142

11.10Functions............................................................................................................. 142

11.11Abstract Syntax and Semantics.........................................................................14311.11.1Area..................................................................................................... 14311.11.2Mapping............................................................................................... 14411.11.3CoreDomain........................................................................................ 14411.11.4GuardPattern....................................................................................... 14411.11.5BottomPattern..................................................................................... 14511.11.6RealizedVariableDeclaration............................................................... 14511.11.7Assignment.......................................................................................... 14611.11.8enum EnforcementMode..................................................................... 14711.11.9EnforcementOperation........................................................................ 147

11.12Concrete Syntax..................................................................................................147

12RELATIONS TO CORE TRANSFORMATION............................................ 149

12.1Mapping approach............................................................................................... 149

12.2Mapping rules....................................................................................................... 150

12.3Relational Expression of Relations To Core Transformation..........................158

A.ADDITIONAL EXAMPLES.......................................................................... 176

A.RELATIONS EXAMPLES............................................................................ 176

B.UML TO RDBMS MAPPING....................................................................... 176

C.OPERATIONAL MAPPING EXAMPLES..................................................... 183

D.BOOK TO PUBLICATION EXAMPLE........................................................ 183

E.ENCAPSULATION EXAMPLE ................................................................... 183

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

17

F.UML TO RDBMS......................................................................................... 184

G.SPEM UML PROFILE TO SPEM METAMODEL........................................ 186

H.CORE EXAMPLES...................................................................................... 188

I.UML TO RDBMS MAPPING ........................................................................ 188

B.OCL METAMODEL ADAPTATION............................................................. 195

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, MARCH 21, 2005

18

2 Scope

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

19

3 ConformanceQVT language conformance is specified along two orthogonal dimensions: thelanguage dimension and the interoperability dimension. Each dimension specifies a setof named levels. Each intersection of the levels of the two dimensions specifies a validQVT conformance point. All conformance points are valid by themselves, whichimplies that there is no general notion of "QVT conformance". Instead, a tool shall statewhich conformance points it implements, as described below in Section 3.1.

3.1 CONFORMANCE POINTS

Any combination of two named levels, one from each dimension, constructs aconformance point. 3.1 specifies the 12 different possible conformance points. A toolcan claim to be conformant according to one or more of these 12 conformance points.

Interoperability DimensionLanguage Dimension

Export XMI-Export Execution XMI-Execution

Core

Relations

Operational Mappings

Figure 1. Conformance Table

For example, a tool could be QVT-Relations-Executable, QVT-Relations-XMI-Exportable, and QVT-Core-Exportable. Another tool could be QVT-Core-Exportableand QVT-Relations-Exportable.

There is one implicit requirement: A tool which is QVT-Executable or QVT-XMI-Executable for a particular language level shall also be QVT-Exportable conformant orQVT-XMI-Exportable conformant, respectively, for the same language level.

3.2 LANGUAGE DIMENSION

The language dimension consists of the three named language levels:

• Core: The Core language is described in Section 11. This includes the ability toinsert black-box implementations via MOF operations as specified.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

20

• Relations: The Relations language is described in Section 9. This includes theability to insert black-box implementations via MOF operations as specified.

• Operational Mappings: The Operational Mappings Language is described inSection 10.

3.3 INTEROPERABILITY DIMENSION

The interoperability dimension has four named interoperability levels:

• Export: An implementation shall provide a facility to export a model-to-modeltransformation in the concrete syntax of the language given by the languagedimension.

• XMI-Export: An implementation shall provide a facility to export a model-to-model transformation into its XMI serialization which conforms to the MOFmeta-model of the language given by the language dimension.

• Execution: An implementation shall provide a facility to import or read, andthen execute the concrete syntax description of a transformation in the languagegiven by the language dimension. The execution shall be according to thesemantics of the chosen language as described in this document.

• XMI-Execution: An implementation shall provide a facility to import or read,and then execute an XMI serialization of a transformation description whichconforms to the MOF meta-model of the language given by the languagedimension. The execution shall be according to the semantics of the chosenlanguage as described in this document.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

21

4 Normative ReferencesMOF 2.0 SpecificationUML 2.0 OCL specification

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

22

5 Terms and Definitions5.1 GLOSSARY

Area In the context of a core mapping an area is a pair of patterns,consisting of a guard pattern and a bottom pattern. Area is anabstract metaclass, and its concrete subtypes are CoreDomain(where its purpose is to match instances in source and targetmodels) and Mapping (where its purpose is to match the traceinstances).

Bottom Pattern A pattern which is checked or enforced for the bindingsgenerated by the guard pattern of the same area of a mapping,and other patterns which this area is related to for execution in aparticular direction.

Core Domain A specialised kind of domain that forms part of a mapping. Acore domain is also an area which defines a pair of patterns,consisting of a guard pattern and a bottom pattern.

Domain A domain is a distinguished set of variables to be matched in atyped model. It is related to other domains by a transformationrule.

Domain is an abstract type in the QVTBase package which hasconcrete types RelationDomain and CoreDomain.

Domains have flags to indicate whether they are checkonly orenforced. When a transformation is executed with the typedmodel of this domain as its target model, and it is an enforceddomain, values may be created or destroyed in the typed modelin order to satisfy the rules of the relation to which it belongs.

Guard Pattern A pattern which must hold as a precondition to the applicationof the bottom pattern related to it in an area of a core mapping.

Identifying Property A property of class that is part of a key defined in a relationaltransformation.

Incremental Update Once a relationship (a set of trace instances) has beenestablished between models by executing a transformation,small changes to a source model may be propagated to a targetmodel by re-executing the transformation in the context of thetrace, causing only the relevant target model elements to bechanged, without modifying the rest of the model.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

23

Key In the context of relations a key is a definition of whichproperties of a MOF class, in combination, can uniquely identifyan instance of that class. These properties are called identifyingproperties, and are used when matching template patterns todetermine how many instances of a class should exist in arelationship by creating or locating an instance for each uniquekey that can be derived from the values bound to the identifyingproperties.

Mapping A transformation rule in a Core transformation description. It isan area, consisting of a pair of patterns which are designed tolocate or create instances of the trace classes which store therelationships between models. It also owns a set of coredomains which identify the model elements in those models tobe related to one another.

Relation A relation is a subset of an N-ary product of sets, A1 x A2 x ... xAN, and may be represented as a set of N-tuples (a1, a2,..., aN). Inthe context of MOF, each set AK, called a domain, is a MOFtype, and a relation will be populated by tuples referring tomodel elements of those types which exist in MOF extents.

A Relation in the QVT specification also defines the rules bywhich the exact subset of model elements to be related isdetermined. These rules comprise variables of additional MOFtypes, template pattern matches on the structure of the relationdomains which bind values to the variables, OCL constraintsover the relation domains and variables of the relation, andassertions that other relations hold.

Relations imply the existence of equivalent trace classes whichhave properties for each of its domains, and whose set of traceinstances are equivalent to the relation's population of tuples.

Relation Domain A specialisation of the concept of a domain. In a Relation adomain is a type which may be the root of a template pattern,which can match any model element navigable from that type.

A domain implies the existence of a property of the same type ina trace class derived from the relation to which it belongs.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

24

Template Pattern A template pattern is a combination of a literal as defined inOCL which can match against instances of a class and values forany of its properties, including recursive matching of other classinstances which are values of those properties. It also allows forthe binding of variables to any value matched in that structure,including collections of values. Template Patterns are part of thedefinition of a relation domain. They provide a terse, user-friendly expression of what can be quite verbose expressions inordinary OCL. Template Patterns rely on identifying propertiesof classes, defined by keys to further simplify the specificationof relationships between relation domains.

Trace Class A MOF class with properties that refer to objects and values inmodels that are related by a transformation. Instances of theseclasses (trace instances) are created during the execution of atransformation so that relationships between models that arecreated by the execution can be stored. In the context of theRelations Language, a trace class is derived from each Relation,with a property to represent each domain of the relation.

Trace Instance An instance of a trace class which represents the linkagebetween models established by a transformation execution.These instances may be used to aid in propagating incrementalupdates to a source model into a target model without re-executing the entire transformation.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

25

6 Symbols

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

26

7 Additional Information7.1 CHANGES TO ADOPTED OMG SPECIFICATIONS

This specification does not make any changes to existing OMG specifiations.

However, it does presume that the forthcoming OCL 2.0 Final Adopted Specificationwill contain a number of bug fixes, and will provide a valid semantic binding for MOF2.0.

7.2 STRUCTURE OF THE SPECIFICATION

This specification defines three related transformation languages: Relations, OperationalMappings, and Core.

Section 8 – QVT Overview, describes the relationships between the three langaugemodels, and gives an overview of their purposes and features.

Section 9 – The Relations Language, provides the details of this language, and itsevaluation semantics. It shows the MOF metamodel and describes the elements of thatmodel. It gives the concrete syntax for the language. It also describes how black-boxoperation implementations can be used.

Section 10 – Operational Mappings, provides the details of this language in terms ofimperative mappings which extend the QVTBase package introduced in the previoussection, as well as side-effect extensions to OCL 2.0, and their evaluation semantics. Itshows the MOF metamodel and describes the elements of that model. It gives theconcrete syntax for the language.

Section 11 – The Core Language, describes the Core on which the semantics of theRelations Language is based. The core evaluation semantics is given in semi-formal set-theoretic notation. Then the MOF metamodel and descriptions of its elements are given.

Section 12 – Relations to Core Transformation, gives the transformation from anarbitrary Relations specification for a particular execution direction, to an equivalentCore specification and trace classes. This allows Relational transformation descriptionsto be understood in terms of the formal semantics of the Core.

Finally, Appendix 12.3 – Additional Examples, provides some whole transformationexamples to augment the excerpt examples shown inline in the rest of the specification.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

27

8 QVT OverviewThe QVT specification has a hybrid declarative/imperative nature, with the declarativepart being split into a two-level architecture. We start by explaining the two-levelarchitecture of the declarative part, as it forms the framework for the executionsemantics of the imperative part.

8.1 TWO LEVEL DECALARATIVE ARCHITECTURE

The declarative parts of this specification are structured into a two-layer architecture. The layers are:

• A user-friendly Relations metamodel and language which supports complexobject pattern matching and object template creation. Traces between modelelements involved in a transformation are created implicitly.

• A Core metamodel and language defined using minimal extensions to EMOFand OCL. All trace classes are explicitly defined as MOF models, and traceinstance creation and deletion is defined in the same way as the creation anddeletion of any other object.

Figure 2. Relationships between QVT metamodels

8.1.1 Relations A declarative specification of the relationships between MOF models. The Relationslanguage supports complex object pattern matching, and implicitly creates trace classesand their instances to record what occurred during a transformation execution. Relationscan assert that other relations also hold between particular model elements matched bytheir patterns. The semantics of Relations are defined in a combination of English andfirst order predicate logic in Section 8.3, as well as by a standard transformation for anyRelations model to trace models and a Core model with equivalent semantics. Thistransformation can be found in Section 12. It can be used purely as a formal semanticsfor Relations, or as a way of translating a Relations model to a Core model for executionon an engine implementing the Core semantics.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

Relations

Core

RelationsToCore Transformation

declarative imperative

Operational Mappings

&

Black Box Impls

28

8.1.2 CoreThis is a small model/language which only supports pattern matching over a flat set ofvariables by evaluating conditions over those variables against a set of models. It treatsall of the model elements of source, target and trace models symmetrically. It is equallypowerful to the Relations language, and because of its relative simplicity, its semanticscan be defined more simply, although transformation descriptions described using theCore are therefore more verbose. In addition, the trace models must be explicitlydefined, and are not deduced from the transformation description, as is the case withRelations. The core model may be implemented directly, or simply used as a referencefor the semantics of Relations, which are mapped to the Core, using the transformationlanguage itself. The definition of the Core semantics is given in Section 11.

8.1.3 Virtual Machine AnalogyAn analogy can be drawn with the Java architecture, where the Core langauge is likeJava Byte Code and the Core semantics is like the behaviour specification for the JavaVirtual Machine. The Relations language plays the role of the Java language, and thestandard transformation from Relations to Core is like the specification of a JavaCompiler which produces Byte Code.

8.2 IMPERATIVE IMPLEMENTATIONS

In addition to the declarative Relations and Core Languages which embody the samesemantics at two different levels of abstraction, there are two mechanisms for invokingimperative implementations of transformations from Relations or Core: one standardlanguage, Operational Mappings, as well as non-standard Black-box MOF Operationimplementations. Each relation define a class which will be instantiated to trace betweenmodel elements being transformed, and it has a one-to-one mapping to an Operationsignature that the Operational Mapping or Black-box implements.

8.2.1 Operational Mappings LanguageThis language is specified as a standard way of providing imperative implementations,which populate the same trace models as the Relations Language. It is given in Section10. It provides OCL extensions with side effects that allow a more procedural style, anda concrete syntax that looks familiar to imperative programmers.

Operational Mappings can be used to implement one or more Relations from aRelations specification when it is difficult to provide a purely declarative specificationof how a Relation is to be populated. Operational Mappings invoking other OperationalMappings always involves a Relation for the purposes of creating a trace between modelelements, but this can be implicit, and an entire transformation can be written in thislanguage in the imperative style.

8.2.2 Black Box ImplementationsMOF Operations may be derived from Relations making it possible to "plug-in" anyimplementation of a MOF Operation with the same signature. This is beneficial forseveral reasons:

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

29

• It allows complex algorithms to be coded in any programming language with a MOFbinding (or that can be executed from a language with a MOF binding).

• It allows the use of domain specific libraries to calculate model property values. Forexample, mathematical, engineering, bio-science and many other domains havelarge libraries that encode domain-specific algorithms which will difficult, if notimpossible to express using OCL.

• It allows implementations of some parts of a transformation to be opaque.

However, it is also dangerous. The plugin implementation has access to objectreferences in models, and may do arbitrary things to those objects. Black boximplementations do no have an implicit relationship to Relations, and each black boxmust explicitly implement a Relation, which is responsible for keeping traces betweenmodel elements related by the Operation implementation. In these cases, the relevantparts of the models can be matched by a Relation, and passed out to implementations inthe most relevant langauge for processing.

To extend the Java architecture analogy, the ability to invoke black box and operationalmapping implementations can be considered equivalent to calling the Java NativeInterface (JNI).

8.3 EXECUTION SCENARIOS

The semantics of the Core language (and hence the Relations language) allow for thefollowing execution scenarios:

• Check-only transformations to verify that models are related in a specified way.• Single direction transformations.• Bi-directional transformations. (In fact more than two directions are possible,

but two is the most common case.)• The ability to establish relationships between pre-existing models, whether

developed manually, or though some other tool or mechanism.• Incremental updates (in any direction) when one related model is changed after

an initial execution.• The ability to create as well as delete objects and values, while also being able to

specify which objects and values must not be modified.

The operational mapping and black box approaches, even when executed in tandemwith relations, restrict these scenarios by only allowing specification of transformationsin a single direction. Bi-directional transformations are only possible if an inverseoperational implementation is provided separately. However, all of the other capabilitiesdefined above are available with imperative and hybrid executions.

8.4 MOF METAMODELS

This specification defines three main packages, one for each of the languages defined:QVTCore (Section 11.11), QVTRelation (Section 9.12.5) and QVTMappingOperations(Section 10.2). All of these depend on a package defining common structure forTransformations: QVTBase (Section 9.12.1).

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

30

In addition the QVTRelation package uses Template Pattern Expressions defined in theQVTTemplateExp package (Section 9.12.4).

QVTMappingOperations extends QVTRelation, as it uses the same framework fortraces defined in that package.

All of QVT depends on the Expressions package from OCL 2.0, and all of the languagepackages depend on EMOF.

Figure 3. Dependencies between MOF Packages defined in the QVT specification

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

31

Figure 4.

9 The Relations Language9.1 TRANSFORMATIONS AND TYPED MODELS

A transformation specifies a set of relations that must hold between the model elementsof a set of candidate models. These models are named, and the types of elements theycan contain are restricted to those within a set of referenced packages. A transformationexecution is in a particular direction, which is defined as the selection of one of themodels as a target. The execution of the transformation proceeds by attempting to makeall the relations hold by modifying only the target model. Some relations only checkwhether a relationship holds between the candidate models and an execution will eitherconfirm this, or report errors when they do not.

9.2 RELATIONS AND DOMAINS

A relation specifies a relationship that must hold between the model elements of thedifferent candidate models. A relation consists of two or more domains, and a pair ofconstraints known as the guard clause (or when clause) and the where clause. Eachdomain nominates a candidate model, and in the simplest case, a type to match in thatmodel. However domains have patterns, which can be viewed as a graph of objectnodes, their properties and association links originating from an instance of the domain'stype. Alternatively a pattern can be viewed as a set of variables, and a set of constraintsthat model elements bound to those variables must satisfy in order to qualify as a validbinding of the pattern. A domain pattern can be considered a template for objects andtheir properties that must be located, modified, or created in a candidate model in orderto satisfy the relation.

A relation's guard clause specifies the conditions under which the relationship needs tohold, i.e. the relationship is required to hold only when the guard condition is satisfied.A relation's where clause specifies the condition that must be satisfied by all modelelements participating in the relationship, and it may constrain any of the variables inthe relation and its domains.

9.3 CHECK AND ENFORCE

A relation domain may be marked as 'checkonly' or 'enforced' - a checked domain issimply checked to see if there exists a valid match in the relevant model that satisfiesthe relationship; whereas for a domain that is enforced, when the relationship does nothold, model elements may be created, deleted or modified in the target model for theexecution in order to satisfy the relationship.

Let us use an example to illustrate some of the above.

transformation umlRdbms (uml uses SimpleUML, rdbms uses SimpleRDBMS) {

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

32

In this transformation declaration, named "umlRdbms" there are two typed candidatemodels – "uml" and "rdbms". The model named "uml" declares the SimpleUMLpackage as its meta model, and the model named "rdbms" declares the SimpleRDBMSpackage as its meta model. At runtime the transformation umlRdbms may be executedeither in the direction of the "uml" model or in the direction of the "rdbms" model. Thatis, either the model containing SimpleUML elements will be the target, or the modelcontaining SimpleRDBMS elements will be the target. The target model may be empty,or may contain existing model elements to be related by the transformation. For non-trivial executions, it is assumed the source model contains model elements, in a wellformed configuration.

relation PackageToSchema /* map each package to a schema */ { checkonly domain uml p:Package {name=pn} enforce domain rdbms s:Schema {name=pn} }

In the above relation, "PackageToSchema", two domains are declared (and empty guardand where clauses) which will match elements in the "uml" and "rdbms" modelsrespectively. They both specify simple patterns – a package with a name, and a schemawith a name. The domain for the uml model is marked as check only and the domain forthe rdbms model is marked as both enforced (which entails checking).

If we are executing the transformation umlRdbms in the direction of rdbms then foreach package in the uml model, the relation checks if there exists a schema with samename in the rdbms model, and if it does not, a new schema is created in that model withthe given name.

However, if we are executing in the direction of uml and there exists a schema in rdbmsfor which we do not have a corresponding package with same name in uml, then it issimply reported as an inconsistency – a package is not created because uml is notenforced, it is only checked.

To consider another variation of the above scenario, if we are executing in the directionof rdbms and there exists a schema in rdbms for which there does not exist acorresponding package with the same name in uml, then that schema will be deletedfrom the rdbms model. Otherwise the models will be inconsistent with the checkingsemantics of the uml direction. Please note that in this execution scenario schemadeletion will be the outcome even if the uml domain is marked as enforced, because thetransformation is being executed in the direction of rdbms, and object creation,modification and deletion can only take place in the target model for the currentexecution.

9.3.1 Where and When ClausesA relation can be constrained by two sets of predicates. Consider the following relation:

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

33

relation ClassToTable /* map each persistent class to a table*/ { checkonly domain uml c:Class { namespace = p:Package {}, kind='Persistent', name=cn } enforce domain rdbms t:Table { schema = s:Schema {}, name=cn, column = cl:Column{name=cn+'_tid', type='NUMBER'},

key = k:Key{name=cn+'_pk', column=cl} } when { PackageToSchema(p, s); } where { AttributeToColumn(c, t); } }

In the above example the relation ClassToTable has a guard (when) clause and a whereclause. The guard clause states that the relation ClassToTable needs to hold only whenthe PackageToSchema relation holds between the package containing the class and theschema containing the table. The where clause specifies that when the ClassToTablerelation holds the relation AttributeToColumn must also hold.

9.4 PATTERN MATCHING

Let us use an example to discuss matching of the patterns associated with domains,known as object template expressions. We continue to use ClassToTable above as anexample.

ClassToTable defines several object template expressions which are used to matchpatterns in candidate models. A template expression match results in a binding of modelelements from the typed model to variables declared by the domain. A templateexpression match may be performed in a context where some of its variables mayalready have bindings to model elements (e.g. resulting from an evaluation of the guardclause or other template expressions). In this case template expression match findsbindings only for the free variables of the domain.

In the case of the domain associated with the "uml" model, the pattern will bind all thevariables in the expression ("c", "p", and "cn"), starting from the domain's root variable"c" of type Class. In this example the variable "p" already has a binding resulting fromthe evaluation of the guard expression PackageToSchema(p, s). The matching proceedsby filtering all of the objects of type Class in the "uml" model, eliminating any which do

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

34

not have the same literal values for their properties as the template expression. In theexample, any Class with its "kind" property not set to 'Persistent' is eliminated.

Properties that are compared to variables, such as "name=cn" will have the "cn" variablebound to the value of the name property for all classes that are not filtered out due to amismatch with other property comparisons. The value of "cn" will be either used inanother domain, or can have additional constraints placed on it in the where expressionof the domain or its owning relation.

Then the matching proceeds to properties shown with their values compared to nestedtemplate expressions. For example, the property pattern "namespace = p:Package {}"will match only classes which have a non-null reference to a Package. At the same time,the variable "p" will be bound to refer to the Package. However, since in our example" p" is already bound in the guard expression, the pattern will only match those classesthat have a reference to the package bound to " p".

Arbitrarily deep nestings of template expressions are permitted, and matching andvariable binding proceeds recursively until there is a set of value tuples corresponding tothe variables of the domain and its template expression. For example the three variables:"c", "p" and "cn". These make a 3 tuple, and each valid match will result in a uniquetuple representing the binding.

In a given relation invocation, there may be multiple such valid matches for a giventemplate expression. How this multiplicity is dealt with depends on the executiondirection.

For instance if ClassToTable is executed with rdbms as the target model, then for eachvalid match (i.e. valid tuple of variable bindings) of the uml domain, there must exist atleast one valid match of the rdbms domain that satisfies the where clause. If for a givenvalid match of the uml domain, there does not exist a valid match of the rdbms domain,then (since rdbms domain is enforced) objects are created and properties are set asspecified in the template expression associated with the rdbms domain. Also for eachvalid match of the rdbms domain, there must exists at least one valid match of the umldomain that satisfies the where clause (this is required since uml is marked checkonly –see below); otherwise objects will be deleted from the rdbms model such that it is nolonger a valid match.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

35

9.4.1 Keys and Object Creation using Patterns

As mentioned previously, an object template expression also serves as a template forcreating an object. However, we do not want to create a new object when it alreadyexists in the model. But how do we ensure this? The MOF allows for a single propertyof a class to be nominated as identifying. However, for most metamodels, this isinsufficient to uniquely identify many kinds of objects. The relations metamodelintroduces the concept of keys to identify any number of properties of a Class thattogether make a unique identifier for an object.

For example, continuing with the ClassToTable relation, we might wish to specify thatfor our transformation that a well-formedness criterion for simpleRDBMS modelsincluded unique names for tables of a schema. We can state this as follows:

key Table {schema, name};

Keys are used during object creation – if an object template expression has propertiescorresponding to a key of the associated class, then the key is used to locate a matchingobject in the model; a new object is created only when a matching object does not exist.

In our example, consider the case where we have a persistent class with name ‘foo’ inuml model and a table with a matching name ‘foo’ in a matching schema in the rdbmsmodel but that does not have an associated primary key. In this case as per our patternmatching semantics we do not have a valid match in rdbms and so we need to createobjects to satisfy the relation. However, since the existing table matches the keyproperties (i.e. name and schema), we do not have to create a new table; we just have toupdate the table with the primary key.

9.5 CHECKING SEMANTICS

Here we give a semi-formal semantics of relations. A more formal semantics are givenin the section on ‘relations to core mapping’ in Section 12 by specifying how a relationspecification maps to the core model.

For the purpose of semantics definition assume that a relation has the following form:

Relation R{ Var <R_variable_set> // declaration of variables used in therelation [checkonly | enforce] Domain:<direction_1>

<domain_1_variable_set> // subset of<R_variable_set> { <domain_1_pattern> [<domain_1_condition>] } ... [checkonly | enforce] Domain:<direction_n>

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

36

<domain_n_variable_set> // subset of<R_variable_set> { <domain_n_pattern> [<domain_n_condition>] } // n >= 2 [when <when_variable_set> <when_condition>] [where <where_condition>]}

Please note the following relationships:

• <domain_k_variable_set> is a subset of <R_variable_set> for k = 1..n• The intersection of domain variable sets need not be null, i.e. a variable may

occur in multiple domains.• The intersection of a domain_variable_set and when_variable_set need not be

null.

Given the above, checking of relation R in <direction_k> evaluates to TRUE if thefollowing predicate calculus formula evaluates to TRUE.

We use the following syntactic convention in the formulae:

|<variable_set>| - a binding of variables of the set <variable_set>ForAll |<variable_set>| - for all bindings of variables of the set Exists |<variable_set>| - there exists a binding of variables of the set<exclusive_domain_k_variable_set> – variables occuring exclusively in domain k,i.e. those variables of domain k that do not occur in any other domain or the whenclause. It is a subset of <domain_k_variable_set>.

Check(R, <direction_k>)=ForAll |<when_variable_set>|( <when_condition> implies ( ForAll |(<R_variable_set> minus (<when_variable_set> union <exclusive_domain_k_variable_set>))| ( ( (<domain_1_pattern> and <domain_1_condition>) and .... (<domain_k-1_pattern> and <domain_k-1_condition>) and (<domain_k+1_pattern> and <domain_k+1_condition>) and .... (<domain_n_pattern> and <domain_n_condition>) )

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

37

implies ( Exists |<exclusive_domain_k_variable_set>| ( (<domain_k_pattern> and <domain_k_condition>) and <where_condition> ) // Exists ) // implies ) // ForAll ) // implies) // ForAll

In the above formula the term <domain_k_pattern> refers to the set of constraintsimplied by the pattern of domain k. Please refer to Section 9.8 for a detailed discussionon pattern matching semantics.

9.6 ENFORCEMENT SEMANTICS

Enforcement of a relation with model k as the target model has the following semantics:

For each valid binding of variables of the guard (when) clause and variables of domainsother than the current target direction domain k that satisfy the guard condition andsource domain patterns and conditions, if there does not exist a valid binding of theremaining unbound variables of domain k that satisfies domain k's pattern and wherecondition, then create objects (or select and modify if they already exist) and assignproperties as specified in domain k pattern. A more formal definition is given below.

Also, for each valid binding of variables of domain k pattern that satisfies domain kcondition, if there does not exist a valid binding of variables of the guard clause andsource domains that satisfies the guard condition, source domain patterns and wherecondition, and at least one of the source domains is marked 'checkonly' (or 'enforce',which entails check), then delete the objects bound to the variables of domain k if thefollowing condition is satisfied: delete an object only if it is not required to exist as perenforcement semantics for any of the valid bindings of the source domains (i.e. avoiddelete followed by create). A more formal definition is given below.

Enforce(R, <direction_k>)=Create(R, <direction_k>)and // and is deliberate!Delete(R, <direction_k>)Create(R, <direction_k>)=ForAll |<when_variable_set>|( <when_condition> implies (

ForAll |(<R_variable_set> minus (<when_variable_set> union <exclusive_domain_k_variable_set>))| (

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

38

( (<domain_1_pattern> and <domain_1_condition>) and .... (<domain_k-1_pattern> and <domain_k-1_condition>) and (<domain_k+1_pattern> and <domain_k+1_condition>) and .... (<domain_n_pattern> and <domain_n_condition>) ) implies (

Exists |<exclusive_domain_k_variable_set>| ( (<domain_k_pattern> and <domain_k_condition>) and <where_condition> ) // Exists or ( // assert that there are no remaining free varsother than the object // node vars of the domain pattern. pl see the section'Restrictions on // expressions used in the relaional language' for a moredetailed // discussion. assert( (<exclusive_domain_k_variable_set> minus getObjectVars(domain_k_pattern)) = NULL ) and ForAll objVar in (getObjectVars(domain_k_pattern)) ( createOrUpdate(objVar, objVar.boundTemplate, (<R_variable_set> minus <exclusive_domain_k_variable_set>)) ) ) // or ) // implies ) // ForAll ) // implies) // ForAll

createOrUpdate(unboundObjectVar, objectTemplate, boundVarableContext):Boolean{ 1. If the object template contains identifying properties corresponding to at least one of the keys of the class of the object, then try to locate such an object in the model; if there is no such object, then create a new object. 2. bind unboundObjectVar to the object found or created in step 1. 3. assign properties of the object as specified by the property template items of the object template. 4. return TRUE.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

39

}

Please note: Object creation semantics depends on the notion of identifying propertiesof a class. QVT extends MOF core to specify keys for classes. A key is a set ofproperties of a class that uniquely identify an instance of the class in a model extent. Aclass may have multiple keys (as in relational databases).

Delete(R, <direction_k>)=(not exists od in R.domain ((od.direction != <direction_k>) andod.isChecked = TRUE))orForAll |<domain_k_variable_set>|( (<domain_k_pattern> and <domain_k_condition>) implies ( not Exists |(<R_variable_set> minus <domain_k_variable_set>)| ( <when_condition> and (<domain_1_pattern> and <domain_1_condition>) and .... (<domain_k-1_pattern> and <domain_k-1_condition>) and (<domain_k+1_pattern> and <domain_k+1_condition>) and .... (<domain_n_pattern> and <domain_n_condition>) and <where_condition> ) // not Exists implies ( ForAll objVar in makeSet(<domain_k_variable_set>) ( // delete the object only if it is not required toexist as per enforcement // semantics for any of the valid bindings of theopposite domains not Exists |<domain_k_variable_set>| // new scope ( (<domain_k_pattern> and <domain_k_condition>) and Exists |(<R_variable_set> minus<domain_k_variable_set>)| ( <when_condition> and (<domain_1_pattern> and <domain_1_condition>) and .... (<domain_k-1_pattern> and <domain_k-1_condition>) and (<domain_k+1_pattern> and <domain_k+1_condition>) and

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

40

.... (<domain_n_pattern> and <domain_n_condition>) and <where_condition> ) // Exists and belongsTo(objVar, makeSet(<domain_k_variable_set>)) ) // not Exists implies delete(objVar) ) // ForAll ) // implies ) // implies) // ForAll

The relations-to-core mapping in Section 12 provides a more precise definition of theabove check and enforcement semantics.

9.7 CHANGE PROPAGATION SEMANTICS

In relations, the effect of propagating a change occurring in one of the oppositedirections to an enforced direction is semantically equivalent to executing the entiretransformation afresh in the enforced direction. The enforcement semantics of objectcreation and deletion guarantee that no redundant creations and no unwarranteddeletions take place. Tool implementations may of course perform change propagationin a more efficient manner. The relations to core mapping provides one suchimplementation option, as core mappings support incremental change propagation moredirectly.

Please refer to Section 12 on relations to core mapping for a more detailedunderstanding of how change propagation is handled in core and how that applies torelations.

9.8 PATTERN MATCHING SEMANTICS

9.8.1 IntroductionPatterns are one of the more powerful features offered by the Relations language. Tosimplify the description of the semantics we first present a simple "infrastructure" modelof patterns and explain their semantics. Then Section 9.8.3 explains how Templateexpressions as used within a QVT relation specification can be transformed to thissimple model. The example meta-model of 9.8.1 and its corresponding instance modelof 9.8.1 are used as examples throughout the text.

attrs Attribute

Name

Class

Name Kind

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

41

Figure 5. SimpleUML Model

:Class Name = "c1"

Kind = "P"

:Class Name = "c2"

Kind = "T"

:Attribute

Name = "c1a1"

:Attribute

Name = "a2"

:Attribute

Name = "a3"

:Attribute

Name = "a4"

Figure 6. Instance Model

9.8.2 Pattern infrastructureTo simplify the semantics definition we assume a pattern to have the following abstractstructure

Pattern = {

e1: <classname1>, e2: <classname2> …. en:<classnameN>l1 : <assoc1> (ei, ej) …. lm:<assocM>(eu, ew)where <predicate>

}

A pattern can be viewed as a graph where the pattern elements, e1, e2, …en, with types<classname1>, <classname2>…<classnamen> respectively, are the nodes of the graphand pattern links l1, l2, …lm are the edges. The predicate is a Boolean expression thatmay refer to the pattern elements. The predicates may refer to variables other than thepattern elements; these are the free variables of a pattern. A pattern is used to findmatching sub-graphs in a model. A sub-graph of a model consisting of objects o1, o2, …on, matches a pattern as described above if and only if :

• o1 is of type <classname1> or one of its subtypes, and o2 is of type <classname2> orone of its subtypes, and so on…

• oi and oj are linked by association <assoc1> and ou and ow are linked by association<assoc2>, and so on…

• There exists one or more bindings of values to free variables such that <predicate>evaluates to true when references to e1,e2, …en are replaced by o1, o2, …on

respectively.

Once a pattern has matched each ei is bound to the corresponding oi and each freevariable vi is bound to the value with which the <predicate> was evaluated whileperforming the match. For example:

Pattern {

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

42

c1: Class, a1: Attributel1: attrs (c1, a1) where c1.name = X and a1.name = X + Y}

In the above example X and Y are free variables. The only sub-graph of the model inFigure 2 that matches the above pattern is <c1, c1a1>. This matching binds X to “c1”and Y to “a1”

9.8.2.1 Collection PatternsThe type of elements in a pattern could be a collection such as – Set, OrderedSet, Bag orSequence. If the type of ei is a collection of type <classnamei> then a sub-graph of amodel matches the pattern if and only if• oi is a collection of objects from the model of type <classnamei>• There is no collection of objects from the model of type <classnamei>, oj such that oi

is a sub-collection of oj and replacement of oi with oj will satisfy the other patternmatching criteria

• If lj: <assocname>(em, ei) is a link in the pattern and the type of em is <classnamem>then every element of oi must be linked to om by the association <assocname>

• If lj: <assocname>(em, ei) is a link in the pattern and the type of em is also set of<classnamem> then every element of oi must be linked to every element of om by theassociation <assocname>

For example:

Pattern {c1: Class, a1: Set(Attribute)l1: attrs (c1, a1) where TRUE}

The two sub-graphs <c1, {c1a1, a2}> and <c2, {a3, a4}> of the instance model in 9.8.1match the above pattern.

ConstraintsA pattern must have at least one element. Only first order sets are allowed, i.e.,Elements cannot have type set of sets.

9.8.3 QVT Template ExpressionsHere we describe how the QVT Template Expressions (9.12.4), can be transformed tothe infrastructure described above.

The Template Expressions model consists of TemplateExp, which is an abstract classspecialized by ObjectTemplateExp and CollectionTemplateExp. ObjectTemplateExp istransformed to a pattern element with type as the referredClass of theObjectTemplateExp. If the ObjectTemplateExp is bound to a variableExp then the nameof the variableExp is the name of the element else a unique name is generated for theelement.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

43

A CollectionTemplateExp is transformed to a pattern element with type as a Collection.An ObjectTemplateExp has a set of PropertyTemplateItems; if the value expressionassociated with a PropertyTemplateItem is another ObjectTempalteExp then theproperty is transformed to a link. The predicate part of a pattern is a conjunction of thefollowing • An ObjectTemplateExp has a set of associated PropertyTemplateItems. Each

PropertyTemplateItem has an associated value Expression. This expression istransformed into a predicate on the property that is referred to by thePropertyTemplateItem

• A CollectionTemplateItem has a part expression that is a predicate. This predicate isretained as is

• For every CollectionTemplateItem an additional predicate asserting that thecollection is non-empty is added

• A TemplateExp has an associated where expression that is a predicate. This is alsoretained as is

For example, consider the pattern specified by the concrete syntax:

Class { name = X, attribute = Attribute {name = X + Y}}

The instance model for the above example is shown in 9.8.3. For brevity the detailedstructure of OCL expressions is excluded and only the final VariableExp is shown in thefigure.

Figure 4. QVT Instance Pattern Model

:ObjectTemplateExp Class

:VariableExp

name = 'X'

:PropertyTemplateExp

name = "name"

:PropertyTemplateExp

name = "attribute"

:ObjectTemplateExp

value

:VariableExp

name = 'Y'

value

Figure 7. Example Pattern Instance

The pattern structure corresponding to the above model is: Pattern {

dummy: Class, dummy1: Attribute: attribute (dummy, dummy1)freevars X, Y

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

44

where dummy.name = X and dummy1.name = X + Y}

9.9 RESTRICTIONS ON EXPRESSIONS USED IN THE RELATIONAL LANGUAGE

In order to guarantee executability – i.e. there exists a bounded algorithm to enforce arelation in a given direction – expressions occurring in a relation are required to satisfythe following conditions:

1. It should be possible to order the set of expressions that occur in the when clause,source domains and where clause, such that only the following kinds of expressionsoccur in the set:1.1. An expression of the form

<object>.<property> = <variable>

Where <variable> is a free variable, and <object> is either a variable bound to anObjectTemplateExp of an opposite domain pattern or a variable that gets a binding froma preceding expression in the expression order. This expression provides a binding forvariable <variable>.1.2. An expression of the form:

<object>.<property> = <expression>

Where <object> is either a variable bound to an ObjectTemplateExp of a domain patternor a variable that gets a binding from a preceding expression in the expression order.There are no free variable occurences in <expression> (variable occurrences if anyshould all have been bound in the preceding expressions)1.3. No other expression has free variable occurences (all their variable occurrences should have been bound in the preceding expressions)

2. It should be possible to order the set of expressions that occur in the enforced domain,such that only the following kinds of expressions occur in the set:2.1. An expression of the form

<object>.<property> = <expression>

Where <object> is either a variable bound to an ObjectTemplateExp of the domainpattern or a variable that gets a binding from a preceding expression in the expressionorder. There are no free variable occurrences in <expression> (variable occurrences ifany should all have been bound in the preceding expressions)2.2. No other expression has free variable occurrences (all their variable occurrencesshould have been bound in the preceding expressions)

9.10 INTEGRATING BLACK-BOX OPERATIONS WITH RELATIONS

A relation may optionally have an associated black-box operational implementation toenforce a domain. The black-box operation is invoked when the relation is executed in

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

45

the direction of the enforced domain and the relation evaluates to false as per thechecking semantics. The invoked operation is responsible for making the necessarychanges to the model in order to satisfy the specified relationship. It is a runtimeexception if the relation evaluates to false after the operation returns. The signature ofthe operation can be derived from the domain specification of the relation – an outputparameter corresponding to the enforced domain, and an input parameter correspondingto each of the other domains.

The Relations which may be implemented by OperationalMappings and Black boxOperations are restricted in the following ways:

• They may not have any when or where cluases.• Their domains may not have template expressions or where clauses.

These restrictions allow for a simple call-out semantics, which does not need anyconstraint evaluation before, and constraint checking after the operation invocation.Guards, Patterns and other machinery can be used in a "wrapper" relation which invokesthe simple relation with values constrained buy the wrapper.

9.11 IN-PLACE TRANSFORMATIONS

A transformation may be considered in-place when its source and target directions areboth bound to the same model at runtime. The following additional comments apply tothe enforcement semantics of an in-place transformation:- A relation is re-evaluated after each enforcement-induced modification to a target

pattern instance of the model.- A relation’s evaluation stops when all the pattern instances satisfy the relationship.

9.12 ABSTRACT SYNTAX AND SEMANTICS

The Relations metamodel is structured into three packages: QVTBase, QVTTemplate,and QVTRelation.

9.12.1 QVTBase PackageThis package contains a set of basic concepts, many reused from the EMOF and OCLspecifications, that structure transformations, their rules, and their input and outputmodels. It also introduces the notion of a Pattern as a set of predicates over Variables inOCL Expressions.

9.12.1.1TransformationA Transformation is a Package to contain and provide a namespace for a set of Rules. Itis also a Class whose Properties define the configuration values needed at runtime, andOperations which can be implemented as utility functions for the transformation. Itcontains a set of Rules which can be executed at run time. It has a number ofTypedModels, which can be nominated as sources or targets for execution in a particulardirection.

Supertypes

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

46

• Class• Package

Associations• modelParameter: TypedModel [*] {composes}

TypedModels which a Transformation will used as inputs or outputs duringan execution.

• rule: Rule [*] {composes}the Rules owned by the Transformation, which together give it a runtimesemantics when a particular direction for execution is chosen.

• ownedTag: Tag [*] {composes}the MOF Tags that the transformation expects to have values for to configureits runtime environment.

• extends: Transformation [0..1]a Transformation whose Rules will be included in this transformation.Extension is transitive.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

47

Figure 8. QVTBase Package (partial) – Transformations and Rules

9.12.1.2TypedModelA TypedModel is a parameter to a Transformation. A model which is passed to theTransformation by this name is constrained to only contain elements of the typescontained in a given set of Packages. When the set of Rules that form a Transformationare executed, a direction is for the execution is always given in terms of whichTypedModel is to be the target of the transformation.

The Domains of a Mapping must each refer to the TypedModel in which the instancesthat match the domain's patterns will be found.

Supertypes• NamedElement

Associations• transformation: Transformation [1]

the Transformation which owns the Direction.• usedPackage: Package [1..*]

the Packages from which all the types of class-typed Variables in a Domainwith this direction must be drawn.

• dependsOn: TypedModel [*]a reference to another TypedModel which will also need to be matchedagainst when this model is a source model.

9.12.1.3DomainA Domain is a named abstract type which is used to refer to a TypedModel within aRule. The manner of evaluation of the patterns and constraints associated with itsconcrete subtypes will be determined by the value of the isChecked and isEnforcedattributes.

SuperTypes• NamedElement

Attributes• isChecked : Boolean

indicates that the patterns of this Domain will be evaluated with respect tocurrent values in the models supplied.

• isEnforced : Booleanindicates that the model associated with this domain may be updated toenforce the transformation.

Associations• rule: Rule [1]

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

48

the owning Rule of this Domain• typedModel: TypedModel [1]

the TypedModel in which the Domain's patterns will be matched at runtime.

9.12.1.4RuleA Rule is a named abstract type which is used to capture information about how atransformation is executed. It contains a number of Domains which refer to the modelsthat are parameters to the transformation. A rule specification will establish arelationship between the elements matched by those domains.

SuperTypes• NamedElement

Associations• domain: Domain [*] {composes}

the Domains owned by this Rule • transformation: Transformation[1]

the Transformation of which this Rule is a part• overrides: Rule [0..1]

a Rule which this Rule overrides. The semantics of overriding are given bythe concrete subtypes of Rule.

Figure 9. QVTBase Package (partial) – Patterns and Functions

9.12.2 Function

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

49

A Function is a specialisation of an EMOF Operation owned by a Mapping. Functionsare constrained to have no side-effects, and to produce the same result each time theyare invoked with the same arguments. Functions own FunctionParameters indirectlythrough EMOF Operations owning EMOF Parameters.

SuperTypes• Operation

Associations• queryExpression: OclExpression [0..1] {composes}

an Optional specification of the function in OCL. If this reference does notexist, then a black-box implementation is assumed.

9.12.3 FunctionParameterA FunctionParameter is a parameter to an EMOF Operation when specialised to as aFunction owned by a Mapping. It also specialises VariableDeclaration from OCL toallow for the parameters to be used in Predicates (and other OCLExpressions) as namedvariables.

SuperTypes• Parameter• VariableDeclaration

9.12.3.1PredicateA Predicate is the owner of an OCL Expression which evaluates to a Boolean result.The expression usually contains references to the variables of the Pattern owning thePredicate.

SuperTypes• Element

Associations• conditionExpression: OclExpression [1] {composes}

the OCL Expression.• pattern: Pattern [1]

the Predicate's owning Pattern.

9.12.3.2PatternA Pattern is a set of VariableDeclarations and Predicates, which when evaluated in thecontext of a set of model elements, results in a set of bindings for the variables.

SuperTypes• Element

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

50

Associations• bindsTo: VariableDeclaration [*] {composes}

the VariableDeclarations which are to be bound when the Pattern ismatched against a model.

• predicate: Predicate [*] {composes}the Predicates which contain the conditions (expressed as OCL Expressionsover the pattern's variables) which must evaluate to true in order for thepattern to bind values to its variables.

9.12.4 QVTTemplate Package

Figure 10. QVTTemplate Package

9.12.4.1TemplateExpA TemplateExp is a specialization of OCL LiteralExp. Its purpose is to define arbitrarilydeeply nested object and/or collection templates for pattern matching and instantiation.It contains a number of VariableDeclarations which allow for bindings to all elementsin a model which fit the structural form of the top level type of the template. Bindingsare only created if the template's where expression evaluated to true.

SuperTypes• LiteralExp

Attributes

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

51

• isComplete : BooleanTrue if this is a root expression which may be evaluated. False if it is afragment if a larger template. The where property must be null unlessisComplete is true. (i.e. only root template expressions may haveconstraints).

Associations• bindTo: VariableDeclaration [0..1] {composes}

the VariableDeclaration which is to be bound to this part of the templatewhen its root TemplateExp is matched against a model.

• where: OclExpression [0..1] {composes}a boolean expression over all the VariableDeclarations of the parts of theTemplateExp which must evaluate to true in order for the pattern to bind valuesto its variables. A where expression is only valid for a root (isComplete)TemplateExp.

9.12.4.2ObjectTemplateExpAn ObjectTemplateExp is a concrete specialization of TemplateExp. Its purpose is todefine arbitrarily deeply nested object templates for pattern matching and instantiation.The ObjectTemplateExp refers to the Class for which it is a pattern template. It containsa number of PropertyTemplateItems which allow matching of values against Propertiesof its Class. The value attribute of the Template item may be any expression of thecorrect type, including further ObjectTemplateExps in the case of object-valuedproperties, or CollectionTemplateExps in the case of any multi-valued property.

SuperTypes• TemplateExp

Associations• referredClass: Class [1]

the EMOF Class type of objects to be matched by this expression.• part: PropertyTemplateItem [*] {composes}

the PropertyTemplateItems which are to be matched against a model forequality with the property indicated by the part.

9.12.4.3CollectionTemplateExpA CollectionTemplateExp is a concrete specialization of TemplateExp. Its purpose istwofold.

If the ObjectTemplateExp has a memberTemplate, then the every element of theCollection must match the template given by this reference, or else theCollectionTemplate is not matched.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

52

If the ObjectTemplateExp has a filter then the CollectionTemplate will match theCollection returned by adding only members for which the filter expression evaluated totrue.

Exactly one of the filter and memberTemplate references must be valid, and the othermust be null.

SuperTypes• TemplateExp

Associations• memberTemplate: ObjectTemplateExp[0..1] {composes}

an ObjectTemplateExp which each member of the collection must match inorder for the Collection to be a valid match.

• filter: OclExpression [1] {composes}A boolean valued OCL constraint applied to each member of the Collectionto create a sub-collection of those which evaluate true against the filter.

9.12.4.4PropertyTemplateItemA PropertyTemplateItem is a part of an ObjectTemplateExp which nominates aProperty, which must be of the Class identified by the ObjectTemplateExp. It comparesthe value of this property in candidate objects instance against the OCL expressiongiven by its value property. As TemplateExp is a kind of OCL Literal, this allows for thebuild up of recursive template expressions. The value expression must be of acompatible type.

SuperTypes• Element

Associations• referredProperty: Property [1]

the EMOF Property to be matched againt the value expression.• value: OclExpression [0..1] {composes}

the expression to be matched against the referredProperty of thePropertyTemplateItem.

9.12.5 QVTRelation Package

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

53

Figure 11. QVTRelation Package

9.12.5.1RelationA Relation is a set of RelationDomains and pattern constraints (when and whereclauses) which specify how, when executed in a nominated Direction, a set of targetobjects are to be related by a set of trace objects to a provided source model. Theinformal semantics of this execution are described in Sections 9.1, 9.6, and 9.7, and theformal semantics are given by a transformation of Relations specifications to the Coremodel in Section 12.

SuperTypes• Rule

Associations• variable: VariableDeclaration [*] {composes}

the VariableDeclarations of this Relation to be used in the various OCLexpressions associated with the Relation.

• domain: RelationDomain [*] {composes} (from Rule)the TransformationDomains which provide the types of the values whichthis Relation specifies the relationship between. Relations are constrained toowning only RelationDomains via this association.

• when: Pattern [0..1] {composes}

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

54

A set of Predicates that together form the guard to the relation• where: Pattern [0..1] {composes}

A set of Predicates that together constrain the variables bound by the whenclause and all the patterns of the RelationDomains. This is a postconditionwhich will hold after the relation, or must hold after any black-box oroperational mapping invocation.

9.12.5.2RelationDomainA RelationDomains is a variable of a MOF type which belongs to a particular candidatemodel. It may be checked or enforced or both (see its parent type Domain). Associatedwith it is a DomainPattern, which is an arbitrarily complex literal expression andassociated variables which match any structure which can be navigated to from the typeof the RelationDomain.

SuperTypes• Domain

Associations• RootVariable: VariableDeclaration [1]

the VariableDeclaration of the owning Relation to be used as the root for theevaluation of the templateExpression of this RelationDomain'sDomainPattern (via its pattern property).

• pattern: DomainPattern [1] {composes}the DomainPattern of this RelationDomain against which all instances of itstype in its typed model which meet the guard condition will be matched.

9.12.5.3DomainPatternA DomainPattern is subtype of Pattern which can specify an arbitrarily complextemplate literal expression starting from its owning RelationDomain's rootTypevariable's type. Its templateExpression may give an object or collection expressionwhich matches against the properties and links of the domain's root type, and introducesvariables which may bind to any type in the structure.

SuperTypes• Pattern

Associations• templateExpression: TemplateExp [0..1] {composes}

the specification of the literal template pattern to be matched. The templateexpression must conform to the type of the root variable of the owningDomain.

• relationDomain: RelationDomain [1]the owning RelationDomain.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

55

9.12.6 KeyQVT extends EMOF to specify keys for classes. A Key defines a set of properties of aclass that uniquely identify an instance of the class in a model extent. A class may havemultiple keys (as in relational databases). Please refer to section 9.6 for a detaileddescription of the role played by keys in the enforcement semantics of relations.

SuperTypes• Element

Associations• identifies: Class [1]

class that is identified by the key.• part: Property [1..*]

properties of the class that make up the key.

9.13 STANDARD LIBRARY

9.14 CONCRETE SYNTAX

This section provides both the textual and graphical concrete syntaxes for the RelationsLanguage.

9.14.1 Relations Textual Syntax Grammar<topLevel> ::= ('import' <filename> ';' )* <transformation>*<filename> ::= <identifier><transformation> ::= 'transformation' <identifier> '('

<modelDecl> (; <modelDecl>)* ')' ['extends' <identifier> (',' <identifier>)* ]'{'

<keyDecl>* ( <relation> | <query> )* '}'<modelDecl> ::= <modelId> ':' <metaModelId> (, <metaModelId>)* <modelId> ::= <identifier><metaModelId> ::= <identifier><keyDecl> ::= 'key' <classId> '{' <propertyId> (, <propertyId>)* '}' ';'<classId> ::= <identifier><propertyId> ::= <identifier><relation> ::= ['top'] 'relation' <identifier> ['overrides' <identifier>]

'{'<varDeclaration>*

(<domain> | <primitiveTypeDomain>)+ <when>? <where>?

'}' <varDeclaration> ::= <identifier> (, <identifier>)* ':' <typeCS> ';' <domain> ::= [<checkEnforceQualifier>]

'domain' <modelId> [ <identifier> ] ':' <typeCS> '{' <propertyTemplate>* '}' [ '{' <oclExpressionCS> '}' ]

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

56

['implementedby' <OperationCallExpCS>] ';'

<primitiveTypeDomain> ::= 'primitive' 'domain' <identifier> ':' <typeCS> ';'

<checkEnforceQualifier> ::= 'checkonly' | 'enforce' <when> ::= 'when' '{' <oclExpressionCS> '}'<where> ::= 'where' '{' <oclExpressionCS> '}'<query> ::= 'query' <pathNameCS> '(' [<paramDeclaration> (','

<paramDeclaration>)*] ')' ':' [<paramDeclaration> (',' <paramDeclaration>)*]

( ';' | '{' <oclExpressionCS> '}' )

9.14.2 Expressions syntax (extensions to OCL)

<oclExpressionCS> ::= <propertyCallExpCS> | <variableExpCS> | <literalExpCS> | <letExpCS> | <ifExpCS> | <template> | '(' <oclExpressionCS> ')'

| (<oclExpressionCS> ';')*<template> ::= <objectTemplate> | <collectionTemplate>objectTemplate ::= [<identifier>] ':' <typeCS> '{'

<propertyTemplate>* '}' <propertyTemplate> ::= <identifier> '=' <oclExpressionCS><collectionTemplate> ::= <identifier> ':' <collectionTypeIdentifierCS>

'(' <typeCS> ')' '{' <setComprehensionExpression> | <memberSelectionExprCS> | <oclExpressionCSList>

(',' <oclExpressionCSList>)* '}'<setComprehensionExpression> ::= (<identifier> | <objectTemplate>)

'|' <oclExpressionCS> <memberSelectionExprCS> ::= (<identifier> | <objectTemplate> | '_')

'++' (<identifier> | '_')

9.14.3 Graphical Syntax

9.14.3.1Introduction

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

57

Diagrammatic notations have been a key factor in the success of UML, allowing users tospecify abstractions of underlying systems in a natural and intuitive way. Therefore ourproposal contains a diagrammatic syntax to complement the textual syntax of Section9.14.1. There are two ways in which the diagrammatic syntax is used, as a way of: • representing transformations in standard UML class diagrams. • representing transformations, domains and patterns in a new diagram form:transformation diagrams.

The syntax is consistent between its two uses, the first usage representing a subset of thesecond. Here we propose a visual notation to specify transformations. A transformationcan be viewed as a relationship between two or more patterns. Each pattern is acollection of objects, links and values. The structure of a pattern, as specified by objectsand links between them, can be expressed using UML object diagrams. Hence, wepropose to use object diagrams with some extensions to specify patterns within atransformation specification. The notation is introduced through some examplesfollowed by detailed syntax and semantics. 9.14.3.1 specifies a transformation,UML2Rel from UML classes and attributes to relational tables and columns.

9.14.3.1 corresponds to the textual specification given below.

relation UML2Rel {checkonly domain uml1 c:Class {name = n, attribute = a:Attribute{name = an}}checkonly domain r1 t:Table {name = n, column = col:Column{name =an}}}

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

58

c: Class

name = n

a:Attribute

name = an

t: Table

name = n

col : Column

name = an

«domain» «domain»

UML2Rel

uml1 : UMLC C

r1:RDBMS

Figure 12. UML Class to Relational Table Transformation

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

59

The where clause of a relation can be shown using a where box as shown in the9.14.3.1, which extends the above relation to specify that the UML2REL transformationis to be applied on every class within a package.

p:Package

name = n

c:Class

s:Schema

name = n

t:Table

«domain» «domain»

PackageToSchema

uml1 : UMLC C

r1:RDBMS

where

UML2Rel(c,t)

Figure 13. Example showing where clause

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

60

A similar box may be shown for the when clause of a relation. An enforceable domain isshown by replacing the C within the relation symbol by an E. In the above example ifthe RDBMS side is to be made enforceable then it will be as shown in 9.14.3.1.

p:Package

name = n

c:Class

s:Schema

name = n

t:Table

«domain» «domain»

PackageToSchema

uml1 : UMLC E

r1:RDBMS

where

UML2Rel(c,t)

Figure 14. RDBMS domain made enforceable

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

61

Constraints maybe attached to objects or a pattern. This is done as in UML by attachinga note. An example is shown in 9.14.3.1. In the figure one constraint is attached to thecol object and another one to the UML pattern.

c: Class

name = n

a:Attribute

name = an

t: Table

name = n

col : Column

«domain» «domain»

uml1 : UMLC C

r1:RDBMS

name = an

c.kind = 'persistent'

Figure 15. UML2Rel with constraints

In all the examples so far, the patterns comprised individual objects and links betweenthem. The notation also supports specifications involving set of objects. 9.14.3.1 showsan example where Table has a field totcols which is set to the number of attributes in theClass.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

62

UML2Rel

uml1 : UML r1:RDBMS t: Table

totcols =a.size

«domain»

c: Class

a:Attribute

«domain»

C C

Figure 16. Example using set

The notation also includes support for specifying the non-existence of objects andoverriding of relations. 9.14.3.1 specifies a strange transformation from a class with noattributes to a table with totcols = 0. The {not} annotating Attribute indicates that thispattern matches only if there exists no Attribute linked to class c.

UML2Rel

uml1 : UML

C C

r1:RDBMS t: Table

totcols = 0

«domain»

c: Class

{not}:Attribute

«domain»

Figure 17. Example using {not}

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

63

The textual specification corresponding to 9.14.3.1 is as follows.

relation UML2Rel {checkonly domain uml1 c:Class { attribute = Set(Attribute){}}{attribute->size() = 0}checkonly domain r1 t:Table {totcols = 0 }}

9.14.3.2Graphical Notation ElementsThe Table 1 gives a brief description of the various visual notation elements.

Notation Description

A relation between models m1 havingMM1 as meta-model and m2 havingMM2 as meta-model. The label C/Eindicates whether the domain in thatdirection is checkable or enforceable.

o:CAn object template having type C andreferred to by the free variable o.

o:C

a = val

An object template having type C and aconstraint that the property a should takethe value val. val can be an arbitrary oclexpression.

o : C«domain» The domain in a relation.

oset:Coset is an object template that matches aset of objccts of type C

{not}:CA not template that matches only whenthere is no object of type C satisfying theconstraints associated with it.

ocl expr.A constraint that may be attached toeither a domain or an object template.

Figure 18. Table 1 Diagrammatic notations

9.14.3.3Variations in Graphical Notation

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

m1 : MM1C/E C/E

m2:MM2

64

In the above examples the positioning of certain elements in a diagram is only indicativeand tools may choose to position these elements differently. The elements in which toolsmay choose to be different are.

− Name of the relation. The name of the relation may appear anywhere in thedrawing page.

− where and when clause. These may appear as shown or maybe hidden and shownoptionally or shown in a separate frame.

− model and meta-model names. These maybe shown optionally and when shownthey maybe shown anywhere close to the relation symbol in the direction of theappropriate pattern.

check/enforce letter. These need to be shown but may appear anywhere close to therelation symbol and in the appropriate direction

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

65

10 Operational MappingsThe QVTMappingOperations package extends the QVTBase package with additionalconcepts to allow defining transformations which uses a complete imperative approach(operational transformations) or to allow complementing relational transformations withimperative bodies (hybrid style). The overview section provides a summary of thelanguage illustrated by examples like the famous UmlToRdbms transformation. Thenthe semantics and abstract syntax section provides a formal description of themetamodel. Then the extensions to the standard QVT library are presented. Finally, theconcrete syntax is defined formally using EBNF as well as the correspondence with theabstract syntax.

10.1 OVERVIEW

10.1.1 Operational transformationsAn OperationalTransformation is defined as a refinement of a relational transformationon a given direction. It is invokable explicitly using a signature which defines, firstly,the constraints for a model to be a valid participant and, secondly, the role played byeach model in the transformation (input/output/inout classification). AnOperationalTransformation, in turn, defines MappingOperations which are defined asrefinements of Relations for a given direction. In addition it defines a main operationwhich provides an entry point for the execution of the transformation. Invoking anoperational transformation implies executing first its entry operation.

OperationalTransformations can be declared as black-boxes, meaning by that that onlythe signature is provided. Within a QVT definition, this is typically used to invoke anexternal transformation implemented using any existing language. It could also be usedto invoke transformations defined with QVT but whose definition is not available forcommercial reasons. Similarily, mapping operations and helper query operations can bedefined as black-boxes, allowing thus using external mechanisms to implement complexcomputations – such as a transformation that would require lex/yacc analysis.

The example below, illustrates the definition of an operational transformation, with itssignature. This is the well-known Uml2Rdbms example.

transformation Uml2Rdbms(in uml:UML,out rdbms:RDBMS);main() { uml.objectsOfType(Package)->map packageToSchema();}

This declaration defines a unidirectional transformation that will produce a RDBMSmodel from a UML model. The main operation executes the transformation in one pass,invoking the 'packageToSchema' mapping operation on each package of the sourcemodel. We should note that, to initiate a transformation, the approach taken in

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

66

operational transformations in different from what happens in relationaltransformations since, in the latter case, the initialization strategy is not explicit anddepends on pattern matching against the top relations.

In the signature of the transformation, uml is a ModelParameter and UML is aModelType. A ModelType allows defining in a flexible way the conditions under whicha participant model is an acceptable parameter when invoking the transformation as awhole. A ModelType refers to a metamodel definition (a list of MOF packages) andindicates the compliance kind that is required (strict or effective).

modeltype UML uses SimpleUml;modeltype RDBMS "strict" uses SimpleRdbms("http://omg.qvt-examples.SimpleRdbms");

The two declarations above provide complementary information on the model types.These two lines are not manadatory. If not provided the modeltype refers implicitly to aMOF package having the same name than the model type with the default effectivecompliance kind. According to the two declarations above, a "RDBMS" participantmodel should only contain instances of the SimpleRdbms package, in constrast with a"UML" participant model which could actually be an instance of any metamodel, aslong as the metaclasses involved in the transformation at least contains the structuredefined by the SimpleUml Package (called the "effective metamodel"). Using the URIsproperty, the transformation writer indicates what actual metamodels or metamodelprofiles have been used as a reference to write the specification. However, when thecompliance kind is effective the uri indication does not prevent using other metamodels.

To each model parameter – uml and rdbms in our example – corresponds a MOF extent– called the model extent. Model parameters are globally accessible within thetransformation definition – represented by a file in the textual syntax. It is possible toinspect its contents during the transformation – using the objects(), objectsOfType() androotobjects() predefined functions. The list of objects in the extent may evolve due toobject creations and de-referencing of objects.

10.1.2 Query LibrariesA library contains definitions that can be used by transformations. Typically theycontain query operations, constructors or class definitions possibly used as intermediatedata (see the "helpers and intermediate data sub-section"). A query library may defineoperations in the context of a model type – for instance to "extending" the UMLmetamodel with a list of additional helper operations. To that end a library declares asignature with an ordered list of model types – possibly empty when the definitionsconcern pre-defined types.

library MyUmlFacilities(UML);

This library can be imported in transformations dealing with the UML metamodel (Seethe import facilities in the "reuse facilities" subsection).

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

67

10.1.3 Mapping operations as refinements of relationsA mapping operation is syntactically described by a signature, a guard (a when clause), amapping body and a postcondition (a where clause). Conceptually, a mapping operationrefines a relation which is the owner of the when and where clauses. In addition, therelation imposes constraints on the signature of the operation, which should beconsistent with the relation domain types.

mapping Package::packageToSchema() : Schema when { self.name.startingWith() <> "_"}{ name := self.name; table := self.ownedElement->map class2table();}

In the example above, a relation 'PackageToSchema' (first letter upperized) is implicitlydefined by the mapping operation. The mapping body is made of an object expression(ObjectExp metaclass) that contains two assignment expressions. This mapping invokesexplicitly the class2table mapping operation to produce tables from the owned classesof the uml model. In this example, it is not necessary to select the owned elements thathave 'Class' kind before invoking Class::class2table, because the body is only executedfor the source elements that satisfy the type constraint and the when clause. Thecombination of the type constraint with the 'when' clause is named the guard of themapping operation. If a guard fails the mapping invocation return the null value. In theexample above, producing null values does not affect the left-hand side of theassignment of the 'table' property. An assignment of a multivalued property always skipsnull values and duplicates. This default behaviour associated with assignments(AssignExp metaclass) simplifies the written of transformations.A variant for calling a mapping operations is to use the strict call semantics, notatedxmap instead of map. In this case the guard is treated as a pre-condition: if not satisfiedthe mapping call produces an exception instead of returning null.

As we stated before, a mapping operation is always a refinement of a relation, even ifthe concrete syntax does not shows this explicitly. For instance, the previous'packageToSchema' mapping operation, refines the following relation:

relation PackageToSchema { checkonly domain:uml (self:Package)[] enforce domain:rdbms (result:Schema)[] when { self.name.startingWith() <> "_" }}

In operational transformations, the type of the parameters of the mapping operationcorresponds with the type of the template object defining a domain, which in this case isrestricted to only express the type of the object. The when clause that is written for themapping operation represents the when clause of the implicit relation.

In operational transformations, relations are restricted in the sence that no real patternmatching is available (domains indicate only a type constraint). However, it is possibleto define "hybrid" relational transformations that allow mixing relations and mappings

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

68

with no restrictions on pattern matching facility. In the context of these hybridspecifications, the concrete notation of a mapping indicates explicitly the realizedrelation. Also, in this context, the when and where clauses are not repeated in themapping definition.

mapping Package::packageToSchema() : Schema refines PackageToSchema { name := self.name;}

10.1.4 Structure of the body of a mappingA mapping may have three different sections: an initialisation section, a populationsection and a termination section. None of three sections is mandatory. Also a mappingmay declare a guard (when clause) to restrict the applicability of the rule and a post-condition (where clause).The general notation, when there is no shorthand applying, is:

mapping dirkind0 X::mymapping (dirkind1 p1:P1, dirkind2 p2:P2) :r1:R1, r2:R2 when { … } where { … }{ init { … } population { … } end { … }}

Where dirkind refers to in/inout/out direction kinds.

10.1.5 Supporting object orientation and class extension

A mapping operation is owned by the operational transformation, which is a kind ofClass. A mapping operation has a signature indicating the elements involved in themapping, their type and the direction kind (in/inout/out). The type can be of an arbitrarytype – like object instances or datavalues – but excludes model types – which are onlyvalid in the transformation signature. In addition to this a mapping operation maydeclare a context parameter named self, which is typed by a class. A mapping operationthat has a context parameter behaves exactly as if the operation was owned by thecontext class. This mechanism also applies to helper operations – exactly as theadditional operations that OCL uses to factorize constraint definitions. A mapping maydeclare more than one result parameter (direction kind out) and may, also, declare noresult at all. In the former case a tuple with the returned values in returned. In the lattercase null is returned. It is possible for an object passed as an in parameter or as an inoutparameter to be returned. For this the result parameter simply needs to be assigned withthe value of the in or inout parameter (this may be done within the initialization or thetermination section of the mapping body). The example below illustrates various possible kinds of declarations:

mapping foo(in a:A, inout b:B) : c:C;mapping X::bar() : Z;

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

69

mapping inout Y::bar() : Z,W;

In the first declaration, foo is a mapping with no contextual parameter, while X::bar andY::bar are two distinct mappings that behave as extensions to the X and Y metaclassesrespectively. According to this declaration, the Y::bar mapping performs an in-placetransformation for the Y element and produces two output results, a Z and a Winstance.. The bar mapping can be called in the context of an X object (an X instance is passed asthe source argument) or alternatively be called as an ordinary operation that is owned bythe transformation class. In the latter case package and class prefixing may be need todisambiguate references to mapping operations.

var x:X := …;var z:Z := x.map bar(); // equivalent to var z:Z := map X::bar(x);

A mapping operation that do not have a contextual parameter – such as the foo mapping– is invoked without any package prefix, unless it is an operation declared by atransformation that is being imported using access semantics, in which case the name ofthe imported transformation should prefix the mapping reference.

map foo(a,b) map MyAccessedTransformation::foo(a,b)

In terms of execution, all the parameters of a mapping – in the general sense, includingthe contextual parameter and the declared out results – are passed as an ordered tuple ofvalues that is used to build the internal trace. Objects and collections are mutableelements, whereas primitive types such as strings and integers are non mutable – theirvalue is copied when passed as actual parameters. Mutable objects are passed byreference, however it is not legal to change an object parameter with direction kindequal to in. Parameters with out direction kind are parameters that are initially passed inthe tuple of arguments as null values. The execution of a mapping operation typicallyreplaces the null value associated with the out parameter by a non null value, possiblyafter creating an object or after retriving an existing one.

10.1.6 Object creation and object population

The following mapping operation 'class2Table' specifies the mapping from a UML classto a RDBMS Table in the very simplistic case where there is a unique column for eachUML attribute – which implies that the attributes only have primitive types.

mapping Class::class2table() : t:Table when {self.isPersistent(); } { name := 't_' + self.name; column := self.attribute->object(a) Column{name=a.name;type=getSqlType(a.type);});

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

70

key := object Key {name := 'k_'+ self.name; column := t.column[kind='primary'];};}

In the example above, the object expression construct (ObjectExp metaclass) is used atthree locations. Firstly, there is an implicit ObjectExp that contains the threeassignments in the body and which creates the Table instance. Then the object keywordis explicitly used iteratively to create the Columns and to create the Key instances. Notethat in this example, the notation 'list->object(i) MyClass{ … }' is a shorthand for 'list->forEach(i) object MyClass { … }'.

An ObjectExp always refers to a Class type and, in addition, optionally refers to ainstance variable. The semantics of an object expression that refers to a variable (as in'object x:X { … }') is to provoke the instantiation of the X class only if the value of x isnull. If the object expression is provided without any variable reference, theinstanciation always occurs. With or without instanciation, the next step is to execute insequenced the expressions within the body of the ObjectExp. This expressions aretypically assignments. However there is no restriction on the kind of computations thatcan be done – for instance one may call the assert or debug operations to collect loginformation, or one may make inner calls to the object construct to create other objects.

The transformation writer may decide to treat the three kinds of output symmetrically,by changing the mapping declaration as follows:

mapping Class::class2table() : t:Table, k:Key, cols:Sequence(Column) when {self.isPersistent() } { population { cols := self.attribute->object(a) Column{name:=a.name;type:=getSqlType(a.type);}; object t:{ -- the type Table is not repeated here since itcan be derived name := 't_' + self.name; column := cols; key := object k:{ name := 'k_'+ self.name; column := cols[kind='primary'];} }; k:= t.key; }}

According to this declaration, the mapping will return a tuple with three items instead ofreturning a unique Table element. In addition to this, the trace created buy the executionof this mappig will "remember" the three results – and not only the table as in theoriginal declaration. If the transformer writer wants the mapping operation to return onlya Table instance but in the same time wants the key and columns be included in thetrace of this mapping invocation, then he will define the mapping signature as below:

mapping Class::class2table(out k:Key, out cols:Sequence(Column) ) :Table;

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

71

The parameters declared with out direction can be skipped from the mapping callsyntax. This is equivalent to pass null values (casted to an empty list when a collectionis expected).

// out parameters receive null valuesmyTable := myClass.map class2table();

It is also possible to pass variables references for out parameters. The values of thesevariables are changed after the call.

// out parameters receive null valuesvar keyInstance : Key; // keyInstance has null default value;var columnList : Sequence(Column);myTable := myClass.map class2table(keyInstance,columnList); debug("created key: %s" % key.repr()); -- uses the pre-definedformat operator

10.1.7 Inlining of mapping operations

The execution of an inner object expression, as the creation of the Key instance in:mapping Class::class2table() : t:Table when {self.isPersistent()} { name := 't_' + self.name; column := self.attribute->object(a) Column(name=a.name;type=getSqlType(a.type);)); key := object Key {name := 'k_'+ self.name; column := t.column[kind='primary'];};}

behaves almost as if it was a call to an "inlined" mapping. For example, it would bepossible to write the example differently, with two additional mappings responsible forcreating the columns and the keys.

mapping Class::class2table() : t:Table when {self.isPersistent()}{ name := 't_' + self.name; column := self.attribute->map attr2Column()); key := self.map class2key(t.column);}

where the two invoked mappings are defined by,

mapping Attribute::attr2Column() : Column { name:=self.name;type:=getSqlType(self.type);}mapping Class::class2Key(in cols:Sequence(Column)) : Key { name := 'k_'+ self.name; column := cols[kind='primary'];}

The advantage of inlining the mapping is that the specifications appears to be muchmore concise. In the other hand, splitting of mappings may favour reusability.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

72

10.1.8 Using constructor operationsThere is yet another way to express the creation of Columns by using a constructoroperation. A constructor is a facility defined to instanciate a metaclass of a metamodelthat can potentially be reused by any transformation that aims to create instances of themetaclass. Constructors are typically packaged in libraries that transformations canimport. However they can also be defined internally to a transformation.

The constructors:

constructor Column::Column (n:String,t: String) { name:=n;type:=t; }constructor Key::Key(n:String,primarycols:Sequence(Column)){name:=n;column:=primarycols;}

play the same role than the attr2Column and class2key mappings. However, these twoconstructors can be more easily be reused in other transformations that create RDBMSobjects since they do not depend on any UML source object.

The notation to invoke constructors uses the construct keyword:column := self.attribute->construct(a) Column(a.name,getSqlType(a.type)));key := construct Key('k_'+self.name,t.column[kind='primary']);

All the previous examples show that there are many ways to structure a transformationdefinition. One may prefer to define various small mapping rules or may prefer defininglarge but minimal number of rules. Depending on reusability concerns, one may alsodefine a set of constructors and put them within a library, or may prefer to define astandalone transformation.

10.1.9 Helpers and intermediate dataApart from the mapping operations and constructors, an operational transformation mayuse for its definition:

- Intermediate classes- Intermediate properties- Helper query operations

Below an example of usage of intermediate data and helpers in a re-designedUml2Rdbms transformation that will treat appropriately non primitive attributes:

intermediate class LeafAttribute{name:String;kind:String;attr:Attribute;};intermediate property Class::leafAttributes : Sequence(LeafAttribute);query Class::isPersistent() = self.kind='persistent';query Association::isPersistent() = (self.source.kind='persistent' andself.destination.kind='persistent');

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

73

In the declarations above, the LeafAttribute class is used to store intermediate data usedto flatten non primitive UML attributes. In our re-designed Uml2Rdbms example, acomposite attribute produces as much columns that there are leaf attributes. TheleafAttribute property declared above is an intermediate property, that is, a propertyowned by the transformation class but having a reference to a metaclass (its context). Infact, the property behaves as any other property of the context metaclass, except that itscontent does not survive after the transformation terminates – unless an implementationgenerates persistent trace records for a specific purpose.

The mapping definition below shows the usage of the intermediate property. First thevalue of the property is computed in the initialization section using the attr2LeafAttrsmapping. Then the columns are generated using as source the list of LeafAttributestored in the intermediate property.

mapping Class::class2table() : t:Table when {self.isPersistent() ;} { init { self.leafAttributes := self.attribute->mapattr2LeafAttrs();} name := 't_' + self.name; column := self.leafAttributes->map leafAttr2OrdinaryColumn(); key := object Key {name := 'k_'+ self.name; column := t.column[kind='primary'];};}

In the example above, the isPersistent query is defined in the context of the UML Classmetaclass whereas the query getSqlType – see the previous version of the class2tablemapping definition – has no specific context attached. Both possibilities are available inQVT. Defining non contextual queries make sence when there is no evident parameterto be selected as the context, or when two candidate inputs have a symmetric role in thequery.

Queries may be defined on primitive types – like string or integers. This is mainly usefulto extend the facilities provided by the standard library.

query String::addUnderscores() = "_".concat(self).concat("_");

10.1.10 Updating objects and resolving object referencesSolving a transformation problem using a procedural style often requires organizing thetransformation in various passes and accessing objects that were previously created.Within mapping operations there are a list of specific constructs to allow retrievingobjects already created in order to update them. These constructs are called theresolution operations. These operators use the implicit trace tuples that are associatedwith the establishment of a relation, and consequently the execution of a mappingoperation.In the Uml2Rdbms example, we may for instance need to update the tables created fromclasses and attributes by adding columns derived from UML associations.

mapping Association::asso2table() : Table when {self.isPersistent()}{ -- result is the default name for the output parameter of therule

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

74

init { result := self.destination.resolveone(#Table); } foreignKey := self.map asso2ForeignKey(); column := result.foreignKey.column;}

The resolve construct inspects the trace data to see whether there is a Table instance thathas been created from a association destination class and that satisfies a booleancondition. In our case the condition is to be a kind of "Table" (the notation '#Table' is ashorthand for oclIsKindOf(Table)). The resolveone operation returns the first elementthat satifies the condition. The invresolve performs the reverse treatment, that is, looksfor the objects that were responsible for generating the object passed as the contextargument to the invresolve operator.

An important variant of the resolution operator is the resolveIn construct which filtersaccording to a specific mapping operation. Below there is a simple example illustratingthe usage of of this variant. We have a list of java classes (JClass instances) which havea packageName field indicating the name of the owning Package. The transformationcreates a Java Package (JPackage) for each package name found in the java classes. Inthis example, we should take care not to create two packages having the same name.This is ensured by inspecting the objects created by the rule before entering thepopulation section.

transformation JClass2JPackage(inout javamodel:JAVA);main () { javamodel->objectsOfType(JClass)->jclass2jpackage();}mapping Class::jclass2jpackage() : JPackage () { init { result := resolveIn(jclass2jpackage,true)->select(p|self.package=p.name)->first(); if result then return; } name := self.package;}

In the example above, return is used to avoid executing the population section when thepackage is found.

A final flavour of the resolution operator is the ability to postpone the retrieval ofobjects until the end of the transformation (that is to say, at the end of the execution ofthe entry operation). In certain circuntancies, using deferred resolutions avoid definingvarious passes for a transformation. Below an example where we have potential cyclicreferencing when transforming classes that may refer to each other through theinheritance link.

transformation Uml2Java(in uml:UML,out java:JAVA) main() : JAVA::Interface { uml->objectsOfType(Class)->map transformClass();}mapping UML::transformClass() : JAVA::Interface () { name := "Ifce".concat(self.name); base := self.superClass->late resolve(#JAVA::Interface);}

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

75

In terms of execution, the 'late resolve' expression returns a built-in future value whichsaves the context for a future invocation – here the source argument plus the resolvecondition compiled as a function. The immediate effect of assigning a property with afuture variable – the assignment of the base property in our example above - isequivalent to receive a null value – but with a specific side-effect: the future variable issaved internally with the reference of the property or variable to be assigned. If thefuture variable is accessed before being assigned, then its side-effect is lost – and thefuture value casted as an ordinary null value.

We provide below the solution to the transformation problem that do not uses the lateresolution. This solution uses two passes.

transformation Uml2Java(in uml:UML,out java:JAVA) main() : JAVA::Interface { uml->objectsOfType(Class)->map transformClass(); uml->objectsOfType(Class)->map transformClassInheritance();}mapping UML::transformClass() : JAVA::Interface { name := "Ifce".concat(self.name);}mapping UML::transformClassInheritance() : JAVA:Interface { base := self.superClass->resolveIn(transformClass,#JAVA::Interface);}

10.1.11 Reuse facilities: importing transformations and libraries

Because writting a large and complex transformation is like developing any complexsoftware, reuse facilities and modularity are quite important within QVT. Objectorientation plays a fundamental role. The first mechanism we should mention istransformation extension. An operational transformation – which is a kind of Class -may extend a transformation by defining or overriding helpers and operation mappings,and also by adding additional intermediate data.

transformation Uml2RdbmsWithInheritance(in uml:UML,out rdbms:RDBMS) extends Uml2Rdbms overrides {Class::class2table,Association::Asso2table;}query Class::getBaseClasses() : Set(Class); // new helper to bedefined// redefined class to table transformationmapping Class::class2table() : Table { … }

The semantics of transformation extension is simply based on copy/paste: the effect isthe same as if the definitions of the extended transformation were defined in theextender. Overriding allows inhibiting existing definitions and possibly replacing themby new ones.

The language also allows for a lighweight import: a transformation can access anothertransformation or a query Library. In such a case, the semantics is not the semantics of a

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

76

copy/paste but it is based on referencing. When using the concrete syntax, the name ofthe accessed transformation or library should prefix any definition being accessed.

Import with access semantics is useful to invoke coarse-grained black-boxtransformations. The example below, illustrates its usage. The UmlNormalizetransformation is instantiated and then invoked to achieve some cleaning in the UMLmodel prior to start the effective work creating the RDBMS model. The transformoperation is used to invoke the complete transformation on the instance of thetransformation class.

transformation Uml2Rdbms(in uml:UML,out rdbms:RDBMS):access transformation UmlNormalize(inout UML);access mathlib;main () { if not UmlNormalize(uml).transform() then { uml->objectsOfType(Package)->map package2schema(); mathlib.average(uml); } else raise "UmlModelIllFormed" endif;}

Invoking a transformation returns a transformation class instance – which is the implicitinstance created before executing the entry operation. The failed() operation is used tocheck whether the transformation raised an error. Other operations related to thetransformation class are defined in the standard library. Note that the currenttransformation instance can be explicitly accessed using the this variable.

10.1.12 Dynamic definition and invocation of transformationsWhen dealing with a complex MDA process, it may be useful to be able to definetransformations that use transformations definitions computed automatically. It isindeed possible for a transformation definition to be the output of a transformationdefinition – since a QVT model can be represented as a model. The language provides apre-defined 'asTransformation' operation that allows to cast a transformation definition(a model typed through a ModelType that accepts QVT compliant definitions) as aninstance of the corresponding transformation class. The implementation of this'asTransformation' operation typically requires "compiling" the transformationdefinition on the fly.

The example below illustrates a possible usage of this facility. This Pim2Psmtransformation transforms a PIM model into a PSM model. To this end, the initial PIMmodel is first of all automatically annotated using an ordered set of UML Packages thatdefines the transformation rules to infer the annotations, on the basis of an arbitraryproprietary UML-oriented formalism. Each UML Package defining a transformation istransformed into the corresponding QVT compliant specification. When executed insequence, each resulting QVT transformation definition adds its own set of annotationsto the PIM model. At the end, the annotated PIM is converted into a PSM model usingthe AnnotatedPim2Psm transformation.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

77

transformation PimToPsm(inout pim:PIM, in transfSpec:UML, outpsm:PSM);access transformation UmlGraphicToQvt(in uml:UML, out qvt:QVT);access transformation AnnotatedPimToPsm(in pim:PIM, out psm:PSM)main() { transfSpec->objectsOfType(Package)->forEach(umlSpec:UML) { var qvtSpec : QVT; if UmlGraphicToQvt(umlSpec,qvtSpec).transform()<>null then{ debug("Generation of the QVT definition hasfailed",umlSpec);return;}; ; if (var transf := qvtSpec.asTransformation()) then { debug("Instanciation of the QVT definition hasfailed",umlSpec);return;} if transf.transform(pimModel,psmModel) { debug("failed transformation for packagespec:",umlSpec); return;} }}

10.1.13 Reuse facilities: mapping extension

Apart from the coarse-grained extension mechanism, based on import oftransformations, the language also provide reuse facilities at the level of the mappingoperations. A mapping operation may be declared an inheriting from another specificmapping operation. This is particularily useful when transforming models compliantwith metamodels that expose a lot of class hierarchies. Typycally a mapping dealingwith a sub-class may take benefit of the mappings defined for their superclasses.

mapping Attribute::attr2Column (in prefix:String) : Column { name := prefix+self.name; kind := self.kind; type := if self.attr.type.name='int' then 'NUMBER' else 'VARCHAR'endif;}mapping Attribute::attr2ForeignColumn (in prefix:String) : Column inherits leafAttr2OrdinaryColumn { kind := "foreign";}

The example above illustrates reuse of code when two mappings perform similar actionsto populate the same model element. In terms of execution semantics, inheriting from amapping is equivalent to invoke the inherited rule just before entering the part of therule dealing with the population of the properties. Due to this semantics, the compliancerules between parameters simply obeys to the constraints that exists between the callerand the callee. In particular the context parameter of the inheriting mapping may be asub-class of the context of the inherited mapping operation.

A variant of mapping inheritance is mapping merging. Within a transformation, amapping may declare the mappings that will complement its execution. In terms ofexecution, the ordered list of complementary mappings is executed in sequence after the

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

78

termination section. The ordinary compliance rules between a caller and the callee applyhere constraining the parameters of the complementary mapping to conform to themapping serving as the base for merging.

The example below shows an example of a transformation definition that uses mappingmerging. This style of writing allows defining a modular specification where we almosthave a mapping operation for each rule defined in natural language.

// Rule 1 (in english): A Foo should be transformed as a Atom withthe name upperized// and a Bar lowerizedmapping Foo::foo2atombar (out atom:Atom,out bar:Bar) merges foo2barPersistence, foo2atomFactory{ object atom:{name := "A_"+self.name.upper(); } object bar:{ name := "B-"+self.name.lower();}}// Rule 2: Persistent attributes of Foo are treated as volatile Barpropertiesmapping Foo::foo2barPersistence (in atom:Atom, out bar:Bar) { object bar:{ property := self.attribute->mappersistent2volatile(); }}// Rule 3: An Atom factory should be created for each Atom and havethe name// of the associated Bar.mapping Foo::foo2atomFactory (in atom:Atom, out bar:Bar) { object bar:{ factory := object Factory {name := bar.name}}; }

Note that according to the mapping call semantics, a merged rule is not invoked if theguard is not satisfied.

10.1.14 Disjunction of mapping operationsA mapping operation may be defined as a disjunction of an ordered list of mappings.This means that an invocation of the operation results on the selection of the firstmapping whose guard (type and when clause) succeds. The null value is returned if noguard succeeds.

Below an example:

mapping UML::Feature::convertFeature () : JAVA::Element disjuncts convertAttribute, convertOperation, convertConstructor() {}mapping UML::Attribute::convertAttribute : JAVA::Field { name := self.name;}mapping UML::Operation::convertConstructor : JAVA::Constructor { when {self.name = self.namespace.name;} name := self.name;}mapping UML::Operation::convertOperation : JAVA::Constructor { when {self.name <> self.namespace.name;}

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

79

name := self.name;}

10.1.15 TypedefsThe typedef mechanism allows attaching constraints to existing types. When used in thesignature of a mapping operation the constraints become part of the guard of themapping operation. The condition is expressed within brackets after the type taken asreference.

typedef TopLevelPackage = Package [_parent()=null];typedef AttributeOrOperation = Any [#Attribute or #Operation];typedef Activity = ActionState[stereotypedBy("Activity")];

The type defined by a typedef in considered to be in the scope of the model type of thetype taken as reference. For instance, if Package exists in the context of a UMLmodeltype, the TopLevelPackage is also considered being defined in the context of theUML modeltype.The Any type, used to define the AttributeOrOperation typedef, is a pre-defined type ofthe language representing all possible types. It is useful when a metamodel do not definea common base type for all its types.

A typedef can also be used to simply define an alias to a complex type, as for tupletypes:

typedef PersonInfo = Tuple{name:String,phone:String};

10.1.16 Imperative expressions

The body of helpers and mapping operations typically contains list of expressions thatare executed in sequence. The language provides various enhancements to the originalOCL expressions to allow writing transformations using a procedural style, which takesadvantage of some of the nice features of OCL (functional style, collection operators)but also, if desired, avoids some of its drawbacks (criptic expressions, verbosity andrestricted iterative loop support).

Some of the most relevants enhancements are:

- The ability to define query operations using a list of expressions executed in sequenceand the possibility to exit immediately from the operation using return. A query maydeclare more than a result parameter. It may also have side-effects on the parameters,except for the source context parameter (self).

query Person::isNominated() : Boolean { if self.salary>10000 then {result:=true; return;} if self.degree()>5: then {result:=true; return;} result:=false;}

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

80

query String::splitFilePath() : dirname:String, filename:String;

- The ability to include block expressions within an if expression. The endif keywordcan be omitted if not useful to disambiguate nested if expressions.

if something then { expr1; expr2; expr3; } else expr4;

- The ability to iterate on a condition using a "while" construct. This avoids having tofind complex recursive solutions to problems that can be very easy to solve using asimple conditional iteration.

query Node::getNextRelevantNode() : Node { var curr:Node := self; while (true) { if curr.isFinal() then {result:=null; return;} if curr.isComment() then {curr := curr.next();} else break; } result := curr;}

- Implicit castings, as the ability to pass "strings" when enumeration types are expectedand to pass objects references when Boolean values are expected. The latter isequivalent to test the null value.

if node.getNextRelevantNode() then …

is equivalent to:

if node.getNextRelevantNode()<>null then …

10.1.17 Pre-defined variables: this, self and resultThis represents the transformation instance being defined. It can be used implicitly torefer to the properties of the transformation class or to the operations owned by him.Within a contextual operation (a query helper operation or a mapping operation) selfrepresents the contextual parameter.Within a contextual operation result represents the unique result parameter - if there is aunique declared result - or the tuple containing the list of declared result parameters.

10.1.18 NullThe literal null is a specific literal value that complies to any type. It can be explicitlyreturned by an operation or can be implicitly returned to mean the absence of value.Except when used within the comparison operator or with the isEmpty() and notEmpty()operations, invoking an operation on a null objects returns a null object. The null literalreplaces the OclUndefined literal defined by OCL.

10.2 ABSTRACT SYNTAX AND SEMANTICS

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

81

Transformation(from QVTBase)

EntryOperation

Class(from EMOF)

Property(from EMOF)

LibraryUsagekind : UsageKind

TransformationUsagekind : UsageKind

OperationalTransformationisBlackbox : Boolean

0..1

1

+entry0..1

+entryContext

1

*

*

+intermediateClass*{ordered}

+transfClient*

*

0..1

+intermediateProperty*

+confClient0..1

*

*

+usedLibrary*

+usedBy*

*

*

+usedTransformation*

+usedBy*

{ordered}

{ordered}

{ordered}

Figure 19. Operational Transformations

Class(from EMOF)

Package(from EMOF)

Tag(from EMOF)

LibraryUsagekind : UsageKind

Library

*

0..1

+ownedTag*

+library0..1

*

0..1

*+usedLibrary

0..1

+usingLibrary

Figure 20. Libraries

Library

LibraryUsagekind : UsageKind

1

*

+library1

+usage* UsageKind

extensionaccess

<<enumeration>>

ModelType*

*+binding

*

{ordered}+libUsage *

TransformationUsagekind : UsageKind

*

*

+binding

+transUsage

OperationalTransformation1

*

+transformation

*

*+usage *

1

Element(from EMOF)

Figure 21. Transformation and library usages

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

82

Parameter(from EMOF)

VariableDeclaration(from Expressions)

TypedModel(from QVTBase)

ModelParameterkind : DirectionKind

DirectionKindininoutout

<<enumeration>>

Packageuri : String

OclExpression(from Expressions)

ModelTypecomplianceKind : String

*

0..1

+metamodel*

+modelType0..1

*

0..1

+addi tionalCondi tion*

+condOwner 0..1

Class(from EMOF)

Figure 22. Model types and model parameters

Type(from EMOF)

AnyTypeTypedef1*

+base

1

+typedef

*

OclExpression0..1

0..1

0..1

+condition

+typedef

0..1

Figure 23. Typedefs

OperationCallExp(from Expressions)

OperationalTransformation

TransformationExp

1

*+referredTransformation

1

+transformationExp*

Figure 24. Transformation Instanciation

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

83

TypedModel(from QVTBase)

ModelParameterkind : DirectionKind

Transformation(from QVTBase)* 1

+modelParameter

*

{ordered}

+transformation

1

OperationalTransformationisBlackbox : Boolean

0..1

*

+enforcedDirection0..1

+refinement*

0..1

*

+refined0..1

+refinement*

Figure 25. Links with relational transformations

VariableDeclaration(from Expressions)

RelationDomain(from QVTRelation)

MappingParameterkind : DirectionKind

1

*

+referredDomain1

+refiningParameter*

Parameter(from EMOF)

Operation(from EMOF)

*0..1 +ownedParameter *+operation0..1 {ordered}

VarParameter

Relation(from QVTRelation)

MappingBody

Function(from QVTBase)

EntryOperation

OclExpression(from Expressions)

*

0..1

+body*

+entryOperation0..1

Helper

*

0..1

+body

*

+helper0..1

ObjectExp

Constructor

0..1

0..1

+body0..1

+constructor

0..1

ContextualOperation

0..1

0..1 +context0..1+contextOwner

0..1

*

0..1 +resul t*

+resul tOwner0..1

MappingOperationisBlackbox : Boolean

** +disjunct

*

+disjuncter*

1

*

+refinedRelation1

+refiningOperation*

0..1

1

+body0..1+mappingOperation

1

*

*+merged

*+merging*

**+inherited

*

+inheriting*

0..1*+overrided

0..1+overriding

*

Figure 26. Structure of Mapping operations

Class(from EMOF)

Property(from EMOF)

ContextualProperty

1

*

+context 1

+contextualProperty

*

0..1

*

+overrided0..1

+overriding *

Figure 27. Contextual properties

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

84

CallExp(from Expressions)

OclExpression(from Expressions)

ResolveExpone : Booleaninverse : Booleandeferred : Boolean

0..1

0..1

+condition

0..1

+resolveCondOwner0..1

MappingOperation

ResolveInExp

0..1

*

+inMapping0..1

+resolveExpression*

Figure 28. Resolution expressions

OperationCallExp(from Expressions)

MappingCallExpstrict : Boolean

OclExpression(from Expressions)

MappingSection

*

0..1

+content*

+section 0..1

MappingBody

0..1

0..1

+initSection

0..1

+initOwner

0..1

0..1

0..1

+endSection

0..1

+endOwner

0..1

0..1

0..1

+populationSection

0..1

+populationOwner

0..1

Element(from EMOF)

ConstructorCallExp

Figure 29. Resolve expression, mapping body and mapping invocation

AssignExp

VariableInitExpUnlinkExp

ReturnExp

BreakExp

ContinueExpSwitchExp

AltExp RaiseExp

TryExpCloneExp

OclExpression

BlockExpTupleExp

Figure 30. Simple Side effect expressions

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

85

CallExp(from Expressions)

DoExpCloneExpdeep : Boolean

LoopExp(from Expressions)

OclExpression

WhileExp

1

0..1

+condition1

+whi leExpression0..1

ForEachExpone : Boolean

OclExpression

VariableDeclaration

BlockExp

*

0..1

+body

*

+blockOwner0..1

0..1

0..1

+returnedElement

0..1

+whileExpression0..1

Figure 31. Side effect calls and block expressions

VariableDeclaration

Class

ModelParameter

ObjectExp

1

*

+referredClass1

+objectExpression* 0..1

*

+targetModel0..1

+objectExpression*

0..1

*

+referredObject0..1

+objectExpression*

OclExpression*

0..1*

+body

+objectExpOwner

0..1

OclExpression

Figure 32. Object expressions

SwitchExp

OclExpression

0..1

0..1

+elsePart0..1

+elsePartOwner

0..1

AltExp

*

0..1 +alternativePart

*+altOwner

0..1

1

0..1

+condition 1

+altCondOwner 0..1

1

0..1

+body

1

+altBodyOwner0..1

Figure 33. Assignments and variable initialisation

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

86

VariableInitExpwithResult : Boolean : false

OclExpression

VariableDeclaration

1

0..1 +referredVariable

1+declaration

0..1

0..1

0..1

+initExpression

0..1+initializedElement

0..1

AssignExpisReset : Boolean

OclExpression

*

0..1

+value

*

{ordered}

+valueOwner0..1

1

0..1

+left 1

+leftOwner

0..1

0..1

0..1

+defaultValue0..1

+defaultOwner

0..1

UnlinkExp

1

0..1

+target

1

+tgtUnlink

0..1

1

0..1

+item 1

+itemUnl ink

0..1

Figure 34. Assignments and variable initilisations

RaiseExpTryExp OclExpression10..1

+body

1

+tryBodyOwner

0..1

0..1

0..1 +exceptExpression0..1

0..1

+exceptOwner

Type(from EMOF) 1

*

+exception

1

+raiseExpression*

*

*

+exception

*

+tryExpression*

Figure 35. Exception handling

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

87

OclExpressionTupleExp

1..*0..1

+element

1..*

+tupleExp

0..1

TypeExp Type(from EMOF)

+referringExp

* +referredType

0..10..1

*

PrimitiveLiteralExp(from Expressions)

NullLiteralExp

Figure 36. Tuple, type and null expression facilities

Concepts for operational Transformations

10.2.1 OperationalTransformationAn OperationalTransformation is a specific kind of Transformation. AnOperationalTransformation defines an unidirectional transformation with a signatureindicating the models involved in the transformation (specialization of the TypedModelconcept). Being a subclass of Transformation, an OperationalTransformation is a Class and aPackage. As a Class it can define properties and operations – like helper queries,mapping operations, and constructors. As a Package it can define types and classes.A non blackbox OperationalTransformation has an entry operation named main servingas the entry point for the execution of the transformation. Invoking anOperationalTransformation produces the invocation of the entry operation.An OperationalTransformation may be defined as a refinement of an existing relationaltransformation (Transformation instance). In such case it indicates the direction of therelational transformation being enforced.

Superclasses• Transformation (indirectly a Class and a Package)

Attributes• isBlackbox : Boolean

indicates that the whole Transformation is opaque : no entry operation andno mapping operations are defined. It is typically used to reuse coarse-grained transformations defined or implemented externally.

• isAbstract : Boolean (from Class)indicates that the transformation serves for the definition of othertransformation. No entry transformation should be defined.

• uri : String (from Package)

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

88

indicates an identity for the transformation. This is in particular useful whenused in conjunction with the pre-defined tag 'proxy'.

Associations• enforcedDirection : ModelParameter[0..1]

indicates the enforced direction of the refined relational transformation thatis associated with this operational transformation. This property should beused in conjunction with the 'refined' link.

• entry : EntryOperation [0..1]An operation acting as the entry point for the execution of the operationaltransformation. It is optional since an OperationalTransformation may serveas a base class for another operational transformation.

• intermediateClass : Class [*]the Classes that are defined explicitly by the transformation writer to containstructured intermediate data used for the purpose of the transformation.These intermediate classes are to be distinguished from the trace classes thatare implicitly and automatically derived from the relations. Instances ofintermediate classes do not survive the execution of the transformation,except for ensuring trace persistence.

• intermediateProperty: Property[*]refers to the the properties defined to store the intermediate data used by thetransformation. These properties may be ContextualProperties, that is,properties that are owned by the transformation class but which areconceptually extensions of the metaclasses involved in the transformation.Intermediate properties do not survive the execution of the transformation –except for ensuring trace persistence.

• refined : Transformation [0..1]indicates a relational transformation being refined by this operationaltransformation. A tool should be able to check the consistency of the resultsof the operational transformation against the relational specification.

• usedLibrary : LibraryUsage [0..*] {composes}The list of libraries being used. The semantics of library import depends onthe usage kind (access or extension semantics).

• usedTransformation : OperationalTransformation [0..*] {composes}The list of OperationalTransformations being used. The semantics oftransformation import depends on the usage kind (access or extensionsemantics).

• /modelParameter: TypedModel [*] (from Transformation} {composes}The signature of the OperationalTransformation. The TypedModels shouldbe instances of ModelParameters. A ModelParameter indicates a directionkind (in/out/inout) and are typed by a ModelType (a subclass of Type).Model parameters are globally accessible within the module and can be

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

89

inspected using the predefined operations defined on model types (such asobjects(), objectsOfType() and rootobjects()).

• /nestedPackage : Package [0..1] (from Package)This link can only be used to refer to a Package used to define a ModelType(ModelType::metamodel link). It is useful when the metamodel of a modeltype is defined locally.

• /ownedAttribute : Property [0..*] (from Class) {composes}The properties owned by this transformation class. This includesconfiguration properties (such as a MAX_SIZE definition), literal globaldefinitions (such as a JAVA_INT_TYPE) and intermediate properties.Configuration properties are recognized thanks to the pre-defined "config"tag and theirs values can be "passed" using the pre-defined "configvalue" tag.

• /ownedOperation : Operation [0..*] (from Class) {composes}The operations owned by this transformation class. In essential, this includesin particular query opretations, mapping operations, constructors and theentry operation.

• /ownedTag : Tag [0..*] (from Transformation) {composes}All the tags that are defined within this transformation. For instance, a tagmarking a mapping operation will be owned by the transformation class (themarked element is not the owner of the tag).

• /ownedType : Type [0..*] (from Package) {composes}All the types being defined by this transformation. In particular this includesthe ModelTypes of the transformation, intermediate classes, and anycomposite type used to define the type of a variable or a parameter – forinstance as a 'Set(MyMetaclass)'.

• /rule : Rule [0..*] (from Transformation) {composes}The list of relation definitions that are asoociated with the definition of themapping operation. These relations are "simple" relations in the sense thatthe domains are restricted to only specify the type of the parameters. Thewhen expression of the relation serves for the guard of the mappingoperation. The where expression of the relation plays the role of a post-condition for the mapping operation: if the where expression is not satisfiedthen a tool is expected to report an error.

• /modelType : ModelType [0..*] (derived(derived as: 'self.ownedType.oclIsKindOf(ModelType)' )The list of model types defined for this transformation.

Constraints• All TypedModels of a OperationalTransformation are instances of

ModelParameter.self.typedModel->forAll(oclIsKindOf(ModelParameter))

• The type of a ModelParameter is an instance of ModelType.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

90

self.type.oclIsKindOf(ModelType)

• The refined and enforcedDirection links should be used together (if provided).self.refined<>OclUndefined implies self.enforcedDirection<>OclUndefinedand self.enforcedDirection<>OclUndefined implies self.refined<>OclUndefined

• Class inheritance should not be used for transformation classes.self.tsuperClass->isEmpty()

• A transformation cannot be defined as an ownedType of a package..self.package->isEmpty()

Execution semantics

This specification defines an imperative and one-shot scenario execution semantics forthe OperationalTransformations.

An OperationalTransformation is a class. Invoking the operational transformation firstlyimplies instantiating the class and then initializing the properties representing the modelparameters – so that they become globally accessible. After that, the entry operation isinvoked on the class instance representing the transformation. For each ModelParameterthere is a corresponding implicit MOF extent. The objects of the extents are accessedusing the pre-defined operations defined in the QVT library (such as ObjectsOfType).The entry operation executes in sequence the ordered list of expressions of its body. Inparticular it can invoke helper and mapping operations, but can also invoke otheroperational transformations - possible defined as black-boxes. The direction kindsdeclare the role played by the models in the transformation. It is not legal to definemappings that make changes to a model declared with an in direction kind. An inoutdirection kind is used for in-place transformation, whereas out is used for creating a newmodel. At the end of the execution of the main, the list of deferred assignments are executed insequence (see the execution semantics of deferred assignments in the AssignExpdescription). For the execution semantics of mapping operations, see the correspondingmetaclass description section.

Notation

The notation to define a transformation uses the transformation keyword. This shouldbe the first declaration in the file.

The declaration below defines an operational transformation named Uml2Rdbms with asignature made of two model parameters uml and rdbms typed by the UML andRDBMS model types. It also defines a tag to indicate the transformer writer.

transformation Uml2Rdbms(in uml:UML, out rdbms:RDBMS);tag "author" Uml2Rdbms = "Pepe";

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

91

10.2.2 LibraryA Library is kind of Class and a kind of Package. It is used to represent a group ofoperations – queries or constructors - or type definitions useful for reuse. The QVTstandard library is an example of a Library instance which do not need to be importedexplicitly.

Superclasses• Class, Package

Attributes• uri : String (from Package)

indicates an identity for the Library. This is in particular useful to when usedin conjunction with the pre-defined tag 'proxy' to avoid repeating thecomplete definitions of the library when exchanging a transformationimporting it.

Associations• usedLibrary : LibraryUsage [0..*] {composes}

The list of libraries being used. The semantics of library import depends onthe usage kind (access or extension semantics).

• ownedTag : Tag [0..*] {composes}All the tags that are defined within this Library. For instance, a tag markinga helper operation will be owned by the Library (and not by the markedelement which is not the owner of the tag)..

• /ownedAttribute : Property [0..*] (from Class) {composes}The properties owned by this Library. May include literals or configurationproperties. These have the same semantics as configuration properties andliterals defined for operational transformations.

• /ownedOperation : Operation [0..*] (from Class) {composes}The operations owned by this transformation class. This includes queryopretations and constructors. Mapping operations cannot be defined inLibraries – they should be defined in transformations, possibly abstracttransformations.

• /ownedType : Type [0..*] (from Package) {composes}All the types being defined by this transformation. In particular this includesthe ModelTypes defined for the library – for instance "UML" if the queryoperations apply on UML metaclasses. It also included computed compositetypes such as collection types – like 'Set(MyMetaclass)' - and tuple types.

NotationThe notation to define a library uses the library keyword. This should be the firstdeclaration in the file.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

92

The declaration below defines a library named UmlUtilities with a signature made of amodel type named UML1_4.

library UmlUtilities(UML1_4);

10.2.3 LibraryUsageRepresents the usage of a library through one of these two import semantic. Withextension semantics, importing the library is identical to defining the importedoperations of the imported library in the importing library. This is in particular true forcontextual operations which have an effect on the list of symbols that are accessible to aclass instance. With access semantics, the definitions of the imported library are notincluded in the name space of the importing library. Contextual operations of theimported library cannot be invoked as operations of the referred context class. They canonly be invoked as operations of the owning library.

Superclasses• Element

Attributes• kind: UsageKind

The semantics of the import. Possible values are access and extension.Associations

• binding: ModelType [0..*]The model types being "passed" to the imported library. The binding is doneaccording to the ordering of the original list of model types declared by theimported module. Note that model types are contained using the ownedTypelink.

NotationThe notation for a library usage depends on who is the importer. If the importer is atransformation, a declaration with the import keyword or with the access keyword isneeded, depending on the usage kind (extension or access). If the importer is a librarythe extends keyword complements the library declaration for extension. Otherwise, anindependent import library declaration is needed.The import declaration below indicates the usage of a library using extend semanticswhile the second declares the usage using access semantics. Bindings are inferred by theorder of the model types.

transformation Uml2Rdbms(in uml:UML, out rdbms:RDBMS);import library UMLUtilities(UML);access library MathLibrary;

The declaration below indicates that a library extends another library.library UMLUtilities(UML) extends BasicUMLUtilities(UML);

10.2.4 TransformationUsageRepresents the usage of a transformation through one of these two import semantic.With extension semantics, importing the transformation is identical to defining theimported operations of the imported transformation in the importing transformation.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

93

This is in particular true for contextual operations which have an effect on the list ofsymbols that are accessible to a class instance. With access semantics, the definitions ofthe imported transformation are not included in the name space of the importingtransformation. Contextual operations of the imported transformation cannot be invokedas operations of the referred context class. They can only be invoked as operations ofthe owning transformation.

Superclasses• Element

Attributes• kind: UsageKind

The semantics of the import. Possible values are access and extension.Associations

• binding: ModelType [0..*] {ordered}The model types being "passed" to the imported library. The binding is doneaccording to the ordering of the original list of model types declared by theimported module. Note that model types are contained using the ownedTypelink.

Notation

The notation for a usage of a transformation depends on the import semantics used. Foran extension, the extends declarations complements the signature of the transformation.Othewise, a separated access declaration is needed. The complete signature of thetransformation may be reminded, however this is not mandatory.In the example below, the first declaration below declares that the Uml2Rdbms uses theBasicUml2Rdbms transformation with extend semantics while the second declares theusage of UmlCleaning using access semantics. Bindings are inferred by the order of themodel types.

transformation Uml2Rdbms(in uml:UML, out rdbms:RDBMS) extends BasicUml2Rdbms(in UML, out RDBMS);access transformation UmlCleaning(inout UML);

10.2.5 ModelParameterA Parameter representing a model participating in the transformation. TheModelParameters contains an indication stating what will be the role of thetransformation on a model (in, inout or out direction kinds). The ordered set ofModelParameters forms the signature of the OperationalTransformation. AModelParameter specializes the QVTBase::TypedModel metaclass. The type of aModelParameter is a ModelType. Model parameters are globally accessible within themodule defining the transformation. Pre-defined operations defined on model types canbe used to inspect at any time during the transformation the objects that are part of themodel. More precisely there is a MOF extent corresponding to each model parameter.Any object creation occurs in an extent associated with a model parameter.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

94

Superclasses• TypedModel• Parameter• VariableDeclaration

Attributes• kind: DirectionKind

indicates the role played by the transformation on the model. Possible valuesare in (changes forbidden), inout (model updated) and out (model beingcreated).

Constraints• The type of a ModelParameter is an instance of ModelType.

self.type.oclIsKindOf(ModelType)

• The type of the ModelParameter should be consistent with the declared usedpackages

NotationModel parameters are notated as simple parameters within the signature of atransformation. If the direction kind is not provided, the in value is assumed.

10.2.6 ModelTypeA ModelType is a Type defined locally by the transformation to represent constraintsthat a model has to satisfy in order to be a valid participant of a transformation. To thatend, a ModelType refers to a "metamodel" (made of one or more MOF Packages) whichdefine at least the set of classes and property elements that are expected by thetransformation. A model type is defined as a subclass of Class so that it is possible todefine operations and properties on it. In order to restrict more the set of valid participant models, a ModelType may –optionally - specify a list of extra conditions that models need to hold. Example: a UML1.4 model which does not define use cases may be fully compliant with all the UML 1.4well formedness rules and still not be a valid input for a transformation that expectsUML models with use cases.A ModelType gives a type to the ModelParameters. The pre-defined QVT librarydefines a set of inspection operations – such as the objects() and objectsOfType()operations - to access the objects of the model extent (the MOF extent that is implicitlyassociated to each model parameter).

Superclasses• Type

Attributes• complianceKind: String

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

95

indicates the kind of required compliance. Predefined values are "effective"and "strict". The default value is "effective". Other values could be definedbut their semantics is outside the scope of this specification.

Associations• metamodel: Package [1..*]

the Packages defining the structural constraints for a model parameter tocomply to its ModelType. The Package::uri informs the user on the "actual"metamodel that has been taken as reference – in the case the referredmetamodel is an effective metamodel..

• extraCondition: OclExpression [1..*]extra conditions restricting the set of valid participant models for this modeltype.

Semantics of model compliance When an operational transformation in invoked, the model parameters passed asarguments should comply with the model types of the parameters of the invokedtransformation. The meaning of compliance of models to models types is defined below:When the compliance kind is "strict", the objects of the model extent should necessarilybe instances of the metaclasses of the referred MOF packages. If the referred metamodeldefines well-formedness constraints these should also be satisfied.When the compliance kind is "effective", any instance in the model extent that has atype that is referred in the model type metamodel need at least to contain the propertiesdefined in the effective metamodel metaclass and have compatible types. The bindingbetween the types in the effective metamodel and the actual types in the model extent isbased on name comparison, except for specific renamings expressed using the alias pre-defined tag – see the QVT standard library.In both cases (strict or effective), model compliance implies additionally to comply withthe extra constraints of the model type.

Effective compliance allows defining flexible transformations that "work" for similarmetamodels. For instance, if a transformation is defined for UML 1.4 but uses no UML1.4 specificities, we can manage so that it also works with UML 1.3 models.Note: We define here only the meaning of a model being compliant with a ModelType.Comparisons and classifications between model types are possible but are considered tobe out of scope of this specification.

NotationA model type is firstly referred by name in the signature of the defined transformation orlibrary. It may also appear in import declarations (access or extends). After that it ispossible to provide more information on the modeltype by adding modeltypedeclarations. The general form is:

modeltype name "compliancekind" uses packageref("uri") where {…};

The extra conditions may use the self variable which is implicitly defined in the whereblock and refers conceptually to an instance of the model type (a model). The

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

96

declaration below declares that a model type uses for its definition an existing Packagenamed SimpleUml by providing its URI. The second declaration only gives an URI andindicates a strict compliance kind.

transformation Uml2Rdbms(in uml:UML, out rdbms:RDBMS);modeltype UML uses SimpleUml("http://omg.qv-samples.SimpleUml);modeltype RDBMS "strict" uses "http://omg.qv-samples.SimpleRdbms";

10.2.7 DirectionKindA DirectionKind is an enumeratation type that gives the possible values of directionkinds for ModelParameters and MappingParameters. Possible values are in, inout andout.

10.2.8 TransformationExpA TransformationExp is a special kind of OperationCallExp. The effect of thisexpression is the creation of an instance of a transformation class. This expression isneeded when a transformation needs explicitly to invoke another transformation. Toinvoke a transformation, first the transformation is instanciated (TransformationExp)and then it is invoked using the transform pre-defined operation call. Invoking thetransform operation implies the invocation of the entry operation.

ModelParameters are passed as the arguments of the OperationCallExp. The values forany unassigned configuration properties can be provided using the configvalue tag (seethe pre-defined tags in the standard library) or directly by assigning the configurationproperties of the transformation instance.

A TransformationExp can only be used within an entry operation.

Superclasses• OperationCallExp

Associations• referredTransformation [1] : OperationalTransformation

The transformation being invoked. Note that the referred transformation maybe provided as a simple proxy definition, containing only the uri propertyfilled and the signature of the operational transformation.

Constraints• A transformation instanciation expression can only be invoked within an entry

operation.self.lookOperationContainer().oclIsKindOf(EntryOperation)

• The instanciated transformation should define an entry operation.self.referredTransformation.entry->notEmpty()

Execution semantics of transformation instanciation and invocation

The execution semantics is as follows.MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

97

i) An OperationalTransformation is instanciated through a TransformationExpconstruct (since it is a kind of Class), the configuration properties are populated, and theModelParameters assigned. In addition model extents for the out parameters are created.ii) The entry operation of the transformation is invoked through a transform call on thetransformation instance. This entry operation does not have parameters but can accessthe model parameters.iii) Variables passed as arguments for the ModelParameters with out direction kind arechanged to receive the model extends created in (i) step.

NotationThe notation to instanciate a transformation uses no keyword but instead uses theoperation call syntax where the called operation is the name of the transformation withthe model parameters passed as arguments. Note that there is no need to instanciateexplicitly the current transformation. Only transformations that are imported with accesssemantics need to be instanciated prior to the invocation. In the example below, the entry operation called main instanciates an accessedUmlCleaning transformation class and then invokes it (transform call).

transformation Uml2Rdbms(in uml:UML, out rdbms:RDBMS);access transformation UmlCleaning(UML);main() { var transf := UmlCleaning(uml); // TransformationExp expression if transf.transform() then …}

Concepts for defining the structure of mapping operations

10.2.9 ContextualOperationA contextual operation is a base class for operations owned by the transformation classthat define a context parameter and zero or more result parameters. The contextparameter - also know as 'self' – refers to a type – for instance a metaclass involved inthe transformation. Conceptually, a contextual operation behaves as an operationextending the referred contextual type, even if it this not contained by him. Thecontextual parameter and the results parameters are part of the signature of theoperation. These parameters are owned directly by the operation instead of beingvariables defined within the body of the operation. The definition of a contextual operation has the effect of inserting a new symbol in thenamespace of the owner (the transformation or the library) and in parallel inserting asymbol in the namespace of the context class. As a consequence, a contextual operationcan be invoked either as a non-contextual operation ('self' is the first argument of thecall expression) or as an operation of the context class ('self'' is the source of the callexpression).

Superclasses• Operation

Associations• context: VarParameter [0..1]

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

98

The context variable representing the object on which the operation isinvoked.

• result: VarParameter [*]The variables containing the values to be returned by this operation.

• overrided: Operation [0..1]An operation of an imported transformation or library that is overridden.

• /ownedParameter: Parameter [*] (from Operation)The other parameters of the operation.

10.2.10 HelperA helper is a ContextualOperation that performs a query on a source object and providesa result. In contrast with QVTBase::Functions, a helper may have side-effects on theother parameters – for instance a list may be passed and changed within the body and itseffect be visible after the operation call termination. However it it illegal to create orupdate object instances within a helper operation – except for pre-defined types likesets, tuples and so on. The body of a helper is an ordered list of expressions that isexecuted is sequence. It may declare various results. In such a case, the operation returnsa tuple containing the values of the result parameters is returned. Rationale: Helpers in operational transformation allows written complex queries in aconfortable way since the user is not restricted to write everything within a uniqueexpression.

Superclasses• ContextualOperation

Associations• body: OclExpression [*]

the body of the operation containing an ordered list of expressions to beexecuted in sequence.

Notation

The notation is the notation for any contextual operation except that the query keywordis used. The body may be introduced using a simple expression (with '=' symbol) or bedefined within braces.The declaration below declares a query to retrieve all derived classes of a UML class.The body is not defined meaning that it is a blackbox implemented elsewhere. Thisquery is defined within a library.

library UmlUtilities(UML);query Class::getAllDerivedClasses() : Set(Class);

10.2.11 EntryOperationMOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

99

The EntryOperation represents the entry point for an operational transformation. Itsbody is a list of expressions executed in sequence. Within a EntryOperation it ispossible to invoke not only mapping operations but also other transformations (seeTransformationCallExp). Invoking a transformation means executing its entryoperation. An OperationalTransformation cannot define more than one entry operation. An entry operation has no parameters but can access any globally accessible property orparameter, such as the ModelParameters. The name of an entry operation is "main".

Superclasses• Operation

Associations• body: OclExpression

the body of the operation containing an ordered list of expressions to beexecuted in sequence.

Notation

The notation uses the main keyword and a body containing the list of expressions.

transformation UmlCleaning(inout uml:UML);main() { uml->objectsOfType(Package)->map cleanPackage();}

10.2.12 MappingOperationA MappingOperation is a specific kind of MOF Operation. As such it is owned by aClass. It may be a blackbox (no body included) or may be provided with an imperativebody definition (see MappingBody). A MappingOperation refines a Relation. From thepoint of view of a relation, the mapping body is treated as any blackbox MOFoperation. The relation defines a kind of contract that the mapping operation needs tofulfil when creating the target elements. The parameters of the mapping operations areconstrained by the type of the relation domains. For a parameter, the correspondingrelation domain is found using the following ordering: first the contextual parameter,then the owned parameters and finally the result parameters. The invocation of themapping operation depends on the satisfaction of the when clause of the correspondingrelation.There are three reuse and composition facilities associated to mappings: a mapping mayinherit from another mapping. A mapping operation may also merge other mappingoperations. In addition a mapping operation may be defined as disjunction of othermapping operations. See execution details in the execution semantics sub-section below.

Superclasses• Operation

Attributes• isBlackbox: Boolean

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

100

indicates whether the the body is available. If blackbox is true this meansthat the definition should be provided externally in order to thetransformation to be executed.

Associations• inherited: MappingOperation [*]

indicates the list of the mappings that are specialized. • merged: MappingOperation [*]

indicates the list of mapping operations that are merged. • disjunct: MappingOperation [*]

indicates the list of potential mapping operations to invoke. • refinedRelation: Relation [1]

the realized relation. The relation defines the guard (when) and thepostcondition for the mapping operation.

• body: MappingBody [0..1]the body of the mapping operation.

Execution semantics

We first define the semantic of the execution of a mapping operation in absence of anyreuse facility (inheritance, merge and disjunction), then we describe the effect of usingthese facilities.

Executing a mapping operation

A mapping operation may declare a contextual parameter. In such a case the mappingbehaves as an operation extending the type of the contextual parameter. Resolving themapping call implies finding the operation to call on the basis of the actual type of thesource ('self'). This follows usual object oriented virtual call semantics. After the call resolution is done, all the parameters of the mapping are passed as a tuple.The parameters includes, in this order: the context parameter – if any - , the "ownedparameters" (from Operation::ownedParameter) and the parameters declared as "result".All out parameters – in particular result parameters – have their value initialized to null.All in or inout non null values – except for the primitive types – string, boolean andnumerical values – are passed by reference. However it is not legal to change the valuewhen an object is declared with in direction kind (a good compiler is expected to emitan error on this). After passing of the parameters, the type compliance of the actual object parameters andthe when clause are checked: if this fails null is returned.If the guard succeeds, then the relation trace is checked to know whether the relationalready holds. If, this is the case the output parameters (out direction kind) are populatedusing the corresponding trace tuple of the relation and the value associated to the resultparameters is returned. Otherwise the body of the operation is executed according to theexecution semantic of mapping bodies (see MappingBody).

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

101

The execution semantics of the mapping body is as follows:i) The initialization section is entered and the expressions of the initialisation section areexecuted in sequence. In the initialisation section typically we find variable assignments,mapping or query invocations or explicit assignments of the output parameters.ii) At the end of the initialization section, an implicit "instanciation section" is enteredwhich provokes the instanciation of all the out parameters which still have a null value.By doing so, the corresponding relation trace tuple is populated. From that point therelation is considered to be "hold" and the trace data becomes available.iii) The population section is entered and each expression is executed in sequence. Apopulation section typically contains a list of ObjectExps which corresponds with theout and inout parameters.iv) The termination section is entered provoking the execution in sequence of the list ofexpressions. A termination section typically contains additional computations that needto take place after population of output objects occurs like operation mappinginvocations.

Executing mappings that inherits from other mappingsA mapping that has inherited mappings invokes first its initialisation section - includingthe implicit instanciation section – and only then, invokes the inherited mappings.Invocation of the inherited mappings follows the "standard" invocation semantics,except that the out parameters may now start with a non null value – which would be thecase if the out parameter was changed in the initialisation section of the inheritingmapping. Parameter compliance between the inheriting mapping and the inheritedmapping simply follows the compliance constraints between a caller and a callee.

Executing mappings merging other mappings.The merged mappings are executed at the end of the execution of the merging mapping.The parameters of the merging mapping are passed to the parameters of the mergedmappings, in particular the actual value of the out parameters. Parameter compliancebetween the merging mapping and the merged mappings simply follows the complianceconstraints between a caller and a callee.

Executing mappings defined as disjunction of other mappings.An invocation of a mapping operation defined as a disjunction of other mappingoperation first checks for the first guard mapping in the list that succeeds. Then the bodyof the selected mapping is executed following normal operation mapping executionsemantics. If no guard succeeds then null value is returned. The signature of thedisjuncting mapping need to conform to the signature of the disjuncted mappings –following ordinary constraints between the caller and the callee. In particular the resultof the disjunction needs to be a super type of the result type of the composed mappings.

Notation

A mapping operation signature is notated as any other operation signature except that ituses the mapping keyword, and includes various additional elements. The general formis:

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

102

mapping inout contexttype::mappingname (in p1:P1, inout p2:P2, outp3:P3) : r1:R1, r2:R2 inherits xxx, merges yyy, disjuncts zzz, refines rrrr when {…}where {…}

The contexttype may not appear if the mappings do not declare a contextual parameter.For result parameters the direction kind is necessarily out and don't need to be notated.For the other parameters, including the contextual parameter, the default is in – if notprovided.The declaration below is an example of a mapping operation that defines a contextualparameter (of type Package), a result (of type Schema) a guard. However no body isdefined (it is a blackbox).

mapping Package::packageToSchema() : Schema when { self.name.startingWith() <> "_"};

10.2.13 ConstructorA ContextualOperation used to facilitate the creation of metaclass instances. It can onlybe invoked within mapping operations or within other constructors. In terms ofsemantics, it is equivalent to define a mapping operation with no source context,returning the object constructed using a single ObjectExp expression. The uniquedifference is that the constructor is defined as an extension of the referred contextualmetaclass.

Associations• body: ObjectExp [0..1]

the expression serving to populate the object using the given parameters.

NotationThe notation for declaring constructors is similar to declare any contextual operationexcept that uses the constructor keyword and declares no result. The name of theconstructor is necessarily the name of the context type. Since the body is an ObjectExp,it is notated as any ObjectExp that has has its object keyword skipped (the body containsdirectly the list of expressions of the ObjectExp).The declaration below is an example of a constructor definition for a Column metaclass.

constructor Column::Column (n:String,t: String) { name:=n;type:=t; }

10.2.14 ContextualPropertyA property that is owned by a transformation but is conceptually defined as an extensionof the type referred by the context. This properties are accessed as any other property ofthe referred context tye. This is used to defined intermediate properties as classextensions of a metaclasses involved in a transformation. Superclasses

• PropertyAssociations

• context: Class [1]MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

103

the class being extended with this property.• overrided: Property [1]

the imported property being overrided by this property.NotationThe notation for contextual uses the property keyword, possibly complemented withthe intermediate qualifier. The declaration below is an example of an intermediateproperty that is defined in the context of an existing metaclass.

intermediate property Class::leafAttributes : Sequence(LeafAttribute);

10.2.15 VarParameterA VarParameter is a MOF Parameter that is also a VariableDeclaration. Note: This is useful to reuse the same OCL VariableExp expression to access localvariables and parameters.

Superclasses• VariableDeclaration• Parameter

10.2.16 MappingParameterA MappingParameter is a VarParameter that is annotated with in/inout/out directionkinds indicating constraints on the operation in respect to the actual parameters. AMapping parameter is associated to a relation domain and is constrained by the type ofthe top level template expression of the domain.

Superclasses• VarParameter

Attributes• kind: DirectionKind

The direction indication of the parameter. in value means that the actualparameter is not changed, inout means the actual parameter is updated, outmeans that the actual parameter will receive a new value.

Associations• referredDomain: RelationDomain

The relation domain that corresponds to the parameter.Constraints

• The type of the parameter is the type of the object template expression of thereferred domain.

10.2.17 MappingCallExp

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

104

A MappingCallExp is a special kind of OperationCallExp. It represents the invocationof a MappingOperation but has specific execution semantics. See execution semanticsof in the MappingCallExp metaclass description.

Superclasses• OperationCallExp

Attributes• strict : Boolean

Indicates the effect of calling the operation with actual parameters that donot match the guard (signature + when clause). If strict is false, the defaultbehaviour applies, that is to say, null is returned but no exception isgenerated. If strict is true, an error will be produced. Note that in the lattercase the compiler should be able to report errors when there is a typemismatch with the signature.

Notation A mapping call is notated as any other operation call except that is uses the map orxmap keyword. The latter keyword is used when strict is true. The map and xmapkeywords may be called on a list and have, if needed, the iterator variable inparenthesis.This is in fact a shorthand notation when combined with the ForEachExpexpression.

self.ownedElement->map class2table(); // shorthand of self.ownedElement->forEach(i) i.mapclass2table();self.ownedElement[#Class]->xmap(i) i.class2table();myInstance.map myMapping();

If the mapping call has no contextual parameter, it does not require to be prefixed by thetransformation name, unless it is a mapping defined by an imported and accessedtransformation. Even, if not necessarily notated, a mapping call that do not declares acontextual parameter, is invoked on the current transformation (the implicit thisproperty owned by the transformation and representing the current transformation classinstance). When a mapping declares a context parameter, mapping can be called on thesource object, or alternatively the source object can be passed as the first parameter. Inthe latter case, the name of the context type should prefix the mapping name.

mapping X::bar() : Z;var x:X := …;var z:Z := x.map bar(); // equivalent to var z:Z := map X::bar(x);

10.2.18 ConstructorCallExpA ConstructorCallExp represents the invocation of a Constructor operation.Superclasses

• OperationCallExpNotation

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

105

A constructor call is notated using the construct keyword. The same notationalconventions apply as for calling mapping operations – in particular the shorthand wheninvoked within a ForEachExp expression.

constructor Column::Column (n:String,t: String) { name:=n;type:=t; } // declarationcolumn := self.attribute->construct(a) Column(a.name,getSqlType(a.type))); // call

10.2.19 ResolveExpA ResolveExp is a CallExp expression that inspects trace objects of the transformationin order to retrieve objects created by previous mapping operation invocations.Conceptually, for each mapping invocation, the transformation keeps the information ofwhat objects played the role of out parameters and maintain links with the source object(contextual parameter) that was used in past invocations.The resolve expression filter potential results on the basis of a condition expression andreturns the objects satifying the condition. If the one property is true, only the first isreturned. When the inverse property is true, the resolve expression performs the inverse treatment(looks for source objects that were responsible for "producing" a given output).In ddition the deferred option allows storing the context of the resolution call so that itcan be called at the end of the transformation program and assigned to a property – seesemantics details in AssignExp description. This facility can be used to avoid having touse various explicit passes to solve a transformation problem.

Superclasses• CallExp

Association• one: Boolean

An indication whether the resolve expression should return a unique firstresult or all results.

• inverse: BooleanIf true the resolve expression looks for the source objects responsible for the"creation" of an object instead of looking for the objects "created" by thesource object.

• deferred: BooleanAn indication whether the resolve expression return a future valuecontaining the necessary information to compute the resolution later. Seeexecution semantics.

Execution semantics

The trace information for a mapping operation invocation is created after the executionof the initialisation section (see MappingOperationExp execution semantics). The tracecontains a tuple that stores a reference of the mapping operation (or what is equivalent areference to the corresponding relation) and then the value for each parameter, including

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

106

the context variables and the result variables. It remembers the direction kind of eachparameter as well as the position of the slot referring to the context variable and the slotof the result variables. In this sence the trace for operational transformation extends thestructure of the trace defined for relational transformations.An execution engine then has then sufficient information to be able to keep track of theobjects that were derived from a source object and to reverse the relationship.

Note that this resolve facility makes only a partial usage of all the trace information thatis computed. However this is sufficient in most of the cases.

The semantics of deferred resolutions is explained in the AssignExp metaclass, sincethis is related to the consumption of future values by assignment expressions.

NotationThe notation uses the operation call convention where the called operation is namedresolve, resolveone and invresolve. The condition expression is in parenthesis. WhenisDeferred is true the late keyword is used before the "operation" name. We should notehowever that resolve, resolveone and invresolve are not defined as pre-definedoperations – since they are directly represented by the ResolveExp metaclass. Theresolution operator may be called on a list. This is a shorthand for invoking it in thebody of a ForEachExpr expression.

myresult := mysourceobject.resolveone(#Table); // #Table shorthandfor oclIsKindOf(Table)myprop := mylist->late resolve(#Table); // shorthand for mylist->forEach(i) i.late resolve(#Table)

10.2.20 ResolveInExpA variant of the ResolveExp where the resolution is done only for a given mappingoperation. This expression may be called without any source argument. The effect is tolook for objects independently of the used source.

Superclasses• ResolveExp

Association• inMapping: MappingOperation

The mapping rule that is the target for trace inspection.NotationThe notation uses the operation call syntax where the called operation is namedresolveIn. The same notational conventions as for the ResolveExp applies. The firstparameter is the reference of the rule and the second parameter is the condition toevaluate.

myresult := mysourceobject.resolveIn(myrule,mycondition);

10.2.21 CloneExp

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

107

A CallExp expression which effect is to create a new object from an existing one.Depending on the value of deep booolean property, the copy is superficial (copy onlythe objet excluding its sub-objects) or may copy all sub-objects. A object reference isduplicated in the cloned object provided there are no multiplicity constraints that willmake the model ill-formed.Superclasses

• CallExp

Attribute• deep: Boolean

An indication whether the copy is superficial or complete in respect to thesub-objects that may be contained by the cloned object.

NotationThe notation uses the operation call syntax where the called operation is named clone ordeepclone depending on the value of the deep attribute. The source argument is theobject to be copied.The same usual notational conventions as the forEach shorthandapplies: a clone "operation" can be invoked on a list.

myresult := mysourceobject.clone();resultlist := mylist->clonedeep(); // shorthand of mylist->forEach(i) i.clonedeep();

10.2.22 MappingBodyA mappingBody represents the structure of the imperative body of a mappingoperation implementing a relation. It consists of three non-mandatory sections:initialisation, population and termination sections. See execution semantics in theMappingOperation metaclass description.

Superclasses• Element

Associations• initSection: mappingSection [0..1]

The initial section containing the ordered set of expressions to be executed insequence prior to a possible instanciation of the output parameters.

• populationSection: MappingSection [0..1]The population section containing the expressions used to populate the inoutparameters and out parameters.

• endSection: MappingSection [0..1]The termination section containing other expressions to perform finalcomputations before leaving the mapping oepartions.

NotationThe notation uses firstly braces that comes after the signature of the mapping operation.The contents of the mapping has a general syntax which is:MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

108

mapping mapping_signature // see MappingOperation description{ init { … } // init section population { … } // population section end { … } // end section}

If is in most cases possible to skip the population keyword and directly expands itscontents. In addition, when there is a unique declared result, and when the populationkeyword is omitted, the notation assumes that there is an implicit unique ObjectExp inthe population section used to populate the declared result: the contents of the objectexpressions is directly expanded in the first level of the body.The declaration:

mapping A::AtoB() : B { init { … } myprop1 := … ; // assignments of the implicit object result:B{ … } myprop2 := …;}

is equivalent to:mapping A::AtoB() : B { init { … } population { object result:B { myprop1 := … ; myprop2 := …; }; }}

We should note than this shorthand is very common since most of the rules are simplerules defining a unique result.When the result is not explicitly declared with a name, the result name is assumed. Theleft-hand side of the assignments apply to the result variable. The self variable is usedfor the context parameter.

10.2.23 MappingSectionA MappingSection is an abstraction used to partition the body of a mapping. ASection contains an ordered set of expressions that are executed in sequence.

Superclasses• Element

Associations• content: OclExpression [0..*]

The set of expressions to be executed in sequence.NotationThe keywords init, population and end are used to introduce the three kinds of sectionswhich contains a body delimited with braces. See MappingBody description for usageexamples.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

109

Side-effect extensions

10.2.24 ObjectExpAn ObjectExp is used to populate an existing object or to create and populate a newobject. The object is created only if the referredObject is empty or has a null value. Thebody contains typically property assignments or local variables declarations. However itcan also include arbitrary operation calls such as a call to the assert() or debug() pre-defined operations (see the standard library).

The value returned by this expression is the referredObject.

Superclasses• OclExpression

Associations• referredObject: VariableDeclaration [0..1]

The object to be populated. If not provided or if the value is null the object isinstantiated prior to the execution of the list of expressions in the block.

• referredClass: Type[0..1]Indicates the class of the object to be created or populated.

• targetModel: ModelParameter[0..1]Indicates the model extend where the object should reside in case it isinstanciated. This is optional if the information can be infered from the typeof the object.

NotationThe notation uses the object keyword followed by the referred variable and the referredclass. There are some syntax variants depending on the availability of the referredvariable and the possibility to skip the class reference.

object x:X { … } object Y { … } // No referred variable here.object x: { … } // the type of 'x' is skipped here when alreadyknown

In addition, to this, when the extent location for an object creation cannot be inferredfrom the referred type or referred variable, the object keyword is suffixed with themodel parameter.

Object:UML x:X { … } When the object construct is used within a ForEachExp, there is a shorthand that allowsmaking the notation more compact:

list->object(x) {… } // shorthand for list->forEach(x) object { … }In certain circunstancies, the object keyword can be skipped and its body contentsdirectly expanded in an outer definition. See the notation of MappingBody.

10.2.25 BlockExp

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

110

A BlockExp is an expression defined by an ordered list of expressions. Theseexpressions are executed in sequence. A BlockExp is an abstract class. The valuereturned is the value of the declared returnedElement variable or null if not declared.. The variables of the owning scope of the BlockExp can be used by the expressionswithin the block. The block creates a new scope – local variables to the scope are notaccessible outside.

Superclasses• ExpressionExp

Associations• body: OclExpression [0..*]

The set of expressions to be executed in sequence.• returnedElement : TypedElement [0..1]

The local Variable to hold the value for the result of the expression.

10.2.26 DoExpA DoExp is a block expression used to perform a computation using variousexpressions. It is typically used in conjunction of other constructs such as IfExp andForEachExp.Superclasses

• BlockExpNotationThe notation uses the do keyword with a variable declaration in parenthesis and thebody delimited by braces..

do (x:MyClass) { … } If no returnedElement is declared the parenthesis can be skipped. A do expression isoften used in conjunction with a IfExp or in conjunction with a ForEachExp. In bothcases, the do keyword is skipped.

if something then {…} else {…} // shorthand of 'if something do {…}else {…}'list->forEach(i;res) { … } // shorthand of list->forEach(i) do(res){…}

10.2.27 WhileExpA WhileExp is a block expression that iterates on a list of expressions until acondition becomes false. The returned value is the value of the variable designated bythe returnedElement local variable at the end of the iteration. If no returnedElement isprovided the result is always null.A WhileExp is a kind of BlockExp. A BreakExp within the block provokes thetermination of the block. A ContinueExp provokes the execution of the next iterationwithout executing the remaining instructions in the block.

Superclasses• BlockExp

AssociationsMOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

111

• condition : OclExpression [1]The condition to be evaluated at each iteration (including the first iteration).

NotationThe notation uses the while keyword with a variable declaration and a condition inparenthesis – delimited by a semi-colon - and the body delimited by braces. If noreturned variable is declared, the parenthesis only contains the condition.

while (x:MyClass := self.getFirst(); x<>null) { … } while (not node.isFinal()) { … }

10.2.28 ForEachExpA ForEachExp is a LoopExp that is used to iterate on an expression over a collection.The execution semantics depends on the one attribute. If one is true, the ForEachExpstops the loop as soon as a non null value is found and returns this unique value (andnull otherwise). If one is false, ForEachExp returns in a list all the non null resultsobtained by each iteration.When used in conjunction with a DoExp, the ForEachExp construct behaves as apowerful "imperative" variant of the IterateExp construct. The value returned by eachiteration is freely computed using the "returnedElement" of the DoExp. In addition theBreakExp and ContinueExp expressions are available.

Superclasses• LoopExp

Attribute• one : Boolean

Indicates whether the expression should stop the iteration after a non nullvalue is found.

NotationThe default notation uses the forEach and forEachOne with the iterator variabledeclared in parenthesis and the body expression after the parenthesis. The accessoperator is the arrow '->'. When the body is a property reference or an operationreference, the forEach keyword can be omitted.

list->myproperty // shorthand of list->forEach(i) i.mypropertylist->myfunc() // shorthand of list->forEach(i) i.myfunc()

When forEachOne is used, the shorthand uses the '!->' accessor (a '!' mark before thearrow).

list!->myproperty // shorthand of list!->forEachOne(i)i.myproperty.

This notational shorthands are similar to the collect shorthand in OCL – which is alwaysavailable. When a forEach is used in conjunction with a do block expression, the dokeyword is skipped.

list->forEach (i) { … } // equivalent to list->forEach(i) do { … }

10.2.29 SwitchExpA SwitchExp is an expression that allows expressing alternatives depending onBoolean conditions. Semantically it is equivalent to various nested If expressions.MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

112

However it provides a much more direct and "high-level" representation of multiconditional decisions that are typical to various transformation problems.

Superclasses• OclExpression

Associations• alternativePart : AltExp {ordered} [*]

The alternatives. Each alternative consists of a condition and an expressionto evaluate. The alternatives are evaluated in sequence until one conditionsucceeds.

• elsePart : Expresion [0..1] The expression to evaluate if all the conditions fail.

NotationThe notation uses the switch keyword with the general syntax:

switch { (cond1)? exp1; // alt expression (cond2)? exp2; … else?: expn;}

When used in conjunction with a forEachExp expression, a specific shorthand allowsinvoking the switch on a collection.

list->switch (i) { … } // shorthand for list->forEach(i) switch { …}

10.2.30 AltExpAn AltExp is an expression telling that some expression is to be executed if acondition holds. It returns the executed expression if the condition is satisfied, othewiseit returns null. It is semantically equivalent to an IfExp with a null in the else clause.However, its offers a more direct representation of decisions written within a switchexpression.Superclasses

• OclExpressionAssociations

• condition : OclExpression [1]The condition to evaluate.

• body : OclExpression [1]The expression to evaluate if the condition is satisfied

NotationSee the notation of SwitchExp.

10.2.31 VariableInitExpVariableInitExp represents the declaration and the initialization of a variable.This expression returns the initialization value, unless the property withReturn is set tofalse. In that latter case, the expression returns null.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

113

Note: Variable initialization expressions with results are useful within conditionsexpressions in switch expressions where the value can be reused immediately after thevariable is initialized.

Superclasses• OclExpression

Attributes• withReturn : Boolean

Indicates whether the initialization value is returned by this expression. Iffalse null is returned

Associations• referredVariable : Variable [1]

The variable being declared. The variable is visible within the current scope.It starts to be visible after the declaration occurs. See the execution semanticsection for the definition of scope rules.

NotationThe notation uses the var keyword. The initialiation value is notated using ':=' iswithReturn property is false or uses '=' if withReturn is true. The latest is useful whenused embedded in expressions.

var x:= "abracadabra";if (var x="hello") then …

10.2.32 AssignExpAn AssignExp represents the assignment of a variable or the assignment of aProperty. In this description we refer to "target field" the referred variable or property.If the variable or the property is monovalued, the effect is to reset the target field withthe new value. If it is multivalued, the effect is to reset the field or to append itdepending on the isReset property. If the value filed is made of more than oneexpression, then the assignment is said to be a compound assignment, otherwise it is asimple assignment. An expression in a compound assignment is called a contribution.For a simple assignment, if the right-expression is a collection, assigning the variable orthe property means adding each of the items of the collection (additive semantics). Notethat this is only valid for a multivalued target field. Duplicate elements are removed ifthe target field are Sets – this is the case for property elements. In addition null valuesare automatically skipped.A compound assignment is equivalent to perform as much simple assignments as thereare expressions. Null values are skipped.

An assignment may receive a future variable produced by a ResolveExp expressioninvoked with deferred attribute set to true. The effect is equivalent to receive nullexcept that some side-effect occurs in order to allow re-executing the assignment at theend of the transformation. See semantics details below.An AssignExp returns the assigned value (null if a future value is in right-hand side).

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

114

Superclasses• OclExpression

Attributes• isReset : Boolean

Indicates for a multivalued target that the list is reset before executing theassignment.

Associations

• value : [*] ExpressionThe expression to be evaluated in order to assign the variable or the property.

• left : [1] ExpressionThe left hand side expression of the assignment. Should reference a variableor a property that can be updated.

• defaultValue : Expression [0..1]The expression to compute a value in case the evaluation of the 'value'property returns null.

Constraints

• A deferred assignment is a simple assignmentself.value->size()=1

• Local references cannot be used for the value of the assignment.

Execution semantics of deferred assignments

A deferred assignment is an assignment where the value – necessarily a unique value –is a future value produced by a ResolveExp expression. This assignment is not executedat the time the assignment is reached during the control flow. A null value is returnedinstead. However the execution engine saves the context of the future variable – thesource object when invokinf ResolveExp, the function representing the filteringexpression of the ResolveExp and the property or variable reference to be assigned – sothat the assignment can be performed later - more precisely – at the end of the executionof the entry operation of the transformation. The tuple saving the context of the futurevariable and the assignment is appended to an ordered list which is given to the entryoperation to terminate with the execution of the transformation.

NotationThe notation uses the ':=' symbol if isReset is false and the symbol '::=' otherwise.Composite assignments are introduced by a list of expressions delimited by braces. Thedefault value is introduced using the default keyword.

mysimpleproperty := "hello"; mymultivaluedproperty := object Node {…}; // additive semantics

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

115

mymultivaluedproperty ::= object Node {…}; // the list is reset andre-assignedfeature := { // a composite assignment with two contributions self.attribute; self.operation;}

10.2.33 UnlinkExpAn UnlinkExp represents an explicit removal of a value from a multivalued propertylink.Superclasses

• OclExpressionAssociations

• item : [1] OclExpressionThe object to be removed from the multivalued property.

• target : [1] OclExpressionThe target expression. It should evaluate to a Property.

NotationThe notation uses a call to the unlink "operation" where the source argument is thetarget and the first argument is the item to be removed.

feature.unlink(myattribute);

10.2.34 TryExpA TryExp catches possible exceptions raised by the target expression (the body). Itprovides the list of candidate exceptions and indicates the expression to be executed ifcatching of the exception occurs.

Superclasses• OclExpression

Associations• body : [*] OclExpression

The expression being under the control of exception handling.• exceptExpression : [1] OclExpression

The expression to execute if an exception occurs.• exception : [*] Type

The list of exceptions that can be potentially catched. NotationThe notation uses the try and except keywords.

try { expression1 } except (exception1,exception2) '{expression2};

10.2.35 RaiseExp

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

116

The expression that produces an exception.

Superclasses• OclExpression

Associations• exception: [1] Type

The exception being raised.NotationThe notation uses the raise keyword with the exception name as body. The exceptionscan be provided as simple strings.

myproperty := self.something default raise "ProblemHere";

10.2.36 ReturnExpA ReturnExp is used to exit from a ContextualOperation interrupting the normal controlflow. It is useful to exit from a helper operation after a value is computed or to preventfrom the execution of the population section of a operational mapping.Superclasses

• OclExpression

NotationThe notation uses the return keyword alone.

10.2.37 BreakExpA BreakExp is used to stop prematurely an iteration over a list of expressions. It can beused within the body of a WhileExp or within the body of a ForEachExp.Superclasses

• OclExpressionNotationThe notation uses the break keyword alone.

10.2.38 ContinueExpA ContinueExp is used, within an iteration over a list of expressions, to jump to thenext iteration without executing the remaining expressions of the current iteration.AContinueExp can be used within the body of a WhileExp or within the body of aForEachExp.Superclasses

• OclExpressionNotationThe notation uses the continue keyword alone.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

117

10.2.39 TupleExpA TupleExp creates a Tuple literal using the values and the types of the elements.

Superclasses• OclExpression

Associations• element : OclExpression [1..*]

The list of element to be packed as a tuple.NotationA TupleExp is notated by calling the "operation" named tuple, where the number ofarguments corresponds with the list of expressions to pack.

10.2.40 TypeExpThis expression is used to reference any type in an operation argument.

Superclasses• OclExpression

Associations• referredType : Type [1]

The referenced type.NotationA TypeExp corresponds in the notation to a type reference when used with specificoperations dealing with types like the oclIsKindOf operation..

10.2.41 NullLiteralExpThis literal is used to represent the null value. A null value is compliant with any type.A null value is automatically converted as an empty collection when a collection isexpected. A NullLiteralExp extends the semantics of OclUndefined. A NullLiteralExp replacesOclUndefined in operational transformation definitions.

Superclasses• PrimitiveLiteralExp

NotationA NullLiteralExp is notated using the null keyword.

10.2.42 TypedefThis construct allows to constraints an existing type, called the base type. When used inthe signature of a mapping operation the constraints become part of the guard of themapping operation. A typedef is never instanciated. An object of the base type can bechecked to see whether it complies with the typedef.A specific usage of typedef is to provide aliases to complex types likes tuple types. Insuch a case no condition is defined.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

118

Superclasses• Type

Associations• base : Type [1]

The referenced base type.• condition: OclExpression [1]

The expression defining the condition for a instance to comply with thetypedef.

NotationA Typedef is notated using the typedef keyword with the following syntax:

typedef MyType = MyBaseType [ condition_expression ];The brackets delimiting the condition expression is omitted when the typedef is onlyused to rename an existing type:

typedef MyType = Tuple {x:X; y:Y};

10.2.43 AnyTypeThis pre-defined type is used to represent all types of the language. It is conceptually abase type for all the types. It is useful when a metamodel do not define a base type forthe metaclasses. It can be used in conjunction with a Typedef definition.

NotationAn AnyType is notated using the Any type identifier.

10.3 STANDARD LIBRARY

In this section we describe the additions to the OCL standard library.

10.3.1 Virtual operations for marking

10.3.1.1markedAsObject::markedAs() : Boolean

This function has to be defined for each model type. It is used to checkwhether an object has been marked. For instance, for UML 1.4, thiscorresponds to accessing a IML::TaggedValue, while for a MOF model thiscorresponds to accessing a MOF::Tag.

10.3.1.2markValueObject::markValue() : AnyType

This function id used to return a the value associated with a mark. It is avirtual function, and should be defined specifically for each model type.

10.3.2 stereotypedBy

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

119

Object::stereotypedBy(String) : BooleanThis function id used to check whether an instance is "stereotyped". Thedefintion depends on the metamodel.

10.3.3 _parentObject::_parent() : Object

Return the object that contains the current object. Returns null if no object isa container of the current object..

10.3.4 _localIdObject::_localId() : String

Returns a local internal identifier for the instance (it uniquely identifies theinstance in respect to the instance containg it).

10.3.5 _globalIdObject::_globalId() : String

Returns a global identifier for the instance – which identifies the instance inthe used model extent.

10.3.6 formatformat(message:String,tuple:TupleExp) : String

Print a message where the holes - marked with %s, %d, %f - are filled withthe values of the tuple expression. When using, %s the repr() function iscalled whatever is its type. The format %d is used for integers, the %f is usedfor floats.

10.3.7 reprObject::repr() : String

Prints a textual representation of the object.

10.3.8 assertassert(message:String,variable:Object, condition:Boolean)

Emits an errorn message if the condition is not fulfilled when executed.

10.3.9 debugdebug(message:String,variable:Object)

Print a message regarding the variable. Uses the repr() formatting operationto print an arbitraty object.

10.3.10 ModelType operationsThe following operations can be invoked on any instance typed by a ModelType.

ModelType::objects() : Set(Object)Returns the list of the objects in the model extent.

ModelType::objectsOfType() : Set(Object)

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

120

Returns the list of the objects in the model extentthat have the type given.

ModelType::rootobjects(): Set(Object)Returns all the objects in the extent that are not contained by other objects ofthe extent.

ModelType::removeObject : VoidRemoves an object of the model extent.

ModelType::asTransformation : OperationalTransformationCast a transformation definition compliant with the QVT metamodel as atransformation instance. This is used to invoke on the fly transformationsdefinitions created dynamically.

10.3.11 Transformation class operationsThe following operations can be invoked on any instance representing a transformationclass (OperationalTransformation instance).

OperationalTransformation::transform () : BooleanExecutes the transformation on the instance of the transformation class.Returns false is the execution of the transformation terminates with anexception and true otherwise.

OperationalTransformation::raisedException () : ClassReturns the exception raised by the transformation.

10.3.12 Predefined tagsproxy : Boolean

when present this tag indicates that the instance acts a proxy for a definition that isdefined elsewhere. Used for LibraryTransformations

alias : Stringwhen marking a Class or a Property this tag provides a alternative name. This usedin the concrete syntax to avoid name clashes.

config : Stringtag used to mark a property so allow it having its value defined at execution time.See configvalue tag.

configvalue : Stringtag used to mark an operational transformation or a call to an operationaltransformation to pass actual values to the configuration properties (see config tag).

topclasses : Stringtag used to mark model types in order to provide the list of classes names – commaseparated – that are valid as types for the root objects of a model.

main : Boolean

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

121

tag used to indicate whether a library instance or a transformation instance is themain object being defined within a textual file or its corresponding QVT instancemodule – see the concrete syntax section.

rememberChanges : Booleantag used to mark a MappingOperation, an ObjectExp or an AssignExp with anindication stating whether manual changes made within the properties assignedhave to be restored when the transformation is executed twice.

manuallyChanged : Booleantag used to mark a Properties or Classes to indicate that a property or a class hasbeen changed. A tool may automatically annotate a model with this information toimplement an execution scenario that pre-serves manual changes.

10.4 CONCRETE SYNTAX

10.4.1 EBNFWe provide below a formal definition of the textual syntax in EBNF.

10.4.1.1Syntax for module definitions

// start rule<top_level> ::= <module_definition>+

// definitions in a source file<module_definition> ::= <transformation> | <library> | <imports> | <access> | <modeltype> | <package> | <intermediate_class> | <property> | <query> | <constructor> | <entry> | <mapping_operation> | <tag> | <typedef>

// Transformations and library headers<transformation> ::= 'abstract'? 'transformation' <identifier><trans_signature> ('extends' <transf_usage> <overriding>?)? ('refines' <transf_usage> 'enforcing' <identifier>)? ';'<library> :== 'library' <identifier> lib_signature? ('extends' <lib_usage> <overriding>?)? ';'<trans_signature> ::= '(' <param_list> ')'<lib_signature> ::= '(' <id_list> ')'<overriding> ::= 'overriding' '{' scoped_id_list '}'

// general purpose grammar rules<declarator> ::= <direction_kind>? MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

122

(<identifier>|<typespec>|<identifier>':'<typespec> ) ('=' <expression>)?<typespec> ::= <scoped_id>|<complextype><complextype> ::= ('Set','OrderedSet','Sequence','Bag') '(' <typespec> ')'<direction_kind> ::= 'in' | 'inout' | 'out'<param_list> ::= <declarator> (',' <declarator>)*<id_list> ::= <identifier> (',' <identifier>)*<scoped_id_list> ::= <scoped_id> (',' <scoped_id>)*<scoped_id> ::= <identifier> ('::' <identifier>)*<expression_list> ::= <expression> (';' <expression>) ';'?

// import of libraries and transformations<imports> ::= 'imports' lib_usage ';'<access> ::= 'access' ('transformation' transf_usage | 'library' lib_usage) ';'<transf_usage> ::= <scoped_id> ( '(' declarator ')' )?<lib_usage> ::= <scoped_id> ( '(' id_list ')' )?

// model types compliance and metamodel declarations<modeltype> ::= 'modeltype' <identifier> <compliance_kind>? 'uses' <packageref> (',' packageref)* ('where' '{' <expression_list> '}' )? ';'<packageref> ::= (<scoped_id> ( '(' <uri> ')' )? | <uri>)<compliance_kind> ::= <STRING> // like: "strict" and "effective"<uri> ::= <STRING>

// Syntax for defining explicitly metamodel contents<package> ::= 'package' <identifier> '{' <class>* <tag>* '}'<class> ::= 'class' <identifier> '{' <class_property_list>? '}'<class_property> ::= ('composes'|'derived')? <declarator> ('opposites' <identifier>)?<class_property_list>::= <class_property> (';' <class_property>)* ';'?

// intermediate class definitions<intermediate_class> ::= 'intermediate' <class>

// tags<tag> ::= 'tag' <tagid> <scoped_id> ('=' <tagvalue>)? ';'<tagid> ::= <STRING><tagvalue> :: <expression>

// typedefs<typedef> :: 'typedef' <identifier> '=' <typespec> ('[' <expression> ']')? ';'

// Syntax for properties<property_key>+ <scoped_id> ':' <typespec>? ('=' <expression>)? ';' <property_key> ::= ('intermediate' | 'derived' | 'literal' | 'configuration' | 'property')

// syntax for query operations<query> ::= <query_decl> | <query_simple_def> | <query_compound_def><query_header> ::= 'query' <scoped_id> '(' <param_list>? ')' ':' <param_list>

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

123

<query_decl> ::= 'blackbox'? <query_header> ';'<query_simple_def> ::= <query_header> '=' <expression> ';'<query_compound_def> ::= <query_header> '{' <expression_list> '}'

// syntax for constructors<constructor> ::= <constructor_decl> | <constructor_def> <constructor_header> ::= 'constructor' <scoped_id> '(' param_list? ')'<constructor_decl> ::= 'blackbox'? <constructor_header> ';'<constructor_def> ::= <constructor_header> '{' <expression_list> '}'

// syntax for entry operations<entry> ::= "main" '(' param_list? ')' (';' | '{' <expression_list> '}')

// syntax for mapping operations<mapping_operation> ::= <mapping_decl> | <mapping_def> <mapping_header> ::= 'abstract'? 'mapping' <direction_kind>? <scoped_id> '(' param_list? ')' : param_list mapping_composition* mapping_refinement? mapping_when? mapping_where?<mapping_decl> ::= 'blackbox'? <mapping_header> ';'<mapping_def> ::= <mapping_header> '{' <mapping_body>? '}'<mapping_composition> ::= <composition_construct> <scoped_id_list>+<composition_construct> ::= 'disjuncts' | 'merges' | 'inherits'<mapping_when> ::= 'when' '{' <expression_list> '}'<mapping_where> ::= 'where' '{ <expression_list> '}'<mapping_body> ::= <mapping_section>* | <expression_list><mapping_section> ::= ('init'|'population'|'end') '{' <expression_list>? '}'

10.4.1.2Syntax for the expressionsIn this section we provide the syntax for the expressions. The syntax used extends thesyntax of the OCL language (any navigation expression written in OCL can beexpressed using the grammar provided by this section).

<expression> ::= <assignExp> | <varInitExp> | <letExp><assignExp> ::= impliesExp | unaryExp (':=' | '::=') (<expression> | '{' <expression_list> '}' ) 'default' <assignExp><impliesExp> ::= <inclusiveOrExp> | <impliesExp> 'implies' <inclusiveOrExp><inclusiveOrExp> ::= <exclusiveOrExp> | <inclusiveOrExp> 'or' <exclusiveOrExp> <exclusiveOrExp> ::= <andExp> | <exclusiveOrExp> 'xor' <andExp><andExp> ::= <equalityExp> | <andExp> 'and' <equalityExp><equalityExp> ::= <relationalExp> | <equalityExp> ('='|'=='|'<>') <relationalExp>MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

124

<relationalExp> ::= <additiveExp> | <relationalExp> ('<','>','<=','>=') <additiveExp><additiveExp> ::= <multiplicativeExp> | <additiveExp> ('+','-') <multiplicativeExp><multiplicativeExp> ::= <unaryExp> | <multiplicativeExp> ('*','/','%') <unaryExp><unaryExp> ::= <postfixExp> | ('-','not','#','##','*') <unaryExp><postfixExp> ::= <primaryExp> | <postfixExp> '(' <argExp>* ')' | <postfixExp> '!'? '[' (<declarator> '|')? <expression> ']' | <postfixExp> ('.'|'->'|'!->') (<scoped_id> | <iteratorExp> | <blockExp> | <ruleCallExp>)<primaryExp> ::= <literal> | <scopedId> | <ifExp> | <ruleCallExp> | <quitExp> | <tryExp> | <raiseExp> | '(' <primaryExp> ')'

<literal> ::= <INT> | <FLOAT> | <STRING> | 'true' | 'false' | 'null' | ('Set' | 'OrderedSet' | 'Bag' | 'Sequence', 'Any') '{' <expression> (',' <expression>)* '}' | ('Tuple' '{' <declarator> (',' <declarator>)* '}'<ifExp> ::= 'if' <condExpCS> then <ifBody>

'else' <ifBody> 'endif'?<ifBody> ::= <expression> | '{' <expression_list>? '}'<iteratorExp> ::= ('reject', 'collect', 'exists', 'collect', 'forAll') '(' declarator_list '|' <expression> ')' | 'iterate' '(' declarator_list ';' declarator '|' <expression> ')'<blockExp> ::= (<objectExp>|<doExp>|<whileExp>|<switchExp>|<forEach>) <objectExp> ::= 'object' (':' <modelref>)? <objectDeclarator> '{' <expression_list> '}'<modelref> ::= <identifier><objectDeclarator> ::= (<identifier> ':')? <typespec> | <identifier> ':'<whileExp> ::= 'while' '(' <declarator> (';' <expression> ) ')' '{' <expression_list>? '}'<doExp> ::= 'do' ('(' <declarator> ) ')')? '{' <expression_list>? '}'<forEachExp> ::= <forEachHeader> <expression> | '{' <expression_list>? '}'<forEachHeader> ::= ('forEach'|'forEachOne') '(' <declarator> (';' <declarator> )? ')'<switchExp> ::= 'switch' '(' <identifier> ) ')' '{' <altExp>+ ('else' '?' <expression>)? '}'<altExp> ::= '(' <expression> ')' '?' <expression> ';'<ruleCallExp> ::= ('map' | 'xmap' | 'construct' ) ('(' <declarator> ')')? <scoped_id>

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

125

<letExp> ::= 'let' <declarator_list> 'in' <expression><varInitExp> ::= 'var' <declarator> ('::=' | '=') <expression><quitExp> ::= 'break' | 'continue' | 'return'<tryExp> ::= 'try' '{' expression '}' ('except' '(' scoped_id_list ')' '{ expression '}')+<raiseExp> ::= 'raise' scoped_id ('(' arg_list ')')?

10.4.1.3ShorthandsIn this section we describe a list of shorthands used by the concrete notation.- The notation sourcelist[mycondition] is a shorthand for a calling the iterator 'select'.sourcelist->select()

- The notation sourcelist![mycondition] is mapped as a call to a call to the iterator'select' followed by a call to the first() collection operation.sourcelist->select()->first()

- The notation sourcelist->foo() is a shorthand for calling the forEach construct(ForEachExp with one property equal to false). sourcelist->forEach(i) i.foo().

- The notation sourcelist!->bar is a shorthand for calling the forEachOne construct(ForEachExp with one property equal to true).sourcelist->forEach(i) i.bar.

- The notation sourcelist->bar is a shorthand for calling the forEach construct.sourcelist->forEach(i) i.bar.

- The notation sourcelist!->bar is a shorthand for calling the forEachOne construct.sourcelist->forEach(i) i.bar.

- The notation sourcelist.bar is a shorthand for calling the collect iterator (this shorthandcomes from OCL).sourcelist.colllect(i|i.bar).

- The notation '#MyClass' involving the unary '#' operator is a shorthand for oclIsKindOf(MyClass)

- The notation '##MyClass' involving the unary '##' operator is a shorthand foroclIsTypeOf(MyClass)

- The notation '*"mystereotype"' involving the unary '*' operator is a shorthand forstereotypedBy("mystereotype"). Note that potential ambiguity with the integer/floatmultiply operation is solved thanks to the type of the argument (a string in our case).

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

126

- The notation "blabla %s\n" % myvar involving the binary '%' operator is a shortand forinvoking the pre-defined 'format' operation. The potential ambiguity with the modulooperator is solved thanks to the type of the first argument – which is a string in our case.

- The notation list->forEach(a,b) { … } is a shorthand notation for: list->forEach(a) do(b) {…}

- The notation list->switch (i) { … } is a shorthand notation for list->forEach(i) switch {…} - The notation list->object (i) { … } is a shorthand notation for:list->forEach(i) object {…}

- The notation list->construct(i) { … } is a shorthand notation for: list->forEach(i) construct {…}

- The notation list->map(i) foo() is a shorthand notation for:list->forEach(i) map foo()

10.4.2 Mapping from concrete notation to abstract syntaxIn this section, we describe how the concrete notation maps to the abstract syntax. Moreprecisely we explain how a text file – named the textual module - containing a textual-based definition of the operational transformation is translated into a QVT instancemodule – possibly rendered in as a XMI or HUTN file. The mapping is not providedformally. It is provided through a list of examples following a top-down approach. Onlythe mapping of more relevant top-level concepts are illustrated here.

When exchanging OperationalTransformations or Libraries using the QVT metamodelit is recommended to insert all the external definitions in the instance module, possiblyminimized through proxy instances. A proxy instance is an instance marked with theproxy tag containing the minimal required information to allow the operationaltransformation or library be "compiled".

10.4.2.1OperationalTransformations

transformation Foo2Bar(in x:FOO,out y:BAR);

maps as a OperationalTransformation instance that defines two ModelParameters 'x'and 'y', which in turn references (through the type property) two ModelTypes instances,'FOO' and 'BAR'. The in an out directions kinds are stored in the kind attribute of themodel parameters. The creation of the two ModelType instances provokes, for each ofthem, the creation of a Package instance with the same name representing themetamodel. The transformation Foo2Bar is marked with the 'main' tag. Note that atextual module is restricted to define a unique transformation or library. The 'main' tagis used to distinguish the defined transformation or library from the other importedtransformation, metamodel or library definitions residing at same level.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

127

transformation Foo2Bar(in x:FOO, out y:BAR) extendsAbstractFoo2Bar;

If the file contains this definition, necessarily the definition of AbstractFoo2Bar isavailable, at least as a whitebox – the signature of the operations is known - but not as ablackbox – only the global signature of the transformation is known. Apart frominserting the definition of AbstractFoo2Bar in the instance module - possibly minimizedby a proxy that would not retain the body of the operations - this declaration makes thetwo transformation be linked through the TransformationUsage metaclass with kindproperty equal to extension.

transformation Foo2Bar(in x:FOO,out y:BAR) extends AbstractFoo2Bar overriding { a, Z::b, c, d, e, f };

The effect of this declaration is the same as the previous one except that the overridinglist is saved for a further usage. When a ContextualOperation or a ContextualPropertyin the overriding list is redefined, the stored list is used to populate theContextualOperation::overrided or ContextualProperty::overrided link. The binding ofthe model types of the imported transformation with those of the importingtransformation is done on the basis of the order of model type definition (which arecontined through the Package::ownedType association).

10.4.2.2LibrariesThe declaration below defines a library FooUtilities acting on instances of the FOOmodeltype.

library FooUtilities(FOO);

The effect of this declaration is the creation of a Library instance with a 'FooUtilities' asa name and 'FOO' ModelType instance being contained by the library using the'ownedType' link.It is possible for a library not to declare a model type. This occurs for libraries that dealswith primitive types – such as defining new operations to manipulate strings.

library FooUtilities(FOO) extends BasicFooUtilities;

The declaration below has the same effect except that the BasicFooUtilities is includedin the instance module and a LibraryUsage is created with kind property with extensionvalue.

10.4.2.3Importing libraries and transformationsimport library MyMathematicalLibrary;import library FooUtilities(FOO);

These two declaration, which may occur within a transformation definition provokes thecreation of a LibraryUsage with extension value for its kind property.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

128

access library RefactorFoo(FOO);This declaration provokes the creation of a LibraryUsage with access value for its kindproperty.

access transformation RefactorFoo(FOO);This declaration provokes the creation of a TransformationUsage with access value forits kind property.

10.4.2.4Declaring the MOF packages used by the model types

modeltype FOO uses SimpleFoo("http://blabla"), IntermediateFoo;modeltype BAR "strict" uses SimpleBar;

It is not mandatory to declare the packages associated with the model types. If notprovided, a default package having the same name than the model type is created withcompliance kind equal to "effective". When provided, the "default package" createdwhen parsing the transformation or library signature needs to be updated to reflect thedeclaration. When the compliance kind is "effective", the package will either beautomatically computed – by including only the elements that are effectively used – orcould be explicitly defined, as in the example below.The quoted string accompagning a package reference represents the value of the uriattribute for a Package.

package SimpleFoo { class MyClass { x: String; y: Integer;} class AnotherClass { name : String; myClass: MyClass;}}

As any other potential external definition a package may be marked as being a proxytag "proxy" SimpleBar = true;

The declaration below, declares additional constraints regarding the model type. modeltype FOO uses FOO where { atLeastPopulatedWithTwoFoos();}.FOO::atLeastPopulatedWithTwoFoos() { self.objectsOfType(Foo)->size()>=2 }

This is mapped using the the 'additionalCondition' association and adding operations tothe FOO model type – which is a kind of class.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

129

11 The Core LanguageThis chapter introduces the structure of transformation specifications written in the Coremetamodel, and explains their execution semantics.

11.1 TRANSFORMATIONS AND DIRECTIONS

Transformations are sets of constraints and derivations defined between models. Atransformation is defined in a package.

Transformations have zero or more directions. Each direction defines a source and/ortarget of a transformation. A user who executes a transformation can check allconstraints, or enforce all derivations of that transformation in one chosen direction.

Each direction can import one or more Packages. The transformed models are sets ofobjects, in MOF Extents, of the types of the imported packages only.

Directions of a transformation may use other directions of that transformation. Onedirection using another direction declares a dependency between the two models that aretransformed. This feature is typically used for transformations with more then twodirections, where one direction is derived based on a combination of two or more otherdirections.

11.1.1 Mappings

A mapping is part of one transformation and has zero or more domains. Each domain ofa mapping has (is in) one direction of the transformation. Domains do not have names;the name of the direction identifies a domain uniquely in one mapping.

When a user executes a transformation to derive a model, all mappings that are part ofthat transformation are executed, deriving the domains that are in one chosen direction.

The following picture shows the structure of a mapping with two domains, labeled Land R.

The columns in the above picture are called areas. Each area consists of two patterns,the guard pattern and the bottom pattern. For each mapping, there exists one middle areaand one area per domain.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

130

Guard

Bottom

Domain R

Domain L

Middle

Figure 37. Core Domains and Pattern Dependencies

11.2 PATTERNS

Each rectangle in the above picture of a mapping represents a pattern. A pattern is a setof variables and constraints. In general, a mapping consists of one pair of patterns forthe mapping itself (the middle area) and one pair of patterns (a domain area) for eachdomain.

Each type of a variable of a domain pattern must be defined (or imported) in one of thepackages that are imported by the direction of its domain. Each type of a variable of amiddle pattern must be defined (or imported) in the package of the transformation.

Patterns can depend on each other. The dotted arrows in the above picture show thedependencies between the patterns, with the following meaning:

The following rules apply:• A bottom-domain pattern and a bottom-middle pattern always depend on the guard

pattern above it (either both patterns of the same domain or both middle patterns).• A middle-pattern depends on all domain patterns on the same level (either all guard

patterns or all bottom patterns).• When a direction A uses another direction B then each pattern of domain dA that has

direction A depends on the corresponding pattern of domain dB that has direction B. • There are never any dependencies between patterns of domains which do not use each

others directions.

If pattern C depends on pattern S, then C may use variables declared in S in declarationsof constraints in C.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

Dependent pattern Used pattern

131

11.3 BINDINGS

A valid binding is a binding where all variables are bound to a value other thenundefined, and where all constraints evaluate to true.

A match of a pattern results in zero or more valid bindings. A binding is a unique set ofvalues for all variables of the pattern.

For example:• A match of an empty pattern (no variables and no constraints) always results in one

valid binding, with an empty set of values.• A match of a pattern with one variable V and no constraints, always results in one valid

binding per instance of the type of V in the MOF Extent corresponding to the pattern'sowner's direction.

• A match of a pattern with two variables V and W, and no constraints, results always inone valid binding per element of the cartesian product of all instances of the type of Vand all instances of the type of W in the MOF Extent corresponding to the pattern'sowner's direction.

A partial-valid binding is a binding where one or more variables are bound to a valueother than undefined or one or more constraints evaluate to true, and no constraintsevaluate to false (thus, either true or undefined). This implies that, any valid binding ofa non-empty pattern is a partial-valid binding, and partial-valid bindings of emptypatterns do not exist.

An invalid binding is a binding where at least one of the constraints evaluates to false.In other words: an invalid binding is a binding of a non-empty pattern that is not apartial-valid binding.

11.4 BINDING DEPENDENCIES

If a pattern C depends on patterns S1…Sn, then a valid binding of C needs one validbinding for each S1…Sn. In other words: The match of pattern C takes place in thecontext of a set of valid bindings, one for each of S1…Sn.

The constraints in C that use variables from S1…Sn are evaluated using the values ofthe bindings of S1-Sn in the context. This implies that there can be zero or more validbindings of a dependent pattern, using the same valid binding of a used pattern.

A valid combination of valid bindings VSB of a set of dependent patterns SP is a set ofvalid bindings, where each pattern of SP has one unique valid binding from VSB, andeach valid binding of VSB uses other valid bindings of VSB according the dependenciesof the patterns of SP.

If a pattern C depends on patterns S1…Sn, then a partial-valid binding of C may not useany invalid binding of S1…Sn. However, even a partial-valid binding of C that usessome partial-valid bindings of S1…Sn, must have one or more variables of C bound to a

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

132

value other then undefined, or one or more constraints of C evaluated to true. That is,each new partial-valid binding must bind more variables or more constraints evaluatedto true than any binding it uses.

11.5 GUARDS

The matching of all bottom patterns only takes place in the context of a validcombination of valid-bindings of all guard patterns. The validity of the combination isdefined by the dependencies between the guard patterns.

Note that the guard patterns define neither constraints nor derivations on thetransformed models. They are only used for defining a context in which constraints andderivations can be calculated. That is, guards narrow the choice of values in modelsunder consideration for just one mapping, they do not constrain the model as a whole.

11.6 CHECKING

Domains can be checked. Let us suppose that L and R are two different domains of thesame mapping. Either L, or R, or both may be nominated as capable of being checked.

There must be (exactly) one valid combination of a valid-binding of the bottom-middlepattern and one valid binding of the bottom-domain pattern of the checked domain, foreach (and in a valid combination with a) valid combination of valid bindings of allbottom-domain-patterns of all domains not equal to the checked domain.

• Each usage of b1:P1 is read as “a binding b1 resulting from a match of pattern P1”.• Each usage of b1(b2,b3) is read as “b1 is a valid binding and b1 uses binding b2 and

binding b3”.

If domain L and R are given, and domain R is checked:

Forall gl:Guard-L, gr:Guard-R, gm:Guard-Middle (( gl() and gr() and gm(gl,gr) ) impliesforall bl:Bottom-L (

bl(gl) impliesexistsone bm:Bottom-Middle, br:Bottom-R (

br(gr) and bm(bl,gm,br))

))

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

133

If domains R, L and T are given, and domain L is checked, and the direction of R usesthe direction of T:

forall gl:Guard-L, gr:Guard-R, gt:Guard-T, gm:Guard-Middle (( gl() and gr(gt) and gt() and gm(gl,gr,gt) ) impliesforall br:Bottom-R, bt:Bottom-T (

( br(gr,bt) and bt(gt) ) impliesexistsone bm:Bottom-Middle, bl:Bottom-L (

bl(gl) and bm(bl,gm,br,bt))

))

If domain L and R are given and both are checked:

forall g gl:Guard-L, gr:Guard-R, m:Guard-Middle (( gl() and gr() and gm(gl,gr) ) impliesforall bl:Bottom-L (

bl(gl) impliesexistsone bm:Bottom-Middle, br:Bottom-R (

br(gr) and bm(bl,gm,br))

)andforall br:Bottom-R (

br(gr) impliesexistsone bl:Bottom-L, bm:Bottom-Middle (

bl(gl) and bm(bl,gm,br))

))

11.7 ENFORCEMENT

The enforcement direction designates on which domains bottom-pattern bindings arealtered to fulfill the checking constraints. Pattern bindings are only changed when thechecking constraints of a mapping are not (yet) fulfilled.

At evaluation time, one direction (representing all domains in that direction) can bechosen as the enforcement direction.

Constraints can be predicates or assignments. In the context of a binding, a predicateevaluates to true, false or undefined. Thus, predicates are only used for matching. In thecontext of a binding, assignments assign values to properties. Assignments are used toprovide values to variables, and properties of object-valued variables in order to make acheck of the patterns evaluate to true.

Assignments may be default assignments or not. An assignment that is not a defaultassignment also has the meaning of a predicate, where the assignment operator isreplaced by the equality operator. Default assignments only assign values to satisfy thechecking semantics, they do not have meaning as predicates.

Variables may be realized or not. When a variable is realized, a new instance of the typeof that variable may be created or an existing value of that variable may be deleted.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

134

Non-realized variables are only used for matching. Realized variables are used for bothmatching and enforcement.

Assignments and realized variables may only be defined in bottom-domain patterns thatare enforced and in the bottom-middle pattern.

If no valid binding of a certain pattern exists and a valid binding of that pattern isrequired by the checking semantics, then new instances of all unbound realized variabletypes are created and bound as values of the variables and all assignments are executed.

If a valid binding of a pattern exists and it is required by the checking semantics to nothave a valid binding for that pattern, then all assignments are nullified and all realizedvariables values are deleted.

Each usage of b1?(b2,b3) is read as “b1 is a partial-valid binding and b1 uses binding b2and binding b3”.

• Each usage of b1>=b2 is read as “binding b2 is a subset of (or equal to) binding b1(where b1 and b2 are bindings of the same pattern)”.

• Each usage of pre.b1 is read as “a binding b1 existing before a transformationexecution”.

• Each usage of post.b1 is read as “a binding b1 existing after a transformationexecution”.

If domain L and R are given, and both are checked, and R is enforced: forall gl:Guard-L, gr:Guard-R, gm:Guard-Middle (

( gl() and gr() and gm(gl,gr) ) impliesforall bl:Bottom-L (

bl(gl) implies (existsone post.bm:Bottom-Middle, post.br:Bottom-R (

post.bm(bl,gm,post.br) and post.br(gr) andforall pre.bm:Bottom-Middle, pre.br:Bottom-R (

( pre.br?(gr) and pre.bm?(bl,gm,pre.br) )implies( post.bm>=pre.bm and post.br>=pre.br )

))

))andforall pre.br:Bottom-R (

pre.br(gr) and (not exists pre.bm:Bottom-Middle, bl:Bottom-L (

bl(gl) and pre.bm(bl,gm,pre.br))

) implies (not exists post.br:Bottom-R, post.bm:Bottom-Middle (

( post.br?(gr) and pre.br>=post.br )or post.bm?(gm,pre.br)

))

))

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

135

If domain L and R are given, and R is checked and enforced: forall gl:Guard-L, gr:Guard-R, gm:Guard-Middle (

( gl() and gr() and gm(gl,gr) ) impliesforall bl:Bottom-L (

bl(gl) implies (existsone post.bm:Bottom-Middle, post.br:Bottom-R (

post.bm(bl,gm,post.br) and post.br(gr) andforall pre.bm:Bottom-Middle, pre.br:Bottom-R (

( pre.br?(gr) and pre.bm?(bl,gm,pre.br) )implies( post.bm>=pre.bm and post.br>=pre.br )

))

))

)

If domain L and R are given, and L is checked, and R is enforced:

forall gl:Guard-L, gr:Guard-R, gm:Guard-Middle (( gl() and gr() and gm(gl,gr) ) impliesforall pre.br:Bottom-R (

pre.br(gr) and (not exists pre.bm:Bottom-Middle, bl:Bottom-L (

bl(gl) and pre.bm(bl,gm,pre.br))

) implies (not exists post.br:Bottom-R, post.bm:Bottom-Middle (

( post.br?(gr) and pre.br>=post.br )or post.bm?(gm,pre.br)

))

))

11.7.1 Enforcement with black-box operationsIn addition to assignments and realized variables, a mapping may also use black-boxoperations for enforcement of a domain. A domain-bottom pattern can contain operationcall expressions specifically designated for the purpose of enforcement. An operationcall is designated for a specific mode of enforcement: creation or deletion.

Creation semantics: 1. Check if a valid binding of the enforced domain pattern exists for a given valid

binding of the guard and opposite domain patterns.2. If a valid binding does not exist, then execute all the enforcebale elements in

creation mode, i.e. create new instances of unbound realized variables, executeassignments, and invoke operations that are designated for the creation mode ofenforcement of the domain.

3. Check again if a valid binding of the enforced domain pattern exists for the givenvalid binding of the guard and opposite domain patterns. Checking is expected tosucceed now and yied a valid binding (if the implementation is consistent with thespecification.) If the checking fails, raise a runtime exception.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

136

Deletion semantics:4. Check if there exists a valid binding of the enforced domain pattern that is required

not to exist as per the checking semantics.5. If such a binding exists, then execute all the enforcebale elements in deletion mode,

i.e. invoke operations that are designated for the deletion mode of enforcement,nullify assignmenets, and delete realized variable values.

11.8 MAPPING REFINEMENT

Refinement of mappings is used to specialize a mapping in a more specific mapping.Both constraints and variables may be added, but not removed. A new mapping isderived by rewriting rules from the combination of the refined and refining mappings asfollows:

If mapping R refines mapping S then R and S are semantically equal to mapping S’where each pattern of S’ has all variables and constraints of the corresponding patternsof S, extended with all variables and constraints of the corresponding patterns of R. Allpatterns of R may contain new variables and constraints.

The constraints of the extended patterns in S’ are the conjunctions of the constraints thatare at the same 'position' in R and S, applied over the union of the variables in the samepositions in R and S.

11.9 MAPPING COMPOSITION

Composition of mappings is used to make it easy to define mappings that are only'active' in the context of a 'complete' instance of another mapping. In other words: Thechild mapping is matched in the context of a valid binding of the bottom-middle pattern(implying valid bindings for all other patterns) of the parent mapping.

The semantics is defined by rewriting the child mapping without using composition.

The child mapping can be rewritten by extending only the guard patterns, by allvariables and constraints of the same area. In other words: The complete parent mappingbecomes part of the guard.

If mapping C is composed by mapping P (P composes C) then C and P are semanticallyequal to mapping C’ and P where the patterns of C’ have all variables and constraints ofthe patterns of C at the same position, and C’ has its guard patterns extended with allvariables and constraints of the corresponding (same domain or all in the middle) guardand bottom patterns of P.

11.10 FUNCTIONS

Functions (from the QVTBase Package) can be defined in mappings. Functions areoperations (as in EMOF) with and OCL (query) expression as body. Thus, functions donot have side effects.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

137

Functions can be used in the constraints of the patterns of the mapping. If a mapping Srefines mapping G, then a function that is defined in mapping G can be used in mappingS as well.

The parameters of the function are the variables that can be used in the body-expression.The type of the OCL expression should conform to the result type of the function.

11.11 ABSTRACT SYNTAX AND SEMANTICS

Figure 38. QVTCore Package (partial) – Mappings and Patterns

11.11.1 AreaAn Area is a pair of patterns, one of which is a guard to the other. The evaluation of thebottom Pattern is done in the context of the bindings established by evaluating theguard (as well as other bindings, depending on which concrete subtype of Area).

Associations• guardPattern: GuardPattern [1] {composes}

the Pattern which is evaluated as a guard to the bottom Pattern.• bottomPattern: BottomoPattern [1] {composes}

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

138

the Pattern which is evaluated iff the guard of the same Area evaluates totrue with valid bindings for all its Variables.

11.11.2 MappingMappings are Areas whose Patterns contain variables which represent the trace classinstances which refer to types in the Domains contained by the Mapping. The Patternsof the Mapping's owned Domains will refer to model elements external to theTransformation of which a Mapping is part; i.e. source and/or target models, dependingon the execution direction.

SuperTypes• Rule

Associations• domain : Domain [*] {composes} (From QVTBase)

the Domains which specify the Patterns to match, (and perhaps enforce) inthe models related by this Mapping. All Domains owned by a core Mappingmust be of subtype CoreDomain.

• local [*] / context [0..1]A context Mapping can own a local Mapping resulting in compositionsemantics. (See Section 11.9 for semantics of composition.)

• specification [0..1]A Mapping can refine another Mapping, which acts as its specification. Thisresults in refinement semantics. (See Section 11.8 for refinement semantics.)

11.11.3 CoreDomainA CoreDomain is specialisation of QVTBase Domain and Area. It is an additional Areaof a Mapping (which also specialised Area) which has a nominated Direction. ThePatterns of the CoreDomain will be evaluated according to the Direction given atruntime, and the manner of evaluation will be determined by the value of its isCheckedand isEnforced attributes.

SuperTypes• Domain• Area

11.11.4 GuardPatternA GuardPattern is a concrete subtype of Pattern which contain variables which are tobe matched against the model associated with the pattern's owning Area. In the case thatthis area is a Mapping the pattern's variables may only refer to trace classes, and in thecase where it is a CoreDomain the variables may refer to the types in the TypedModelassociated with that domain. See 11.1.1 and it's explanation for the allowable variablebinding dependencies.

SuperTypes

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

139

• Pattern

Associations• area : Area [1]

the Area which the Guard Pattern is owned by.

11.11.5 BottomPatternA concrete subtype of Pattern used in the context of the GuardPattern bindings ofrelated Areas. BottomPatterns may declare RealizedVariableDeclarations as well as theVariableDeclarations which other patterns declare. This enables the matching of thebottom pattern of the domain associated with the target typed model to create and deletevalues of the RealizedVariableDeclarations to enforce the predicates of the pattern. Inaddition black-box EnforcementOperations can be referenced to allow opaque call-outsto enforce the pattern.

SuperTypes• Pattern

Associations• assignment : Assignment [*] {composes}

the Assignments which specify additional equality predicates in check mode,and assignment actions in enforce mode where no valid binding is found.

• enforcementOperation: EnforcementOperation [*] {composes}possible black-box operations to achieve the pattern eforcement in an opaquemanner. See Section 11.7.1 for the semantics of enforcement with black-boxoperations.

• realizedVariable: RealizedVariableDeclaration [*] {composes}Realized Variables are the variables whose values may change in order toenforce the owning BottomPattern when the transformation is executed inthe direction of its owning CoreDomain, or when the BottomPattern belongsto a Mapping.

11.11.6 RealizedVariableDeclarationA RealizedVariableDeclaration is a specialization of an OCL VariableDeclarationwhich may have the value it is bound to either created or deleted by the execution of atransformation.

SuperTypes• VariableDeclaration

Associations• bottomPattern : BottomPattern [*] {composes}

The bottom pattern where these variables are declared.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

140

Figure 39. QVTCore Package (partial) – BottomPattern

11.11.7 AssignmentAn Assignment owns two OCL Expressions. The first, slotOwnerExpression, identifiesthe attribute or variable to which the value identified by the second, valueExpression, isto be assigned. Assignments may also act as Predicates by treating theslotOwnerExpression and valueExpression as the two arguments to an equality operator.

Associations• slotOwnerExpression: OclExpression [1]

an OCL Expression identifying an Attribute or Variable to which thevalueExpression is to be compared or assigned.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

141

• valueExpression: OclExpression [1]an OCL Expression resulting in a value of the type of the slot identified bythe slotOwnerExpression.

• assigned: Property [1]the Property which the slotOwnerExpression should refer to, and whose typethe valueExpression should yield.

• bottomPattern: BottomPatternthe Assignment's owning BottomPattern.

11.11.8 enum EnforcementModeThe enforcement mode of an operation implementing the semantics of a Mapping.

Tags• Creation

The Operation is to create values for the realized variables• Deletion

The Operation is to delete values for the realized variables

11.11.9 EnforcementOperationAn EnforcementOperation is an OCL expression resulting in an Operation Invocationthat plays a special role in the evaluation of the BottomPattern of the enforced domainfor execution in that direction. It is analogous to an assignment in that it is only invokedfor valid bindings of the guard and opposite bottom patterns when the bottom pattern, towhich it belongs, fails. It is an Operation with side-effects, which, after invocation mustresult in the predicates of the bottom pattern evaluating to true. It may be invoked in twomodes: Create, or Delete. In Create mode it must make objects of the types of therealized variables of the bottom pattern, and in Delete mode it must delete these modelelements. In both modes it must also perform whatever other actions are required tofulfil the bottom pattern conditions.

Associations• operationCallExp: OperationCallExp [1]

an OCL Expression identifying an Operation and its parameters, which mustinclude the VariableDeclarations which are realized by the owning bottompattern.

• bottomPattern: BottomPattern [1] the BottomPattern which owns this EnforcementOperation

11.12 CONCRETE SYNTAX

We define a concrete textual syntax for mappings in this document to be able to givesome examples of mappings.

Transformation ::=“transformation” TransformationName “{”

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

142

( Direction“;” )*“}”Direction ::=DirectionName [“imports” PackageName(“,” PackageName)*]

[“uses” DirectionName(“,” DirectionName)*]Mapping ::=

“map” MappingName [“in” TransformationName] [“refines” MappingName]“{” ( [“check”] [“enforce”] DirectionName “(”DomainGuardPattern“)” “{”

DomainBottomPattern“}” )*“where” “(” MiddleGuardPattern “)” “{”

MiddleBottomPattern“}”

( ComposedMapping )*“}”ComposedMapping ::= MappingDomainGuardPattern, MiddleGuardPattern ::= GuardPatternDomainBottomPattern, MiddleBottomPattern ::= BottomPattern

GuardPattern ::=[VariableDeclaration(“,”VariableDeclaration )* “|” ]( Constraint “;” )*

BottomPattern ::=[ (VariableDeclaration | RealizedVariableDeclaration) (“,” ( VariableDeclaration | RealizedVariableDeclaration)* “|” ]( Constraint “;” )*

VariableDeclaration :=VariableName “:” TypeDeclaration

RealizedVariableDeclaration :=“realized” VariableName “:” TypeDeclarationConstraint ::= Predicate | AssignmentPredicate ::= BooleanOCLExpr

Assignement ::=[“default”] SlotOwnerOCLExpr“.”PropertyName “:=” ValueOCLExpr

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

143

12 Relations to CoreTransformation

This Section provides the transformation that gives the Relations language its semanticsin terms of the Core. The principles of the transformation are given first in anintroduction. Then the full transformation specification is shown, and finally, theapplication of this transformation to the familiar object to relational transformation isshown to demonstrate the results.

12.1 MAPPING APPROACH

In relations, transformation classes (or trace classes) are not explicitly specified andused. Instead, a relation directly specifies the relationship that should hold betweensource and target domains. Whereas in core, transformation classes and patterns overthem (to query and instantiate transformation relations between source target modelelements) are an essential part of the specification of mappings. Transformation classesand their instances are important for supporting efficient implementation of incrementalexecution scenarios, but avoiding them at specification level (as far as possible) makes atransformation writer's job easier. Since a relation is an assertion of a relationship thatexists between source and target model elements, and a transformation class essentiallyserves to capture such assertions structurally, it is possible to derive transformationclasses from relation specifications, and relation dependencies can be mapped tocorresponding transformation class dependencies.

A relation’s when and where clauses map to the middle area of a mapping – the whenclause maps to the middle-guard, and the where clause maps to the middle-bottom. Adomain pattern maps to a domain area in the core – domain variables that occur in thewhen clause map to the domain-guard and the remaining domain pattern maps to thedomain-bottom.

Relations can have arbitrary invocation dependencies. A relation can invoke multiplerelations and a relation can be invoked by multiple relations. A relation can invokeanother relation in its pre-condition (when clause) or post-condition (where clause).This style is intuitive to users and allows for complex composition hierarchies to bebuilt. A relation invoking another relation over a set of values is semantically equivalentto a relation asserting the existence of another relation - i.e. asserting the existence of aninstance of the corresponding transformation class with references to, or copies of, thevalues passed to the relation invocation. When mapping from relations to core we needto decompose relation invocation dependencies into simpler mapping dependencies -essentially each relation invocation chain needs to be broken down into its binarycomponents (see the mapping rules below). Since relations are expressed in terms ofpatterns, relation dependencies can be translated to corresponding pattern dependencies.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

144

Structural patterns of the domains of relations can be translated to equality constraints(or assignments depending on the ‘enforcement’ specification) in the core.

Relation variables used in enforced domain patterns are mapped as realized variables inthe bottom patterns of the corresponding core domain.

A relation domain can have a complex pattern consisting of multiple object nodes,properties and links. While translating to core an enforced relation domain’s complexpattern needs to be split into simpler patterns of multiple nested composed mappings.Naively putting the entire pattern in a single (core domain of a) core mapping can leadto duplicate object creations and unwanted object deletion-recreation cycles. This isbecause core has a simplified pattern matching semantics – during enforcement if apattern does not match in its entirety then all the realized variables are freshly createdirrespective of whether any of the objects already exist or not, and during deletion all therealized variables of a pattern binding are deleted irrespective of whether any of theobjects are required in other valid pattern bindings or not. See Rule 4.3 below.

12.2 MAPPING RULES

Trace class generation rule:Rule 1:Corresponding to each relation there exists a trace class in core. The trace class containsa property corresponding to each object node in the pattern of each domain of therelation.

E.g.:relation ClassToTable{ checkonly domain uml c:Class {namespace=p:Package {},kind='Persistent', name=cn} checkonly domain rdbms t:Table {schema=s:Schema {}, name=cn}}

class TClassToTable{ c: Class; p: Package; t: Table; s: Schema;}

For mapping to core we distinguish between two kinds of relations of a transformation:top-level relations and invoked relations. By a top-level relation we mean a relation thatis not invoked from the where clause of any other relation; by an invoked relation wemean a relation that is invoked from the where clause of another relation.

A top-level relation maps to a single core mapping (perhaps with composed mappings),whereas an invoked relation maps to a separate mapping for each invoker-invokedcombination.MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

145

For mapping to core we also distinguish between check-only relations and enforceablerelations. A check-only relation maps to a single core mapping, whereas an enforceablerelation may map to a composite hierarchy of core mappings.

Relation-to-mapping - common rule:Rule 2:The following are the common translation rules between a relation and a core mapping.2.1: Variables of a RelationDomain that occur in the when clause becomeVariables of the core domain guard.2.2: All other Variables of a RelationDomain become Variables of the core domainbottom pattern.2.3: An instance variable corresponding to the trace class of the relation becomes part ofthe core mapping bottom pattern with its properties assigned to the corresponding coredomain pattern variables.2.4: A property template item in the relation domain pattern becomes an assignment (oran equality predicate in the case of check-only domains) in the core domain bottompattern.2.5: Predicates of the when clause become predicates of the core mapping guard.2.6: Non RelationInvocation predicates of the where clause become predicates of thecore mapping bottom.2.6.1: RelationInvocation predicates of the where clause are ignored in this mapping,but reflected in the mapping corresponding to the invoked relation.

Top-level check-only relation to mapping:Rule 3 (extends Rule 2):3.1: A relation is 'checkonly' if it does not have any enforceable domains.3.2: The only realized variable in the entire mapping is the trace class variable in themapping bottom; there are no other realized variables in any of the mapping areas. 3.3: A property template item in a relation domain becomes an equality predicate in thecore domain bottom.3.4: A property template item in a relation domain that refers to a shared variable (i.e. avariable that also occurs in another domain) becomes an equality predicate in themapping bottom.3.5: Shared variables referenced in property template items of relation domains becomevariables of the mapping bottom.

E.g.:relation ClassToTable{ checkonly domain uml c:Class {namespace=p:Package {},kind='Persistent',name=cn} checkonly domain rdbms t:Table {schema=s:Schema {}, name=cn} when { PackageToSchema(p, s); } where { AttributeToColumn(c, t);

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

146

}}

becomes:

map ClassToTable in umlRdbms{ check uml (p:Package) { c: Class| c.namespace = p; c.kind = 'Persistent'; } check rdbms (s:Schema) { t:Table| t.schema = s; } where (v1: TPackageToSchema| v1.p = p; v1.s = s;) { realize v2: TClassToTable, cn:String | v2.p := p; v2.s := s; v2.c := c; v2.t := t; c.name = cn; t.name = cn; }}

Top-level enforceable relation to mapping:Rule 4 (extends Rule 2):4.1: A separate mapping is generated for each enforced domain of the relation.4.2: In this mapping, only the enforced relation domain in question is marked asenforced in core; all its opposite domains are marked in core as checked at most (i.e.either left as they are or downgraded to checked if marked as enforced).4.3: The enforced domain's pattern is decomposed into composed mappings as follows:

• root pattern object variable becomes a realized variable in the domain bottompattern of the current mapping.

• all identifying property template items become assignments in the domainbottom pattern of the current mapping.

• all non identifying property template items of primitive type becomeassignments in the bottom pattern of a nested mapping.

• each non identifying property template item of object type results in a nestedmapping which will have:

• a realized variable in the domain bottom, corresponding to the variable of theproperty value object.

• a property assignment from parent object variable to this variable in the domainbottom.

• and its own nested mappings recursively as described above.4.4: Predicates of the where clause that refer to variables of the enforced domain aredistributed down to the composed mappings as accumulated variable bindings becomeavailable in the nested mappings.4.5: All other opposite domains are mapped to their respective core domain parts asdescribed in Rule 3, i.e. their patterns are not decomposed down into nested mappings.

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

147

4.6: A black-box operational implementation, if any, that the relation has for theenforced domain becomes a pair of enforcement operations (one for creation and one fordeletion) in the domain-bottom pattern, both pointing to the same operation callexpression that takes its arguments from the variables corresponding to the root objectsof the domains of the relation.

E.g.:key Table (name, schema); // key of class ‘Table’key Key (name, owner); // key of class ‘Key’; owner:Tableopposite key:Keyrelation ClassToTable{ checkonly domain uml c:Class {namespace=p:Package {},kind='Persistent', name=cn, description=cd} enforce domain rdbms t:Table {schema=s:Schema {}, name=cn, description=cd, key=k:Key {name=cn+'_pk'}} when { PackageToSchema(p, s); } where { AttributeToColumn(c, t); }}

becomes:

map ClassToTable_rdbms in umlRdbms{ check uml (p:Package) { c: Class| c.namespace = p; c.kind = 'Persistent'; } check enforce rdbms (s:Schema) { realize t:Table| t.schema := s; } where (v1: TPackageToSchema| v1.p = p; v1.s = s;) { realize v2: TClassToTable, cn:String, cd:String | v2.p := p; v2.s := s; v2.c := c; v2.t := t; cn := c.name; cd := c.description; t.name := cn; } map { where () { t.description := cd; } } map { check enforce rdbms () { realize k:Key| t.key := k;

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

148

} where () { v2.k := k; k.name := cn+'_pk'; } }}

E.g.:key Table (name, schema);key Column (name, owner); // owner:Table opposite column:Columnkey Key (name, owner); // key of class ‘Key’; owner:Tableopposite key:Keyrelation ClassToTable{ checkonly domain uml c:Class {namespace=p:Package {},kind='Persistent', name=cn} enforce domain rdbms t:Table { schema=s:Schema {}, name=cn, column=cl:Column { name=cn+'_tid', type='NUMBER'}, key=k:Key{name=cn+'_pk', column=cl} } when { PackageToSchema(p, s); } where { AttributeToColumn(c, t); }}

becomes:

map ClassToTable_rdbms in umlRdbms{ check uml (p:Package) { c: Class| c.namespace = p; c.kind = 'Persistent'; } check enforce rdbms (s:Schema) { realize t:Table | t.schema := s; } where (v1: TPackageToSchema| v1.p = p; v1.s = s;) { realize v2: TClassToTable, cn:String | v2.p := p; v2.s := s; v2.c := c; v2.t := t; cn := c.name; t.name := cn; } map { check enforce rdbms () {

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

149

realize cl:Column| t.column := cl; } where () { v2.cl := cl; cl.name := cn+'_tid'; } map { where () { cl.type := 'NUMBER'; } } } map { check enforce rdbms (cl:Column) { realize k:Key| t.key := k; k.column := cl; } where (v2.cl = cl) { v2.k := k; k.name := cn+'_pk'; } }}

Invoked check-only relation to mapping:Rule 5 (extends Rule 3):5.1: An invoked relation maps to as many core mappings as the relations that invoke it,i.e. there exists a separate core mapping for each invoker-invoked pair.5.2: The guard pattern of the mapping will have a variable corresponding to the traceclass of the invoker relation, with equality predicates between root object variables of allthe patterns of all the domains of the invoked relation and their correspondingproperties in this trace class.5.3: The root object variable of a relation domain's pattern becomes a pattern variable inthe core domain guard (this is in addition to the variables that occur in the when clauseas per rule 2.1).

E.g.:relation ClassToTable{ checkonly domain uml c:Class {namespace=p:Package {},kind='Persistent', name=cn} checkonly domain rdbms t:Table {schema=s:Schema {}, name=cn} when { PackageToSchema(p, s); } where { AttributeToColumn(c, t); }}relation AttributeToColumn{ checkonly domain uml c:Class { attribute=a:Attribute

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

150

{ name=an, type=p:PrimitiveDataType {name=pn} } } checkonly domain rdbms t:Table { column=cl:Column { name=an, type=sqltype} } where { sqltype = if (pn ='INTEGER') then 'NUMBER' else 'VARCHAR'endif }}

becomes:

map AttributeColumn_ClassToTable in UmlRdbms{ check uml (c:Class) { a:Attribute, p:PrimitiveDataType| c.attribute = a; a.type = p; } check rdbms (t:Table) { cl:Column | t.column = cl; cl.type = sqlType; } where (v1:TClassToTable| v1.c = c; v1.t = t;) { realize v2:AttributeToColumn, an:String, pn:String,sqlType:String | v2.c := c; v2.a := a; v2.p := p; v2.t := t; v2.cl := cl; a.name = an; p.name = pn; cl.name = an; sqltype = if (pn ='INTEGER') then 'NUMBER' else 'VARCHAR'endif }}

Invoked enforceable relation to mapping:Rule 6 (extends Rule 4):6.1: An invoked relation maps to as many core mappings as the relations that invoke it,i.e. there exists a separate core mapping for each invoker-invoked pair.6.2: The guard pattern of the mapping will have a variable corresponding to the traceclass of the invoker relation, with equality predicates between root object variables ofall the patterns of all the domains of the invoked relation and their correspondingproperties in this trace class.6.3: The root object variable of a relation domain's pattern becomes a pattern variable inthe core domain guard (this is in addition to the variables that occur in the when clauseas per rule 2.1).

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

151

E.g.:relation ClassToTable{ checkonly domain uml c:Class { namespace=p:Package {}, kind='Persistent', name=cn } enforce domain rdbms t:Table {schema=s:Schema {}, name=cn} when { PackageToSchema(p, s); } where { AttributeToColumn(c, t); }}relation AttributeToColumn{ checkonly domain uml c:Class { attribute=a:Attribute { name=an, type=p:PrimitiveDataType {name=pn} } } enforce domain rdbms t:Table { column=cl:Column { name=an, type=sqltype} } where { sqltype = if (pn ='INTEGER') then 'NUMBER' else 'VARCHAR'endif }}map AttributeColumn_ClassToTable_rdbms in UmlRdbms{ check uml (c:Class) { a:Attribute, p:PrimitiveDataType| c.attribute = a; a.type = p; } check enforce rdbms (t:Table) { realize cl:Column | t.column := cl; } where (v1:TClassToTable| v1.c = c; v1.t = t;) { realize v2:AttributeToColumn, an:String, pn:String,sqlType:String | v2.c := c; v2.a := a; v2.p := p; v2.t := t; v2.cl := cl; an := a.name; pn := p.name; cl.name := an; sqltype := if (pn ='INTEGER') then 'NUMBER' else 'VARCHAR'endif } map { where () { cl.type := sqlType;

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

152

} }}

12.3 RELATIONAL EXPRESSION OF RELATIONS TO CORE TRANSFORMATION// Rule 1: Corresponding to each relation there exists a trace class in core.// The trace class contains a property corresponding to each object node in the// pattern of each domain of the relation.//relation RelationToTraceclass{ checkonly domain relations r:Relation{name=rn, domain = rd:RelationDomain { pattern=t:ObjectTemplateExp {bindsTo=tv:VariableDeclaration {name=vn, type=c:Class {}} } } } enforce domain core rc:Class { name='T'+rn, ownedAttribute=a:Property {name=vn, type=c} } where { SubTemplateToTraceClassProps(t, rc); }}

relation SubTemplateToTraceClassProps{ checkonly domain relations t:ObjectTemplateExp { part=tp:ObjectTemplateExp { bindsTo=tv:VariableDeclaration { name=vn, type=c:Class {}} } } enforce domain core rc:Class {ownedAttribute = a:Property {name=vn, type=c}} where { SubTemplateToTraceClassProps(tp, rc); }}

// For mapping to core we distinguish between two kinds of relations of atransformation:// - top-level relations and invoked relations.// Top-level relations are not invoked by any other relation in the // transformation.// There exists a single mapping (with perhaps contained mappings) for a top-// level relation, whereas for an invoked relation there exists a separate // mapping for each invoker-invoked combination.

// For mapping to core we also distinguish between check-only relations and// enforceable relations. A check-only relation maps to a single core mapping, // whereas an enforceable relation typically maps to a composite hierarchy of // mappings in core.//

// Rule 2:// The following are the common translation rules between // a relation and a core mapping.// 2.1: Variables of a RelationDomain that occur in the when clause become// PatternVarables of the core domain guard.// 2.2: All other Variables of a relationDomain become PatternVars// of the core domain bottom pattern.// 2.3: An instance variable corresponding to the trace class of the relation

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

153

// becomes part of the core mapping bottom pattern with its properties // set(assigned or equated) to the corresponding core domain pattern variables.// 2.4: A property template item in the relation domain pattern becomes an // assignment (or equation in the case of check-only domains) in the core domain // bottom pattern.// 2.5: Predicates of the when clause become predicates of the core mapping // guard.// 2.6: Non relation invocation predicates of the where clause become predicates // of the core mapping bottom.// 2.6.1: relation invocation predicates of the where clause are ignored in this // mapping, but are reflected in the mapping corresponding to the invoked // relation.//

// All Object template expressions (at the top level of the DomainPattern)// become assignments in the core domain bottom. Nested// ObjectTemplateExpressions become assignments in composed mappings. //

// Rule 3 (extends Rule 2):// 3.1: A relation is 'check-only' if it does not have any enforceable domains.// 3.2: Only the trace class variable in the mapping bottom is a // RealizedVariable; // there are no other realized variables in any of the mapping areas.// 3.3: A property template item in a relation domain becomes an equation in the // core domain bottom.// 3.4: A property template item in a relation domain that refers to a shared // variable becomes an equation in the mapping bottom.// 3.5: Shared variables referenced in property template items of relation // domains become variables of the mapping bottom.//relation TopLevelRelationToMappingForChecking{ allDomainVars: Set(VariableDeclaration); sharedDomainVars: Set(VariableDeclaration); unsharedWhenVars: Set(VariableDeclaration); domainVarsSharedWithWhen: Set(VariableDeclaration); domainBottomUnSharedVars: Set(VariableDeclaration); domainBottomSharedVars: Set(VariableDeclaration); checkonly domain relations r:Relation { name=rn, when=whenp:GuardPattern { variable=whenVars:Set(VariableDeclaration) {} }, where=wherep:BottomPattern {}, domain=rd:RelationDomain { isChecked=c, modelExtentName=dir:TypedModel {}, pattern=dp:DomainPattern { variable=domainVars:Set(VariableDeclaration){}, templateExp=te:ObjectTemplateExp {} } } } { r.module.transformation-> exists(t | t.topLevel->includes(r)); not r.domain->exists(d| d.isEnforced = TRUE); } enforce domain core m:Mapping { name=rn, guard=mg:GuardPattern { variable=mgVars:Set(RealizedVariableDeclaration){} }, bottom=mb:BottomPattern { realizedVariable=vs:Set(RealizedVariableDeclaration) { tcv:RealizedVariableDeclaration

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

154

{ name=rn+'_v', type=tc} },

variable = mbVars }, } } domain=md:CoreDomain {isChecked=c, modelExtentName=dir, guard=dg:GuardPattern {variable= dgVars:Set(VariableDeclaration) {}}, bottom=db:BottomPattern {variable= dbVars:Set(VariableDeclaration) {}} } } when { RelationToTraceClass(r, tc); } where { allDomainVars = r.domain->iterate(d; vars: Set(VariableDeclaration) = {} | vars->union(getVars(d)) ) sharedDomainVars = r.domain->iterate(d; vars: Set(VariableDeclaration) = {}| if vars->isEmpty() then vars->union(getVars(d)) else vars->intersection(getVars(d))); unsharedWhenVars = whenVars->minus(allDomainVars); domainVarsSharedWithWhen = domainVars->intersection(whenVars); domainBottomUnSharedVars = domainVars->minus(whenVars)->minus(sharedDomainVars); domainBottomSharedVars = domainVars->minus(whenVars)->intersection(sharedDomainVars);

RVarSetToMVarSet(unsharedWhenVars, mgVars); RWhenPatternToMGuardPattern(whenp, mg); RVarSetToMVarSet(domainVarsSharedWithWhen, dgVars); RVarSetToMVarSet(domainBottomUnSharedVars, dbVars); RVarSetToMVarSet(domainBottomSharedVars, mbVars); RDomainPatternToMDBottomPattern(te, sharedDomainVars, db, mb); RDomainVarsToTraceClassProps(domainVars, tcv, mb);

// Only non relation invocation predicates are copied from where // clause to mapping bottom.

RSimplePatternToMPattern(wherep, mb); }}

// Rule 4 (extends Rule 2):// 4.1: A separate mapping is generated for each enforced domain of the relation.// 4.2: In this mapping only the enforced domain in question is marked asenforced in core;// all its opposite domains are marked in core as checked at most (i.e. // either left as they are or downgraded to checked if marked as enforced).// 4.3: The enforced domain's pattern gets decomposed into nested mappings as // follows:// - root pattern object variable becomes a realized variable in // the domain bottom pattern of the current mapping.// - all identifying property template items become assignments in the // domain bottom pattern of the current mapping.// - all non identifying property template items of primitive type become// assignments in the bottom pattern of a nested mapping.// - each non identifying property template item of object type results // in a nested mapping which will have:// - a realized variable in the domain bottom, corresponding to the // variable of the property value object.// - a property assignment from parent object variable to this

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

155

// variable in the domain bottom.// - and its own nested mappings as above recursively.// 4.4: Predicates of the where clause that refer to variables of the enforced // domain get distributed down to the nested mappings as variable bindings // accumulate in the nested mappings.// 4.5: all other opposite domains are mapped to their respective core domain // parts as described in Rule 3, i.e. their patterns are not decomposed down into // nested mappings.// 4.6: A black-box operational implementation, if any, that the relation has for // the enforced domain becomes a pair of enforcement operations (one for creation // and one for deletion) in the domain-bottom pattern, both pointing to the same // operation call expression that takes its arguments from the variables // corresponding to the root objects of the domains of the relation.//relation TopLevelRelationToMappingForEnforcement{ allDomainVars: Set(VariableDeclaration); oppositeDomainVars: Set(VariableDeclaration); sharedDomainVars: Set(VariableDeclaration); ownRdVars: Set(VariableDeclaration); predicatesWithVarBindings: Set(Predicate); predicatesWithoutVarBindings: Set(Predicate); unsharedWhenVars: Set(VariableDeclaration); domainTopVars: Set(VariableDeclaration); checkonly domain relations r:Relation {name=rn, when=whenp:GuardPattern {variable=whenVars:Set(VariableDeclaration) {}}, where=wherep:BottomPattern { predicate=rpSet:Set(Predicate){}}, domain = rds:Set(relationDomain) { rd:RelationDomain { isEnforced = TRUE, modelExtentName=dir:TypedModel {}, variable=domainVars:Set(VariableDeclaration) {}, pattern=dp:DomainPattern { templateExp=te:ObjectTemplateExp { bindsTo=tev:VariableDeclaration {} } } } ++ rOppositeDomains } } enforce domain core m:Mapping { name=rn+'_'+dir.name, guard=mg:GuardPattern {variable=mgVars:Set(VariableDeclaration) {}}, bottom=mb:BottomPattern { realizedVariable=tcv:RealizedVariableDeclaration { name=rn+'_v', type=tc }, predicate=predicatesWithVarBindings // copy? } domain = cds:Set(CoreDomain) { md:CoreDomain { isEnforced=TRUE, modelExtentName=dir, guard=dg:GuardPattern {variable=dgVars:Set(VariableDeclaration) {}}, bottom=db:BottomPattern { realizedVariable= mtev:RealizedVariableDeclaration } } ++ mOppositeDomains } //TODO: add var only if tev not in whenVars }

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

156

when { RelationToTraceClass(r, tc); } where { allDomainVars = r.domain->iterate(d; vars: Set(VariableDeclaration) = {} | vars->union(getVars(d)) ); oppositeDomainVars = rOppositeDomains-> iterate(d; vars: Set(VariableDeclaration) = {} | vars->union(getVars(d)) ); sharedDomainVars = r.domain-> iterate(d; vars: Set(VariableDeclaration) = {} | if vars->isEmpty() then vars->union(getVars(d)) else vars->intersection(getVars(d))); ownrdVars = domainVars->minus(sharedDomainVars)->minus(whenVars); predicatesWithVarBindings = filterOutPredicatesThatReferToVars(rpSet, ownrdVars); //TODO predicatesWithoutVarBindings = rpSet->minus(predicatesWithVarBindings); unsharedWhenVars = whenVars->minus(allDomainVars); domainTopVars = domainVars->intersection(whenVars);

RVarSetToMVarSet(unsharedWhenVars, mgVars); RWhenPatternToMGuardPattern(whenp, mg); RVarSetToMVarSet(domainTopVars, dgVars); RVarToMVar(tev, mtev); RDomainToMDBottomForEnforcement(te, dir, predicatesWithoutVarBindings, ownrdVars, whenVars, sharedDomainVars, m, db, mb, tcv); RDomainVarsToTraceClassProps(oppositeDomainVars, tcv, mb); TROppositeDomainsToMappingForEnforcement(whenp, rOppositeDomains, sharedDomainVars, mOppositeDomains, mb); RRelImplToMBottomEnforcementOperation(r, rd, mb); }}

// Rule 5 (extends Rule 3):// 5.1: an invoked relation maps to as many core mappings as the relations that // invoke it.// i.e. there exists a separate core mapping for each invoker-invoked pair.// 5.2: The guard pattern of the mapping will have a variable corresponding to // the trace class of the invoker relation, with root object variables of all the // patterns of all the domains of the invoked relation being equated with '// corresponding properties of this trace class .// 5.3: The root object variable of a relation domain's pattern becomes a pattern // variable in the core domain guard (this is in addition to the variables that // occur in the when clause as per rule 2.1).//relation InvokedRelationToMappingForChecking{ allDomainVars: Set(VariableDeclaration); sharedDomainVars: Set(VariableDeclaration); unsharedWhenVars: Set(VariableDeclaration); domainVarsSharedWithWhen: Set(VariableDeclaration); domainBottomUnSharedVars: Set(VariableDeclaration); domainBottomSharedVars: Set(VariableDeclaration); checkonly domain relations r:Relation { name=rn, invokedBy= ri:RelationInvocation { predicate= p:Predicate { pattern=pt:BottomPattern {relation=ir:Relation {name=irn}} } } when=whenp:GuardPattern { variable=whenVars:Set(VariableDeclaration) {}}, where=wherep:BottomPattern {}, domain=rd:RelationDomain

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

157

{ isChecked=c, modelExtentName=dir:TypedModel {}, pattern = dp:DomainPattern { variable=domainVars:Set(VariableDeclaration) {}, templateExp=te:ObjectTemplateExp {} } } } { not r.domain->exists(d| d.isEnforced = TRUE); } enforce domain core m:Mapping { name=rn+'_'+irn, guard=mg:GuardPattern {variable=mgVars:Set(VariableDeclaration) {}}, bottom=mb:BottomPattern { realizedVariable = pvs:Set(RealizedVariableDeclaration) { tcv:RealizedVariableDeclaration { name=rn+'_v', type=tc }

}, variable = mbVars }, domain=md:CoreDomain { isChecked=c, modelExtentName=dir, guard=dg:GuardPattern {variable=dgVars:Set(VariableDeclaration) {}}, bottom=db:BottomPattern {} } } when { RelationToTraceClass(r, tc); } where { allDomainVars = r.domain->iterate(d; vars: Set(VariableDeclaration) = {} | vars->union(getVars(d)) ); sharedDomainVars = r.domain->iterate(d; vars: Set(VariableDeclaration) = {}| if vars->isEmpty() then vars->union(getVars(d)) else vars->intersection(getVars(d))); unsharedWhenVars = whenVars->minus(allDomainVars); domainVarsSharedWithWhen = domainVars->intersection(whenVars); domainBottomUnSharedVars = domainVars->minus(whenVars) ->minus(sharedDomainVars); domainBottomSharedVars = domainVars->minus(whenVars) ->intersection(sharedDomainVars);

RVarSetToMVarSet(unsharedWhenVars, mgVars); RWhenPatternToMGuardPattern(whenp, mg); RInvokerToMGuard(ir, ri, r, mg); RVarSetToMVarSet(domainVarsSharedWithWhen, dgVars); RVarSetToMVarSet(domainBottomUnSharedVars, dbVars); RVarSetToMVarSet(domainBottomSharedVars, mbVars); RDomainPatternToMDBottomPattern(te, sharedDomainVars, db, mb); RDomainVarsToTraceClassProps(domainVars, tcv, mb); RSimplePatternToMPattern(wherep, mb); }}

// Rule 6 (extends Rule 4):// 6.1: an invoked relation maps to as many core mappings as the relations that // invoke it.// i.e. there exists a separate core mapping for each invoker-invoked pair.// 6.2: The guard pattern of the mapping will have a variable corresponding to // the trace class of the invoker relation, with root object variables of all the // patterns of all the domains of the invoked relation being equated with // corresponding properties of this trace class .

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

158

// 6.3: The root object variable of a relation domain's pattern becomes a pattern // variable// in the core domain guard (this is in addition to the variables that occur in // the when clause as per rule 2.1).//relation InvokedRelationToMappingForEnforcement{ allDomainVars: Set(VariableDeclaration); oppositeDomainVars: Set(VariableDeclaration); sharedDomainVars: Set(VariableDeclaration); ownRdVars: Set(VariableDeclaration); predicatesWithVarBindings: Set(Predicate); predicatesWithoutVarBindings: Set(Predicate); unsharedWhenVars: Set(VariableDeclaration); domainTopVars: Set(VariableDeclaration); checkonly domain relations r:Relation { name=rn, invokedBy=ri:RelationInvocation { predicate=p:Predicate { pattern=pt:BottomPattern { relation=ir:Relation {name=irn} } } }, when=whenp:GuardPattern {variable=whenVars:Set(VariableDeclaration) {}}, where=wherep:BottomPattern {predicate=rpSet:Set(Predicate) {}}, domain = rds:Set(relationDomain) { rd:RelationDomain { isEnforced = TRUE, modelExtentName=dir:TypedModel {}, variable=domainVars:Set(VariableDeclaration) {}, pattern=dp:DomainPattern { templateExp=te:ObjectTemplateExp { bindsTo=tev:VariableDeclaration {} } } } ++ rOppositeDomains } } enforce domain core m:Mapping { name=rn+'_'+irn+'_'+dir.name, guard=mg:GuardPattern {variable=mgVars:Set(VariableDeclaration) {}}, bottom=mb:BottomPattern { realizedVariable=tcv:RealizedVariableDeclaration { name=rn+'_v', type=tc }, predicate=predicatesWithVarBindings // copy? } domain = cds:Set(CoreDomain) { md:CoreDomain { isEnforced=TRUE, isChecked=TRUE, modelExtentName=dir, guard=dg:GuardPattern { variable=dgVars:Set(VariableDeclaration) {} }, bottom=db:BottomPattern {} } ++ mOppositeDomains } } when { RelationToTraceClass(r, tc); } where { allDomainVars = r.domain->iterate(d; vars: Set(VariableDeclaration) = {} |

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

159

vars->union(getVars(d)) ); oppositeDomainVars = rOppositeDomains-> iterate(d; vars: Set(VariableDeclaration) = {} | vars->union(getVars(d)) ); sharedDomainVars = r.domain->iterate(d; vars: Set(VariableDeclaration) = {}| if vars->isEmpty() then vars->union(getVars(d)) else vars->intersection(getVars(d))); ownrdVars = domainVars->minus(sharedDomainVars)->minus(whenVars); predicatesWithVarBindings = filterOutPredicatesThatReferToVars(rpSet, ownrdVars); predicatesWithoutVarBindings = rpSet->minus(predicatesWithVarBindings); unsharedWhenVars = whenVars->minus(allDomainVars); domainTopVars = domainVars->intersection(whenVars)->union({tev});

RVarSetToMVarSet(unsharedWhenVars, mgVars); RWhenPatternToMGuardPattern(when, mg); RInvokerToMGuard(ir, ri, r, mg); RVarSetToMVarSet(domainTopVars, dgVars); RDomainToMDBottomForEnforcement(te, dir, predicatesWithoutVarBindings, ownrdVars, whenVars, sharedDomainVars, m, db, mb, tcv); RDomainVarsToTraceClassProps(oppositeDomainVars, tcv, mb); IROppositeDomainsToMappingForEnforcement(when, rOppositeDomains, sharedDomainVars, mOppositeDomains, mb); RRelImplToMBottomEnforcementOperation(r, rd, mb); }}

// opposite domains of a top-level relation's enforced domain are mapped as perrules// 4.2 and 4.5//relation IROppositeDomainsToMappingForEnforcement{ domainTopVars: Set(VariableDeclaration); domainBottomUnSharedVars: Set(VariableDeclaration); domainBottomSharedVars: Set(VariableDeclaration);

checkonly domain relations whenp:GuardPattern { variable=whenVars:Set(VariableDeclaration) {} } checkonly domain relations rds:Set(RelationDomain) { rd:RelationDomain { modelExtentName=dir:TypedModel {}, isChecked=c, variable=domainVars:Set(VariableDeclaration) {} pattern=dp:DomainPattern { templateExp=te:ObjectTemplateExp { bindsTo=tev:VariableDeclaration {} } } } ++ _ } checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} enforce domain core cds:Set(CoreDomain) { md:CoreDomain { isChecked=c, isEnforced=FALSE, modelExtentName=dir, guard=dg:GuardPattern { variable=dgVars:Set(VariableDeclaration) {} }, bottom=db:BottomPattern { variable=dbVars:Set(VariableDeclaration) {}

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

160

} } ++ _ } checkonly enforce domain core mb:BottomPattern { variable=mbVars:Set(VariableDeclaration) {} } where { domainTopVars = domainVars->intersection(whenVars)->union({tev}); domainBottomUnSharedVars = domainVars->minus(whenVars) ->minus({tev})->minus(sharedDomainVars); domainBottomSharedVars = domainVars->minus(whenVars)->minus({tev}) ->intersection(sharedDomainVars);

RVarSetToMVarSet(domainTopVars, dgVars); RVarSetToMVarSet(domainBottomUnSharedVars, dbVars); RVarSetToMVarSet(domainBottomSharedVars, mbVars); RDomainPatternToMDBottomPattern(te, sharedDomainVars, db, mb); }}

// opposite domains of an invoked relation's enforced domain are mapped as per // rules 4.2 and 4.5// In addition, as per rule 6.3 the root object variable of a relation domain's// pattern becomes a pattern variable in the core domain guard (this is in // addition to the variables that occur in the when clause as per rule 2.1).//relation TROppositeDomainsToMappingForEnforcement{ domainTopVars: Set(VariableDeclaration); domainBottomUnSharedVars: Set(VariableDeclaration); domainBottomSharedVars: Set(VariableDeclaration);

checkonly domain relations whenp:GuardPattern { variable=whenVars:Set(VariableDeclaration) {} } checkonly domain relations rds:Set(RelationDomain) {rd:RelationDomain { modelExtentName=dir:TypedModel {}, isChecked=c, variable=domainVars:Set(VariableDeclaration) {}, pattern=dp:DomainPattern { templateExp=te:ObjectTemplateExp {} } } ++ _ } checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} enforce domain core cds:Set(CoreDomain) { md:CoreDomain ] { isChecked=c, isEnforced=FALSE, modelExtentName=dir, guard=dg:GuardPattern { variable=dgVars:Set(VariableDeclaration) {} }, bottom=db:BottomPattern { variable=dbVars:Set(VariableDeclaration) {} } } ++ _ } checkonly enforce domain core mb:BottomPattern { variable=mbVars:Set(VariableDeclaration) {} } where { domainTopVars = domainVars->intersection(whenVars); domainBottomUnSharedVars = domainVars->minus(whenVars) ->minus(sharedDomainVars);

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

161

domainBottomSharedVars = domainVars->minus(whenVars)->intersection(sharedDomainVars);

RVarSetToMVarSet(domainTopVars, dgVars); RVarSetToMVarSet(domainBottomUnSharedVars, dbVars); RVarSetToMVarSet(domainBottomSharedVars, mbVars); RDomainPatternToMDBottomPattern(te, sharedDomainVars, db, mb); }}

relation RWhenPatternToMGuardPattern{ checkonly domain relations whenp:GuardPattern {} enforce domain core mg:GuardPattern {} where { RSimplePatternToMPattern(whenp, mg); RInvocationInWhenToMGuard(whenp, mg); }}

relation RVarSetToMVarSet(domainVarsSharedWithWhen, dgVars);{ checkonly domain relations rvSet:Set(VariableDeclaration) {rv:VariableDeclaration {}++_} enforce domain core mvSet: VariableDeclaration {mv: VariableDeclaration {}++_} where { RVarToMVar(rv, mv); }}

relation RVarToMVar{ checkonly domain relations rv:VariableDeclaration {name=n, type=t:Type {}} enforce domain core mv: VariableDeclaration {name=n, type=t}}

relation RSimplePatternToMPattern{ checkonly domain relations rp:Pattern {predicate=pd:Predicate {conditionExpression=e:OclExpression {}}} { not e.oclIsTypeOf(RelationInvocation); } enforce domain core mp:Pattern {predicate=pd} // new predicate required.}

// relation invocation in when clause maps to a trace class pattern in mapping // guard.//

relation RInvocationInWhenToMGuard{ checkonly domain relations rp:Pattern { predicate=pd:Predicate { conditionExpression=e:RelationInvocation ] { relation=r:Relation { domain=dseq:Sequence(RelationDomain) {} }, argument=aseq:Sequence(VariableExp) {} } } }

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

162

enforce domain core mp:Pattern { variable=vd:VariableDeclaration { name=tc.name+'_v', type=tc:Class {} }, } when { RelationToTraceClass(r, tc); } where { RInvocationArgToTraceClassProp(aseq, dseq, vd, mp) }}

// invocation argument position corresponds to the domain position in invoked // relation.// Domain's root pattern object var gives us the corresponding trace class prop.//relation RInvocationArgToTraceClassProp{ checkonly domain relations aseq:Sequence(VariableExp) { ve:VariableExp {variable=v:VariableDeclaration {}} ++ _ } checkonly domain relations dseq:Sequence(RelationDomain) { d:RelationDomain { pattern=dp:DomainPattern { templateExp = ote:ObjectTemplateExp { bindsTo=dv:VariableDeclaration {name=dvn} } } } ++ _ } { aseq->indexOf(ve) = dseq->indexOf(d); } enforce domain core tcvd:VariableDeclaration){} enforce domain core mp:Pattern { predicate = ee:equalsExp { lhs=pe:PropertyCallExpr {source=tcvd, name=dvn}, rhs=mv } } when { RVarToMVar(v, mv); }}

relation RInvokerToMGuard{ checkonly domain relations ir:Relation {} // invoking relation checkonly domain relations ri:RelationInvocation {argument=aseq:Sequence(VariableExp) {}} checkonly domain relations r:Relation {domain=dseq:Sequence(RelationDomain) {}} // invoked relation enforce domain core mg:GuardPattern {variable=vd:VariableDeclaration {name=tc.name+'_v', type=tc:Class {}} } when { RelationToTraceClass(ir, tc); } where { RInvokerArgToTraceClassProp(aseq, dseq, vd, mg); }}

// invocation argument position corresponds to the domain position in invoked // relation.// Invocation argument variable name gives the invoker trace class prop name;// Domain's root pattern object var gives us core domain guard var

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

163

//relation RInvokerArgToTraceClassProp(aseq, dseq, vd, mg){ checkonly domain relations aseq:Sequence(VariableExp) {ve:VariableExp {variable= v:VariableDeclaration {name=vn}} ++ _} checkonly domain relations dseq:Sequence(RelationDomain) { d:RelationDomain { pattern=dp:DomainPattern { templateExp = ote:ObjectTemplateExp { bindsTo=dv:VariableDeclaration {} } } } ++ _ } { aseq->indexOf(ve) = dseq->indexOf(d); } enforce domain core tcvd:VariableDeclaration){} enforce domain core mp:Pattern {predicate = ee:equalsExp {lhs=pe:PropertyCallExpr {source=tcvd, name=vn}, rhs=mdv}} when { RVarToMVar(dv, mdv); }}

relation RDomainPatternToMDBottomPattern{ checkonly domain relations te:ObjectTemplateExp {} checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} enforce domain core db:BottomPattern {} // domain bottom enforce domain core mb:BottomPattern {} // mapping bottom where { RDomainPatternToMDBottomPatternComposite(te, sharedDomainVars, db, mb); RDomainPatternToMDBottomPatternSimpleNonVarExpr(te, sharedDomainVars, db); RDomainPatternToMDBottomPatternSimpleUnSharedVarExpr(te, sharedDomainVars, db); RDomainPatternToMDBottomPatternSimpleSharedVarExpr(te, sharedDomainVars, mb); }}

relation RDomainToMDBottomForEnforcement{ remainingUnBoundDomainVars: Set(VariableDeclaration); predicatesWithVarBindings:Set(Predicate); remainingPredicatesWithoutVarBindings:Set(Predicate);

checkonly domain relations te:ObjectTemplateExp {bindsTo=v:VariableDeclaration {}} checkonly domain relations dir:TypedModel {} checkonly domain relations predicatesWithoutVarBindings:Set(Predicate) {} checkonly domain relations unboundDomainVars:Set(VariableDeclaration) {} checkonly domain relations whenVars:Set(VariableDeclaration) {} checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} enforce domain core m:Mapping {} enforce domain core db:BottomPattern {} // domain bottom enforce domain core mb:BottomPattern // mapping bottom { predicate=predicatesWithVarBindings-> union({ee:equalsExp {lhs=pe:PropertyCallExpr {source=tcv, name=v.name}, rhs=mv } } } enforce domain core tcv: VariableDeclaration {} // trace class variable when { RVarToMVar(v, mv)

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

164

} where { remainingUnBoundDomainVars = unboundDomainVars->minus(v); predicatesWithVarBindings = filterOutPredicatesThatReferToVars( predicatesWithoutVarBindings, remainingUnBoundDomainVars); remainingPredicatesWithoutVarBindings = predicatesWithoutVarBindings->minus(predicatesWithVarBindings);

RDomainToMDBottomForEnforcementOfIdentityProp(te, sharedDomainVars, db, mb); RDomainToMDBottomForEnforcementOfNonIdentityPropPrimitive(te, m); RDomainToMDBottomForEnforcementOfNonIdentityPropObject(te, dir, remainingPredicatesWithoutVarBindings, remainingUnboundDomainVars, whenVars, sharedDomainVars, m, tcv); }}

relation RDomainToMDBottomForEnforcementOfIdentityProp{ checkonly domain relations te:ObjectTemplateExp { bindsTo=v:VariableDeclaration { type=c:Class {} }, part=pt:PropertyTemplateItem { referredProperty=pp:Property {}, value=e:OclExpression {} } } { c.key.property->includes(pp); } checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} enforce domain core db:BottomPattern {} // domain bottom enforce domain core mb:BottomPattern {} // mapping bottom where { RDomainPatternExprToMappingDomainAssignment(v, pp, e, sharedDomainVars, db); // or RDomainPatternExprToMappingDomainVarAssignment(v, pp, e, sharedDomainVars, db); // or RDomainPatternExprToMappingBottomVarAssignment(v, pp, e, sharedDomainVars, mb); }}

relation RDomainPatternExprToMappingDomainAssignment{ checkonly domain relations v:VariableDeclaration {} checkonly domain relations pp:Property {name=pn} checkonly domain relations e:OclExpression {} { not e.oclIsTypeOf(VariableExp); } checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} enforce domain core db:BottomPattern { assignment = a:Assignment { slotOwnerExpression=pe:PropertyCallExp { source=mv, name=pn }, valueExpression=e } //copy e } where { RVarToMVar(v, mv); }}

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

165

relation RDomainPatternExprToMappingDomainVarAssignment{ checkonly domain relations v:VariableDeclaration {} checkonly domain relations pp:Property {name=pn} checkonly domain relations e:VariableExp {} checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} { not sharedDomainVars->includes(e); } enforce domain core db:BottomPattern { realizedVariable=mv:RealizedVariableDeclaration, assignment = a:Assignment { slotOwnerExpression=pe:PropertyCallExp { source=mv, name=pn }, valueExpression=e } //copy e } where { RVarToMVar(v, mv); }}

relation RDomainPatternExprToMappingBottomVarAssignment{ checkonly domain relations v:VariableDeclaration {} checkonly domain relations pp:Property {name=pn} checkonly domain relations e:VariableExp {} checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} { sharedDomainVars->includes(e) } enforce domain core mb:BottomPattern { realizedVariable=mv:RealizedVariableDeclaration, assignment = a:Assignment { slotOwnerExpression=pe:PropertyCallExp {source=mv, name=pn }, valueExpression=e } //copy e } where { RVarToMVar(v, mv); }}

relation RDomainToMDBottomForEnforcementOfNonIdentityPropPrimitive{ checkonly domain relations te:ObjectTemplateExp { bindsTo=v:VariableDeclaration {type=c:Class {}}, part=pt:PropertyTemplateItem { referredProperty=pp:Property {name=pn}, value=e:OclExpression {} } } {

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

166

not c.key.property->includes(pp); not e.oclIsTypeOf(TemplateExpr); } enforce domain core m:Mapping { local=cm:Mapping { name=m.name+'_forNonIdentityProp', bottom=bp:BottomPattern { assignment=a:Assignment { slotOwnerExpression=pe:PropertyCallExp { source=mv, name=pn }, valueExpression=e } } //copy e } } where { RVarToMVar(v, mv); }}

relation RDomainToMDBottomForEnforcementOfNonIdentityPropObject{ checkonly domain relations te:ObjectTemplateExp { bindsTo=v:VariableDeclaration {type=c:Class {}}, part=pt:PropertyTemplateItem { referredProperty=pp:Property {name=pn}, value=pte:ObjectTemplateExp {pv:VariableDeclaration {}} } } { not c.key.property->includes(pp); } checkonly domain relations dir:TypedModel {} checkonly domain relations predicatesWithoutVarBindings:Set(Predicate) {} checkonly domain relations unboundDomainVars:Set(VariableDeclaration) {} checkonly domain relations whenVars:Set(VariableDeclaration) {} checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} enforce domain core m:Mapping {local=cm:Mapping {name=m.name+'_for_'+v.name, domain = cd:CoreDomain {modelExtentName=dir, bottom= cmdb:BottomPattern {realizedVariable= mpv:VariableDeclaration, assignment = a:Assignment {slotOwnerExpression= pe:PropertyCallExp {source=mv, name=pn}, valueExpression=mpv} } //TODO: add var only if pv not in whenVars } bottom=cmmb:BottomPattern {} } } enforce domain core tcv: VariableDeclaration {} // trace class variable where { RVarToMVar(v, mv); RVarToMVar(pv, mpv); RDomainToMDBottomForEnforcement(pte, dir, predicatesWithoutVarBindings, unboundDomainVars, whenVars, sharedDomainVars, cm, cmdb, cmmb, tcv); }}

relation RDomainPatternToMDBottomPatternComposite{ checkonly domain relations te:ObjectTemplateExp{bindsTo=vte:VariableDeclaration {},

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

167

part=pt:PropertyTemplateItem {referredProperty=pp:Property{}, value=pte:ObjectTemplateExp{bindsTo=vpte:VariableDeclaration {}}} } checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} enforce domain core db:BottomPattern {predicate = ee:equalsExp {lhs= pe:PropertyCallExpr {source=mvte, name=<>}, rhs=mvpte} } enforce domain core mb:BottomPattern {} // mapping bottom when { RVarToMVar(vte, mvte); RVarToMVar(vpte, mvpte); } where { RDomainPatternToMDBottomPattern(pte, sharedDomainVars, db, mb); }}

relation RDomainPatternToMDBottomPatternSimpleUnSharedVarExpr{ checkonly domain relations te:ObjectTemplateExp{bindsTo=vte:VariableDeclaration {}, part=pt:PropertyTemplateItem {referredProperty=pp:Property{}, value=e:VariableExpression{variable=vpte:VariableDeclaration {}}} } checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} { not sharedDomainVars->includes(vpte) } enforce domain core bb:BottomPattern {predicate = ee:equalsExp {lhs= pe:PropertyCallExpr {source=mvte, name=<>}, rhs=mvpte}/*a copy of e? */ } when { RVarToMVar(vte, mvte); RVarToMVar(vpte, mvpte); }}

relation RDomainPatternToMDBottomPatternSimpleSharedVarExpr{ checkonly domain relations te:ObjectTemplateExp{bindsTo=vte:VariableDeclaration {}, part=pt:PropertyTemplateItem {referredProperty=pp:Property{}, value=e:VariableExpression{variable=vpte:VariableDeclaration {}}} } checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} { sharedDomainVars->includes(vpte) } enforce domain core db:BottomPattern {predicate = ee:equalsExp {lhs= pe:PropertyCallExpr {source=mvte, name=<>}, rhs=mvpte}/*a copy of e? */ } when { RVarToMVar(vte, mvte); RVarToMVar(vpte, mvpte); }}

relation RDomainPatternToMDBottomPatternSimpleNonVarExpr{ checkonly domain relations te:ObjectTemplateExp{bindsTo=vte:VariableDeclaration {},

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

168

part=pt:PropertyTemplateItem {referredProperty=pp:Property{}, value=e:OclExpression {}} } checkonly domain relations sharedDomainVars:Set(VariableDeclaration) {} { not e.oclIsTypeOf(TemplateExp); not e.oclIsTypeOf(VariableExpression); } enforce domain core db:BottomPattern {predicate = ee:equalsExp {lhs= pe:PropertyCallExpr {source=mvte, name=<>}, rhs=e} /* acopy of e? */ } when { RVarToMVar(vte, mvte); }}

relation RDomainVarsToTraceClassProps{ checkonly domain relations domainVars:Set(VariableDeclaration){dv:VariableDeclaration {}++_} enforce domain core tcv: VariableDeclaration {} enforce domain core mb:BottomPattern {assignment = a:Assignment{slotOwnerExpression= pe:PropertyCallExp{source=tcv, name=dv.name}, valueExpression=mdv} } when { RVarToMVar(dv, mdv); }}

relation RRelImplToMBottomEnforcementOperation{ checkonly domain relations r:Relation {operationalIml = RelationImplementation{ inDirectionOf = tm:TypedModel{}, impl = op:Operation{} } } checkonly domain relations rd:RelationDomain {modelExtentName = tm} enforce domain core mb:BottomPattern {enforcementOperation = Set(EnforcementOperation) { EnforcementOperation { enforcementMode='Create', operationCallExp=oce:OperationCallExp { referredOperation = op } }, EnforcementOperation { enforcementMode='Delete', operationCallExp=oce } } } where { RRelDomainsToMOpCallArg(r, oce); }}

relation RRelDomainsToMOpCallArg{ checkonly domain relations r:Relation {domain = RelationDomain {

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

169

pattern=DomainPattern{bindsTo=rv:VariableDeclaration{}}} } enforce domain core oce:OperationCallExp {arguments=VariableExpression { variable=mv:VariableDeclaration {}} } where { RVarToMVar(rv, mv); }}

//example identity spec syntax

key VariableDeclaration (name, pattern);key VariableDeclaration (name, relation);

function getVars(te:TemplateExp): Set(Variable){ te.part->iterate(p: vset:Set(Variable) = Set{te.bindsTo} | vset->union(getVars(p.value)) )}

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

170

A.Additional ExamplesA.RELATIONS EXAMPLES

B. UML to RDBMS Mapping

Overview

This example maps persistent classes of a simple UML model to tables of a simpleRDBMS model. A persistent class maps to a table, a primary key and an identifyingcolumn. Attributes of the persistent class map to columns of the table: an attribute of aprimitive datatype maps to a single column; an attribute of a complex data type maps toa set of columns corresponding to its exploded set of primitive datatype attributes;attributes inherited from the class hierarchy are also mapped to the columns of the table.An association between two persistent classes maps to a foreign key relationshipbetween the corresponding tables.

Figure 40. Simple UML Metamodel

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

171

Figure 41. Simple RDBMS Metamodel

UML to RDBMS mapping in textual syntax

transformation umlToRdbms(uml:SimpleUML, rdbms:SimpleRDBMS){key Table (name, schema);key Column (name, owner); // owner:Table opposite column:Columnkey Key (name, owner); // key of class ‘Key’;

// owner:Table opposite key:Keytop relation PackageToSchema // map each package to a schema{ pn: String; checkonly domain uml p:Package {name=pn}; enforce domain rdbms s:Schema {name=pn};} top relation ClassToTable // map each persistent class to a table{ cn, prefix: String;

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

172

checkonly domain uml c:Class {namespace=p:Package {}, kind='Persistent', name=cn};

enforce domain rdbms t:Table {schema=s:Schema {}, name=cn, column=cl:Column {name=cn+'_tid', type='NUMBER'}, key=k:Key {name=cn+'_pk', column=cl}}; when { PackageToSchema(p, s); } where { prefix = ''; AttributeToColumn(c, t, prefix); }}relation AttributeToColumn{ checkonly domain uml c:Class {}; enforce domain rdbms t:Table {}; primitive domain prefix:String; where { PrimitiveAttributeToColumn(c, t, prefix); ComplexAttributeToColumn(c, t, prefix); SuperAttributeToColumn(c, t, prefix); }}relation PrimitiveAttributeToColumn{ an, pn, cn, sqltype: String; checkonly domain uml c:Class {attribute=a:Attribute {name=an, type=p:PrimitiveDataType {name=pn}}}; enforce domain rdbms t:Table {column=cl:Column {name=cn,

type=sqltype}}; primitive domain prefix:String; where { cn = if (prefix = '') then an else prefix+'_'+an endif; sqltype = PrimitiveTypeToSqlType(pn); }}relation ComplexAttributeToColumn{ an, newPrefix: String; checkonly domain uml c:Class {attribute=a:Attribute {name=an,

type=tc:Class {}}}; enforce domain rdbms t:Table {}; primitive domain prefix:String; where { newPrefix = prefix+'_'+an; AttributeToColumn(tc, t, newPrefix); }}relation SuperAttributeToColumn{ checkonly domain uml c:Class {general=sc:Class {}}; enforce domain rdbms t:Table {}; primitive domain prefix:String; where {MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

173

AttributeToColumn(sc, t, prefix); }}// map each association between persistent classes to a foreign keytop relation AssocToFKey{ srcTbl, destTbl: Table; pKey: Key; an, scn, dcn, fkn, fcn: String; checkonly domain uml a:Association {namespace=p:Package {}, name=an, source=sc:Class {kind='Persistent',name=scn}, destination=dc:Class {kind='Persistent',name=dcn} }; enforce domain rdbms fk:ForeignKey {schema=s:Schema {}, name=fkn, owner=srcTbl, column=fc:Column {name=fcn,type='NUMBER',owner=srcTbl}, refersTo=pKey }; when { /* when refers to pre-condition */ PackageToSchema(p, s); ClassToTable(sc, srcTbl); ClassToTable(dc, destTbl); pKey = destTbl.key; } where { fkn=scn+'_'+an+'_'+dcn; fcn=fkn+'_tid'; }}function PrimitiveTypeToSqlType(primitiveTpe:String):String{ if (primitiveType='INTEGER') then 'NUMBER' else if (primitiveType='BOOLEAN') then 'BOOLEAN' else 'VARCHAR' endif endif;}}

UML to RDBMS mapping in graphical syntax

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

174

s:Schema

name = pn

«domain»

umlC E

rdbmsp:Package

name = pn

«domain»

PackageToSchema

c:Class

name = cnkind='Persistent'

p:Package

t:Table

name = cn

s:Schema

«domain»

umlC E

rdbms

when

PackageToSchema(p,s)

«domain»cl:Column

name=cn+'_tid'type='NUMBER'

k:Key

name=cn+'_pk'

where

AttributeToColumn(c,t,'')

ClassToTable

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

175

c:Class«domain»

cl:Column

name=cntype=sqltype

where

cn = if (prefix = '') then an else prefix + '_' + an endif;sqltype = PrimitiveTypToSqlType(pn)

PrimitiveAttributeToColumn

:Attribute

name=an umlC E

rdbms

t:Table«domain»

:PrimitiveDataType

name=pnprefix:String

«domain»

C

c:Class«domain»

where

newprefix = prefix + '_' + anAttributeToColumn(tc,t,newprefix)

ComplexAttributeToColumn

:Attribute

name=an

umlC E

rdbms t:Table«domain»

tc:Classprefix:String

«domain»

C

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

176

where

AttributeToColumn(sc,t,prefix)

SuperAttributeToColumn

umlC E

rdbms t:Table«domain»

sc:Class

prefix:String«domain»

C

c:Class«domain»

general

p:Package srcTbl:Table

when

PackageToSchema(p,s);ClassToTable(sc,srcTbl);ClassToTable(dc,destTbl)

cl:Column

name=fcntype='NUMBER'

pkey:Key

where

fkn = scc+'_'+an+'_'+dcn; fcn=fkn+'_tid';

AssocToFKey

a:Association

name = an

sc:Class

name = scn

dc:Class

name = dcn

umlC E

rdbms

«domain»fk:ForeignKey

name = fkn

«domain»

s:Schema

destTbl:Table

source destination

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

177

C.OPERATIONAL MAPPING EXAMPLES

D. Book To Publication example

package BOOK { class Book {title: String; composite chapters: Chapter;} class Chapter {title : String; nbPages : Integer;}}package PUB { class Publication {title : String; nbPages : Integer;}}transformation Book2Publication(in bookModel:BOOK,out pubModel:PUB)main() { bookModel->objectOfType(Book)->map book_to_publication();}mapping Class::book_to_publication () : Publication { title := self.title; nbPages := self.chapters->nbPages->sum(); }

E. Encapsulation example

-- This QVT definition performs an in place transformation on -- a UML class-diagram model by privatizing the attributes and -- creating accessor methods transformation Encapsulation(inout classModel:UML);modeltype UML uses "omg.org.uml14"-- entry point: selects the packages and applies the transformation -- on each package main() { classModel.objectsOfType(Package) ->map encapsulateAttributesInPackageClasses();}-- Applies the transformation to each class of the package mapping inout Package::encapsulateAttributesInPackageClasses () { init {self.ownedElement->map encapsulateAttributesInClass();}}-- Performs the encapsulation for each attribute of the class -- The initialization section is used to retrieve the list ofattributes -- The population section is used to add the two accessor operations -- The end section is used to privatize each attribute mapping inout Class encapsulateAttributesInClass () {

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

178

init { var attrs := self.attribute;} operation := { -- assignment with additive semantics attrs->forEach(a) object Operation { name := "get_" + self.name.upperFirst(); visibility := "public"; type := a.type; }; attrs->forEach(a) object Operation { name := "set_" + self.name.upperFirst(); visibility := "public"; parameter := object Parameter { name := 'a_'+ self.name.upperFirst(); kind := "in"; type := a.type;}; }; }; end { attrs->map privatizeAttribute();}}-- in place privatization of the attribute mapping inout Attribute::privatizeAttribute () { visibility := "private";}

F. Uml to Rdbms

This example expresses the same transformation semantics, and uses the samemetamodels shown in the Relations Examples in Section 12.3.

-- declaring the transformationtransformation Uml2Rdb(in srcModel:UML,out RDBMS);modeltype UML uses SimpleUml("omg.qvt-samples.SimpleUML");modeltype RDBMS uses SimpleRdbms("omg.qvt-samples.SimpleRDBMS");

-- defining specific helpers and derived propertiesquery UML::Association.isPersistent() = (self.source.kind='persistent' andself.destination.kind='persistent'); intermediate property UML::Class::leafAttributes : Sequence(LeafAttribute);

-- defining intermediate data to reference leaf attributes that may-- appear when struct data types are usedintermediate class UML::LeafAttribute { name:String;kind:String;attr:Attribute;};-- defining the default entry point for the module-- first the tables are created from classes, then the tables are-- updated with the foreign keys implied by the associations

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

179

main() { srcModel.objects()[#Class]->map class2table(); -- first pass srcModel.objects()[#Association]->map asso2table(); -- second pass}-- maps a class to a table, with a column per flattened leaf attributemapping Class::class2table () : Table when {self.kind='persistent';}{ init { -- performs any needed intialization self.leafAttributes := self.attribute->attr2LeafAttrs(); } -- population section for the table name := 't_' + self.name; column := self.leafAttributes->map leafAttr2OrdinaryColumn(); key := object Key { -- nested population section for a 'Key' name := 'k_'+ self.name; column := t.column[kind='primary']; };} -- Mapping that creates the intermediate leaf attributes data.mapping Attribute::attr2LeafAttrs (in prefix:String="",inpkind:String=""): Sequence(LeafAttribute) { init { var k := if pkind="" then self.kind else pkind endif; result := if self.type.isKindOf(PrimitiveDataType) then -- creates a sequence with a LeafAttribute instance Sequence { object LeafAttribute{attr:=self;name:=prefix+self.name;kind:=k;} } else self.type.attribute->map attr2LeafAttrs(self.name+"_",k) endif; }}-- Mapping that creates an ordinary colum from a leaf attributemapping LeafAttribute::leafAttr2OrdinaryColumn (in prefix:String=""):Column { name := prefix+self.name; kind := self.kind; type := if self.attr.type.name='int' then 'NUMBER' else 'VARCHAR'endif;}-- mapping to update a Table with new columns of foreign keysmapping Association::asso2table() : Table when {self.isPersistent();}{ init { result := self.destination.resolveone(#Table); } foreignKey := self.map asso2ForeignKey(); column := result.foreignKey.column;}

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

180

-- mapping to build the foreign keysmapping Association::asso2ForeignKey { name := 'f_' + name; refersTo := self.source.resolveone(Table).key; column := self.source.leafAttributes[kind='primary'] ->map leafAttr2ForeignColumn(source.name+'_');}-- Mapping to create a Foreign key from a lef attributes-- Inheriting of leafAttr2OrdinaryColumn has the effect to call the-- inherited rule before entering the property population sectionmapping LeafAttribute::leafAttr2ForeignColumn (in prefix:String) :Column inherits leafAttr2OrdinaryColumn { kind := "foreign";}

G. SPEM UML Profile to SPEM metamodel

transformation SpemProfile2Metamodel(in umlmodel:UML,outspemmodel:SPEM);modeltype UML uses "omg.org.spem_umlprofile";modeltype SPEM uses "omg.org.spem_metamodel";

query UML::isStereotypedBy(stereotypeName:String) : Boolean;query UML::Classifier::getOppositeAends() : Set(UML::AssociationEnd);main () { -- first pass: create all the SPEM elements from UML elements umlmodel.rootobjects()[#UML::Model]->map createDefaultPackage(); -- second pass: add the dependencies beyween SPEM elements umlmodel.objects[#UML::UseCase]->map addDependenciesInWorkDefinition();}mapping UML::Package::createDefaultPackage () : SPEM::Package { name := self.name; ownedElement := self.ownedElement->map createModelElement();}mapping UML::Package::createProcessComponent () :SPEM::ProcessComponent inherits createDefaultPackage when {self.isStereotypedBy("ProcessComponent");} {}mapping UML::Package::createDiscipline () : SPEM::Discipline inherits createDefaultPackage when {self.isStereotypedBy("Discipline");} {}

mapping UML::ModelElement::createModelElement () : SPEM::ModelElement disjuncts createProcessRole, createWorkDefinition, createProcessComponent, createDisciplineMOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

181

{}mapping UML::UseCase::createWorkDefinition () : SPEM::WorkDefinition { disjuncts createLifeCycle, createPhase, createIteration, createActivity, createCompositeWorkDefinition {}}mapping UML::Actor::createProcessRole () : SPEM::ProcessRole when {self.isStereotypedBy("ProcessRole");} {}-- rule to create the default process performer singletonmapping createOrRetrieveDefaultPerformer () : SPEM::ProcessPerformer { init { result := resolveoneByRule(createOrRetrieveDefaultPerformer); if result then return endif; } name := "ProcessPerformer";}mapping abstract UML::UseCase::createCommonWorkDefinition () : SPEM::WorkDefinition{ name := self.name; constraint := { self.constraint[isStereotypedBy("precondition")] ->map createPrecondition(); self.constraint[isStereotypedBy("goal")]->map createGoal(); };}mapping UML::UseCase::createActivity () : SPEM::WorkDefinition inherits createCommonWorkDefinition when {self.isStereotypedBy("Activity");} {}mapping UML::UseCase::createPhase () : SPEM::Phase inherits createCommonWorkDefinition when {self.isStereotypedBy("Phase");} {}mapping UML::UseCase::createIteration () : SPEM::Iteration inherits createCommonWorkDefinition when {self.isStereotypedBy("Iteration");} {}mapping UML::UseCase::createLifeCycle () : SPEM::LifeCycle inherits createCommonWorkDefinition when {self.isStereotypedBy("LifeCycle");} {}mapping UML::UseCase::createCompositeWorkDefinition () :SPEM::WorkDefinition inherits createCommonWorkDefinition when {self.isStereotypedBy("WorkDefinition");} {}mapping UML::Constraint::createPrecondition () : SPEM::Precondition { body := self.body;MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

182

}mapping UML::Constraint::createGoal () : SPEM::Goal { body := self.body;}mapping UML::UseCase::addDependenciesInWorkDefinition () : SPEM::WorkDefinition merging addDependenciesInActivity{ init { result := self.resolveone(WorkDefinition); var performers := self.getOppositeAends()[i|i.association [isStereotypedBy("perform")]->notEmpty()]; assert("A unique performer is allowed",self,not performers->size()>1) } subWork := self.clientDependency[*includes].supplier ->resolveone(WorkDefinition); performer := if performers then performers->first() else createOrRetrieveDefaultPerformer() endif;}mapping UseCase::addDependenciesInActivity () : WorkDefinition when {self.stereotypedBy("Activity");} { assistant := self.getOppositeAends()[i|i.association [a|a.isStereotypedBy("assist")]->notEmpty()]->resolve(); }

H. CORE EXAMPLES

I. UML to RDBMS Mapping

This example expresses the same transformation semantics, and uses the samemetamodels shown in the Relations Examples in Section 12.3.

-- A Transformation definition from SimpleUML to SimpleRDBMSmodule UmlRdbmsTransformation imports SimpleUML, SimpleRDBMS { transformation umlRdbms { uml imports SimpleUML; rdbms imports SimpleRDBMS; } -- Package and Schema mapping class PackageToSchema { composite classesToTables : Set(ClassToTable) opposites owner; composite primitivesToNames : Set(PrimitiveToName) oppositesowner; name : String; -- uml umlPackage : Package; -- rdbms schema : Schema; } map packageToSchema in umlRdbms {

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

183

uml () { p:Package } rdbms () { s:Schema } where () { p2s:PackageToSchema| p2s.umlPackage = p; p2s.schema = s; } map { where () { p2s.name := p.name; p2s.name := s.name; p.name := p2s.name; s.name := p2s.name; } } } -- Primitive data type marshaling class PrimitiveToName { owner : PackageToSchema opposites primitivesToNames; name : String; -- uml primitive : PrimitiveDataType; -- rdbms typeName : String; } map primitiveToName in umlRdbms { uml (p:Package) { prim:PrimitiveDataType| prim.owner = p; } check enforce rdbms () { sqlType:String } where (p2s:PackageToSchema| p2s.umlPackage=p) { realize p2n:PrimitiveToName| p2n.owner := p2s; p2n.primitive := prim; p2n.typeName := sqlType; } map { where () { p2n.name := prim.name + '2' + sqlType; } } } map integerToNumber in umlRdbms refines primitiveToName { uml () { prim.name = 'Integer'; } check enforce rdbms () { sqlType := 'NUMBER'; } }

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

184

map booleanToBoolean in umlRdbms refines primitiveToName { uml () { prim.name = 'Boolean'; } check enforce rdbms () { sqlType := 'BOOLEAN'; } } map stringToVarchar in umlRdbms refines primitiveToName { uml () { prim.name = 'String'; } check enforce rdbms () { sqlType := 'VARCHAR'; } } -- utility functions for flattening map flattening in umlRdbms { getAllSupers(cls : Class) : Set(Class) { cls.general->collect(gen|self.getAllSupers(gen))-> including(cls)->asSet() } getAllAttributes(cls : Class) : Set(Attribute) { getAllSupers(cls).attribute } getAllForwards(cls : Class) : Set(Association) { getAllSupers(cls).forward } } -- Class and Table mapping class ClassToTable extends FromAttributeOwner, ToColumn { owner : PackageToSchema opposites classesToTables; composite associationToForeignKeys : OrderedSet(AssociationToForeignKey) opposites owner; name : String; -- uml umlClass : Class; -- rdbms table : Table; primaryKey : Key; } map classToTable in umlRdbms { check enforce uml (p:Package) { realize c:Class| c.kind := 'persistent'; c.namespace := p; } check enforce rdms (s:Schema) { realize t:Table| t.kind <> 'meta'; default t.kind := 'base'; t.schema := s; } where (p2s:Package2Schema| p2s.umlPackage=p; p2s.schema=s;) { realize c2t:ClassToTable| c2t.owner := p2s; c2t.umlClass := c;

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

185

c2t.table := t; } map { where () { c2t.name := c.name; c2t.name := t.name; c.name := c2t.name; t.name := c2t.name; } } map { check enforce rdbms () { realize pk:Key, realize pc:Column| pk.owner := t; pk.kind := 'primary'; pc.owner := t; pc.key->includes(pk); default pc.key := Set(Key){pk}; default pc.type := 'NUMBER'; } where () { c2t.primaryKey := pk; c2t.column := pc; } map { check enforce rdbms () { pc.name := t.name+'_tid'; pk.name := t.name+'_pk'; } } } } -- Association and ForeignKey mapping class AssociationToForeignKey extends ToColumn { referenced : ClassToTable; owner : ClassToTable opposites associationToForeignKeys; name : String; -- uml association : Association; -- rdbms foreignKey : ForeignKey; } map associationToForeignKey in umlRdbms refines flattening { check enforce uml (p:Package, sc:Class, dc:Class| sc.namespace =p;) { realize a:Association| getAllForwards(sc)->includes(a); default a.source := sc; getAllSupers(dc)->includes(a.destination); default a.destination := dc; default a.namespace := p; } check enforce rdbms (s:Schema, st:Table, dt:Table, rk:Key| st.schema = s; rk.owner = dt; rk.kind = 'primary'; ) { realize fk:ForeignKey,

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

186

realize fc:Column| fk.owner := st; fc.owner := st; fk.refersTo := rk; fc.foreignKey->includes(fk); default fc.foreignKey := Set(ForeignKey){fk}; } where (p2s:PackageToSchema, sc2t:ClassToTable, dc2t:ClassToTable| sc2t.owner = p2s; p2s.umlPackage = p; p2s.schema = s; sc2t.table = st; dc2t.table = dt; sc2t.umlClass = sc; dc2t.umlClass = dc; ) { realize a2f:AssociationToForeignKey| a2f.owner := sc2t; a2f.referenced := dc2t; a2f.association := a; a2f.foreignKey := fk; a2f.column := fc; } map { where () { a2f.name := if a.destination=dc and a.source=sc then a.name else if a.destination<>dc and a.source=sc then dc.name+'_'+a.name else if a.destination=dc and a.source<>sc then a.name+'_'+sc.name else dc.name+'_'+a.name+'_'+sc.name endif endif endif; a.name := if a.destination=dc and a.source=sc then a2f.name else a.name endif; fk.name := name; name := fk.name; fc.name := name+'_tid'; } } map { where () { fc.type := rk.column->first().type; } } } -- attribute mapping abstract class FromAttributeOwner { composite fromAttributes : Set(FromAttribute) opposites owner; } abstract class FromAttribute { name : String; kind : String; owner : FromAttributeOwner opposites fromAttributes; leafs : Set(AttributeToColumn); -- uml attribute : Attribute to uml;

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

187

} abstract class ToColumn { -- rdbms column : Column; } class NonLeafAttribute extends FromAttributeOwner, FromAttribute { leafs := fromAttributes.leafs; } class AttributeToColumn extends FromAttribute, ToColumn { type : PrimitiveToName; } map attributes in umlRdbms refines flattening { check enforce uml (c:Class) { realize a:Attribute| default a.owner := c; getAllAttributes(c)->includes(a); } where (fao:FromAttributeOwner) { fa : FromAttribute| fa.attribute := a; fa.owner := fao; } map { where { fa.kind := a.kind; a.kind := fa.kind; } } } map classAttributes in umlRdbms refines attributes { where (fao:ClassToTable| fao.umlClass=c) {} map { where { fa.name := a.name; a.name := fa.name; } } } map primitiveAttribute in umlRdbms refines attributes { check enforce uml (t:PrimitiveDataType) { a.type := t; } where (p2n:PrimitiveToName|p2n.primitive=t) { realize fa:AttributeToColumn| fa.type := p2n; } map { where { fa.leafs := Set(AttributeToColumn) {fa}; } } } map complexAttributeAttributes in umlRdbms refines attributes { check uml (ca:Attribute|ca.type=c) {}

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

188

where (fao:NonLeafAttribute | fao.attribute=ca) {} map { where { fa.name := fao.name+'_'+a.name; } } } map complexAttribute in umlRdbms refines attributes { check uml (t:Class) { a.type = t; } where () { realize fa:NonLeafAttribute } map { where { fa.leafs := fromAttributes.leafs; } } } map classPrimitiveAttributes in umlRdbms refines classAttributes,primitiveAttribute {} map classComplexAttributes in umlRdbms refines classAttributes,complexAttribute {} map complexAttributePrimitiveAttributes in umlRdbms refinescomplexAttributeAttributes, primitiveAttribute {} map complexAttributeComplexAttributes in umlRdbms refinescomplexAttributeAttributes, complexAttribute {} -- column mapping map attributeColumns in umlRdbms { check enforce rdbms (t:Table) { realize c:Column| c.owner := t; c.key->size()=0; c.foreignKey->size()=0; } where (c2t:ClassToTable| c2t.table=t;) { realize a2c:AttributeToColumn| a2c.column := c; c2t.fromAttribute.leafs->include(a2c); default a2c.owner := c2t; } map { check enforce rdbms (ct:String) { c.type := ct; } where (p2n:PrimitiveToName) { a2c.type := p2n; p2n.typeName := ct; } } map { where () { c.name := a2c.name; a2c.name := c.name;

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

189

} } map { where () { c.kind := a2c.kind; a2c.kind := c.kind; } } }

} -- end of module UmlRdbmsTransformation

B.OCL metamodel adaptationIn this annex we provide the OCL metamodel with some adaptations needed to make itconsistent with the EMOF metamodel that is used by QVT. In the present time, theQVT metamodel cannot be properly instanciated without these adaptations. We expectthe OCL finalization task to provide an updated OCL metamodel that will make thisadaptation obsolete.

Property

PropertyCallExp

0..1

*

+referredProperty0..1

+referringExp*

Operation

OperationCallExp

0..1

*

+referredOperation0..1

+referringExp*

OclExpression*

0..1

+argument *

+parentCal l

0..1

CallExp

0..1

0..1

+source0..1

+appliedElement

0..1

VariableDeclaration

VariableExp

0..1

*

+referredVariable0..1

+referringExp*

TypedElement

Parameter(from EMOF)

ParameterExp

0..1

*

+referredParameter0..1

+paramReferringExp*

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005

190

OclExpression

IfExp

1

0..1

+condition

1

+ifOwner0..1

1

0..1

+thenExpression

1

+thenOwner

0..1

1

0..1

+elseExpression

1

+elseOwner

0..1

IteratorExp

CallExp

IterateExp

LoopExp

OclExpression 1

0..1

+body

1

+loopBodyOwner

0..1

VariableDeclaration

0..10..1 +resul t 0..1+baseExp0..1

0..1

*

+loopExp

0..1+iterator

*

0..1

0..1

+initExpression

0..1

+initializedElement

0..1

LetExp

OclExpression

0..1

+in

0..1

VariableDeclaration10..1

+variable

10..1

0..1

0..1

+initExpression

0..1

+initializedElement

0..1

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS , OCYOBER 18,2003MARCH 21, 2005

191

IntegerLiteralExpintegerSymbol : Integer

RealLiteralExprealSymbol : Real

BooleanLiteralExpbooleanSymbol : Boolean

StringLiteralExpstringSymbol : String

UnlimitedNaturalExpsymbol : UnlimitedNatural

LiteralExp

EnumerationLiteral

EnumLiteralExp

0..1

*

+referredEnumLiteral0..1

+li teralExp*PrimitiveLiteralExp

NumericLiteralExp

CollectionLiteralExpkind : CollectionKind

Type CollectionLiteralPart*

1+parts

*

1

0..1 *

+type

0..1 *

CollectionRange

OclExpression1

0..1

+fi rst 1

+fi rstOwner0..1

1

0..1

+last 1

+lastOwner

0..1

CollectionItem

1

0..1

+item

1

0..1

LiteralExp

VariableDeclaration

TupleLiteralExp

*

0..1

+tuplePart*

0..1

CollectionKindSetOrderedSetBagSequence

<<enumeration>>

MOF 2.0 QUERY/VIEWS/TRANSFORMATIONS REVISED SUBMISSION, OCTOBER 18, 2003MARCH 21, 2005