Handcrafting a Triple Graph Transformation System to Realize Round-trip Engineering Between UML Class Models and Java Source Code

Thomas Buchmann and Sandra Greiner Chair of Applied Computer Science I, University of Bayreuth, Universitätsstrasse 30, 95440, Bayreuth, Germany

Keywords: Round-trip Engineering, Model-driven Development, Xtend, Triple Graph Transformation Systems.

Abstract: Model transformations are a mandatory requirement for model-driven development, a software engineering discipline, which has become more and more popular during the last decade. Over the years, the concept of unidirectional model transformations and corresponding tool support reached maturity since these kind of transformations are widely used in model-driven engineering, mainly for forward engineering and code generation. In incremental and iterative software engineering processes, forward engineering may be too restrictive since it resembles waterfall-like processes. Thus, bidirectional transformations are required, which aim to provide support for (incrementally) transforming one or more source model to one or more target model and vice versa from only one transformation description. However, they seem to be rarely used in model- driven software development as adequate tool support is missing. On the other hand, programming languages nowadays provide support for higher-level features like closures or lambda expressions which allow to describe transformation patterns in a declarative way. In this paper, we present an approach for round-trip engineering between UML class models and Java source code, which is realized with a triple graph transformation system written in the Xtend programming language.

1 INTRODUCTION and accompanying tools have emerged (Czarnecki and Helsen, 2006). We observe tools, which sup- During the last few years, model-driven software en- port unidirectional batch transformations, e.g. ATL gineering has become more and more popular. The (Jouault et al., 2008), as well as languages for (incre- main focus of model-driven software engineering is mental) bidirectional transformations, as described in put on the development of higher-level models rather the QVT standard (OMG, 2015a). than on source code. Throughout the years, the Uni- Nowadays, tools for specifying and executing uni- fied Modeling Language (UML) (OMG, 2015b) has directional batch transformations are mature and used been established as the standard modeling language frequently in model-driven development. However, for model-driven development. in many scenarios transformations of this kind do not The Object Management Group (OMG) proposes suffice: After transforming a source model into a tar- Model-Driven Architecture (MDA) (Mellor et al., get model, extensions and changes to the target model 2004), a result of a standardization process for may still be required. As a consequence, changes core concepts in model-driven software engineering, to the source model need to be propagated such that which put strong emphasis on interoperability and manual modifications of the target model are retained. portability. UML serves as the standardized modeling These propagations call for incremental rather than language for MDA. To achieve interoperability and batch transformations. Furthermore, changes to the portability, the MDA approach uses both platform in- target model may have to be propagated to the source dependent (PIM) and platform specific (PSM) models model; then, transformations need to be bidirectional. and it uses UML to describe both of them. Altogether, this results in a round-trip engineer- Model transformations constitute the core essence ing process in which source and target models may of model-driven software engineering and especially be edited independently and changes need to be prop- MDA, where they are used, e.g., to transform PIM to agated in both directions. While several languages PSM models. Throughout the years, many languages and tools have been proposed for bidirectional and in-

27

Buchmann, T. and Greiner, S. Handcrafting a Triple Graph Transformation System to Realize Round-trip Engineering Between UML Class Models and Java Source Code. DOI: 10.5220/0005957100270038 In Proceedings of the 11th International Joint Conference on Software Technologies (ICSOFT 2016) - Volume 2: ICSOFT-PT, pages 27-38 ISBN: 978-989-758-194-6 Copyright c 2016 by SCITEPRESS – Science and Technology Publications, Lda. All rights reserved

ICSOFT-PT 2016 - 11th International Conference on Software Paradigm Trends

cremental transformations, there are still a number of the UML model and a MoDisco (Bruneliere et al., unresolved issues concerning both the languages for 2010) Java model. The TGTS merely addresses struc- defining transformations and the respective support tural transformations, including methods with empty tools (Stevens, 2007; Westfechtel, 2016). bodies for user-defined operations in the UML model, As stated above, many formalisms for defining and ignores accessor methods. The rules may be ex- model transformations have been proposed. Besides ecuted both in forward and backward direction. In the approaches mentioned earlier, graphs may be used the forward direction, an additional M2T transforma- to represent models in a natural way. As a conse- tion using Acceleo is executed, which supplies the ac- quence, graph transformation rules describe modifi- cessor methods. Please note that Acceleo allows to cations of graph structures in a declarative way. Fur- protect user-defined blocks within method bodies as- thermore, there is a comprehensive body of theories, suring that manually supplied code fragments remain languages, tools, and applications (Rozenberg, 1997; unchanged on subsequent transformations. The text- Ehrig et al., 1999). to-model transformation takes Java source code and Maintaining consistency between independent transforms it into an instance of the Java metamodel and evolving models requires a graph transformation provided by MoDisco. We supply our own incre- system, which comprises at least the source graph mental discoverer, as the standard discoverer works and the target graph. In order to incrementally prop- in batch mode only. The focus in this paper is on the agate changes, a correspondence graph is necessary TGTS which has been implemented using Xtend and in between for maintaining traceability links. As a which provides bidirectional transformations between result, a triple graph transformation system (TGTS) the UML model and the MoDisco Java model. The is required, containing rules defining source-to-target following subsections briefly introduce Xtend and the and target-to-source transformations, as well as ac- metamodels used in the transformation. tions for checking consistency and repairing incon- sistencies (Buchmann et al., 2008). Corres- MoDisco Java MoDisco UML TGTS TGTS (T2M) In this paper, we provide a case study dealing with rules pondence rules Model (EMF- Java Model Model based) Source incremental round-trip engineering of UML class (EMF- models and Java source code. Our solution has been based) Code implemented using a handcrafted TGTS written with Round-trip Support 1 the Xtend programming language. edit edit The paper is structured as follows: Section 2 pro- vides an overview on the proposed approach. In Sec- User Interaction tion 3 our approach is motivated while key aspects of Figure 1: Round-trip support for UML CASE Tools. the implementation are described in Section 4. The experiences gained in the case study are discussed in Section 5 and related work is presented in Section 6. 2.1 Xtend Section 7 concludes the paper. The general-purpose programming language Xtend has its syntactical and semantical roots in the Java 2 OVERVIEW programming language. However, it focuses on a more concise syntax and extra functionality such as This section provides an overview on our approach. type inference, extension methods and operator over- The round-trip engineering use case presented in loading. While Xtend primarily is an object-oriented this paper would require a bidirectional incremental language, it also provides declarative features known model-to-text transformation since the UML model is from , e.g., lambda expres- represented as an instance of its metamodel and the sions. The Xtend language is statically typed and it Java source code is stored using a set of text files. uses the of Java without modifications. However, up to now there is no language or tool avail- Xtend code is compiled into fully executable Java able supporting this kind of transformations. Thus, code and thus, integrates seamlessly with all existing a combination of multiple transformation languages Java libraries. and tools is needed to solve this issue. Figure 1 de- picts the chosen architecture. The TGTS operates on 2.2 Used Metamodels a correspondence model, which is placed in between As explained above, we strive for round-trip engi- 1http://eclipse.org/xtend/ neering support for UML class models and Java mod-

28 Handcrafting a Triple Graph Transformation System to Realize Round-trip Engineering Between UML Class Models and Java Source Code

Figure 2: Some relevant parts of the UML2 metamodel. els representing the Java source code (by reusing the UML2 implementation. MoDisco framework). Both metamodels are based An Association is a relation between two or more on Ecore (Steinberg et al., 2009), i.e. they share the Classifiers3. The ends are contained as properties ei- same meta-metamodel. Since most UML diagrams ther in the association or the opposite classifier. De- lack precise and formal semantics, we restrict the case pending on whether both associations ends are navi- study on the structural features of both models. Be- gable, an association is said to be bidirectional or uni- havioral aspects, like the body of method declara- directional. tions, are not regarded in this implementation. 2.2.2 Java (MoDisco) 2.2.1 Eclipse UML2 MoDisco is an extensible framework for developing Eclipse UML2 is part of the Eclipse Modeling model-driven tools to support use cases of software Project2. It provides an Ecore-based implementa- modernization. It provides an Ecore-compliant meta- tion of the OMG UML2 specification (OMG, 2015b). model for Java which resembles the AST of the Java Eclipse UML2 only constitutes the abstract syntax of language. Furthermore, it provides a discovery mech- UML2. Figure 2 depicts a simplified overview on rel- anism, that allows to parse existing Java source code evant metaclasses involved in the transformation. into instances of the supplied Java metamodel. Rel- Packages constitute the container elements of the evant cutouts of the MoDisco Java metamodel are UML model tree, with a Model, which is a specializa- shown in Figure 3. tion of a Package, as the root element. Packages may Similar to the UML2 metamodel, a Model element be nested and they contain PackageableElements, e.g. constitutes the root element and contains a hierarchy Classes, Interfaces or Enumerations. Classes and in- of Packages. However, in the Java metamodel, the terfaces may contain Operations (which may have Pa- Model is no specialization of a Package. The model rameters) and Propertys. contains primitive types (orphanTypes), as well as Properties and parameters have a multiplicity and ParameterizedTypes and ArrayTypes, which represent a type. Primitive types may be declared in the model multi-valued typed elements. or they may be imported (importedElements). Please Packages may be nested (ownedPackages) and note that in our case study we always import the may contain ownedElements, e.g. AbstractTypeDec- pre-defined primitive types supplied with the Eclipse 3Please note that in our approach we always assume that an 2http://www.eclipse.org/modeling/ association has exactly two member ends.

29 ICSOFT-PT 2016 - 11th International Conference on Software Paradigm Trends

Figure 3: Some relevant aspects of the MoDisco Java metamodel. laration, the metaclass of which is specialized among in the other one. For example, a corresponding con- others by ClassDeclaration, InterfaceDeclaration and struct for an UML Association is missing in the Java EnumerationDeclaration. metamodel whereas a CompilationUnit is not regarded An AbstractTypeDeclaration contains Body- by the UML metamodel. Furthermore, Propertys in Declarations, which can be either attributes UML are multiplicity elements, i.e. they have a lower (FieldDeclaration) or operations (MethodDeclaration). and an upper bound whereas in Java arrays or collec- Both are typed elements where the type of the opera- tions have to be used to express this behavior. tion represents the returned type. Instead of accessing this type directly, the metaclass TypeAccess provides access to the respective type. With this layer of indirection the interrelation of types is recorded. 3 MOTIVATION The input parameters for a method are modeled as ownedParameters with the metaclass SingleVari- Triple Graph Grammars (TGG) (Schürr, 1994) have ableDeclaration. Moreover, the name of an attribute been proposed to make the task of specifying inter- is placed in the VariableDeclarationFragment. model consistency maintenance easier. They may The CompilationUnits referenced in the Model con- be used to formalize model transformations without stitute the abstraction of physical files which contain specifying a direction. The TGG execution environ- type declarations, like classes, interfaces or enumera- ment automatically derives the respective forward or tions. They serve as anchor points for the M2T code backward transformation rules. On the one hand, generation supplied by the MoDisco framework. TGGs are highly declarative but on the other hand, Both metamodels share great similarities but also some transformations are easier to describe in an im- significant differences, which led to rule explosion in perative way. In (Buchmann and Westfechtel, 2013) previous round-trip approaches. For instance, while the authors present an implementation of round-trip the UML metamodel has one class for all kinds of engineering UML class models and Java source code primitive types, the Java metamodel subclasses the using TGGs. This case study unveils that many rules base class PrimitiveType for each primitive type ex- have to be copied and pasted since the used TGG ap- plicitly. Furthermore, there are elements in each proach lacks concepts, like rule inheritance and im- model which do not have a corresponding element perative language constructs.

30 Handcrafting a Triple Graph Transformation System to Realize Round-trip Engineering Between UML Class Models and Java Source Code

Another implementation of round-trip engineer- dinary programming language, such as Java. This ap- ing UML class models and Java source code us- proach is still followed frequently but clearly a more ing the bidirectional model transformation language high-level approach is desired. In the past, many for- QVT-R was discussed in (Greiner et al., 2016). Since malisms have been proposed for defining model trans- there is no reference implementation for QVT-R, the formations in the context of object-oriented modeling, only available tool for the Eclipse environment is me- e.g. QVT (OMG, 2015a). On the other hand, graphs dini QVT, which does not fully implement the QVT- may represent models in a natural way. Graph trans- R standard. As a consequence, the check-before- formations describe modifications of graph structures enforce semantics is not covered and it is not quite in a declarative way. For maintaining consistency be- clear how when- and where-clauses are applied during tween interdependent and evolving models, a graph transformation execution. Furthermore, it is observed transformation system is required, which deals with that the textual syntax of QVT-R allows a concise no- at least two graphs, namely a source graph s and a tation of the transformation rules. Still, sometimes target graph t. For incremental change propagation, the rules become quite complex due to the fact that a correspondence graph c is placed in between s and the language does not provide constructs for specify- t for maintaining traceability links. This results in a ing control flow or a template mechanism. triple graph transformation system (TGTS), the rules As stated in Section 1, many languages support- of which define source-to-target and target-to-source ing model transformations are available, e.g. ATL transformations, as well as actions for checking con- or QVT, which provide a declarative approach to de- sistency and repairing inconsistencies. scribe model transformations in a concise way. How- Developing a TGTS by hand seems to be a tedious ever, these languages come with certain limitations: and laborious task: First, in addition to the generation Our use case needs a bidirectional model transfor- of graphs, modifications and deletions have to be ad- mation, which has to be performed in an incremen- dressed. Second, each direction of the transformation tal way, in order to update existing models after sub- has to be specified – as well as rules for checking con- sequent changes. ATL only supports unidirectional sistency and establishing correspondences. batch transformations and thus, can not be used here. QVT-R on the other hand, addresses incremental and 4.1 Correspondence Model bidirectional transformations. However, as discussed in (Greiner et al., 2016), tool support for QVT-R is far In our use case, source and target models are the from being mature and there are also some flaws in Eclipse UML2 model and the MoDisco Java model the official standard. In (Buchmann and Westfechtel, (c.f., Section 2.2) respectively. As stated above, for 2013), it was shown that the chosen TGG approach incremental operations, a correspondence model is comes with better tool support than QVT-R but lack- needed. Figure 4 shows the correspondence model ing rule inheritance or template mechanisms lead to used in our implementation. A Transformation con- an explosion of transformation rules. tains an arbitrary number of correspondence elements All in all, our previous work showed using QVT-R (Corr). or TGGs might become quite tedious and also corre- In order to establish traceability links, a corre- sponding tool support has several weaknesses. Hand- spondence element always refers to one EObject from crafting a TGTS on the other hand, requires to spec- the source model and one EObject from the target ify the generation of graphs, to consider modifications model. The String desc describes the element. Since and deletions for each direction as well as to specify Corr is abstract in order to allow different and com- rules for checking consistency and establishing corre- plex specializations, we added the concrete class Ba- spondences. The contribution of this paper is to in- sicElem without additional features which is sufficient vestigate whether the effort in handcrafting a TGTS (i.e. program both transformation directions explic- itly) outweighs the drawbacks of the aforementioned approaches.

4 IMPLEMENTING THE TGTS

As stated in Section 1, model transformations play a key role in model-driven engineering. In principle, model transformations may be programmed in an or- Figure 4: Correspondence model.

31 ICSOFT-PT 2016 - 11th International Conference on Software Paradigm Trends

for our use case. If there are 1:n mappings, no addi- all unreferenced elements, where the umlElement or tional correspondence object is created but the addi- the javaElement are empty, are deleted and saves the tional elements (2-n) are manually maintained in the transformation (Listing 1, line 6,11). The String given rule that transforms the 1:1 mapping. to the deletion calls (Listing 1, line 4,9) can be used to adapt the behavior for specific elements, e.g. deleting 4.2 Transformation Rules elements without a correspondence object.

Listing 1: Abstract base class for our transformation rules. When specifying a model transformation, the soft- ware engineer needs to decide whether the model el- 1 abstract class Elem2Elem { ements should be transformed bottom-up, i.e. start- 2 ... ing with the leaf nodes of the spanning containment 3 def void sourceToTarget(String s) { 4 deleteUnreferencedTargetElements(s) tree or at the root node. As declarative approaches 5 corrModel.save(null) perform a topological sort of model elements, soft- 6 targetModel.save(null) ware developers only have very limited influence on 7 } the transformation order. Typically, the developer 8 def void targetToSource(String s) { must presume the execution behavior when declaring 9 deleteUnreferencedSourceElements(s) the rules. When hand-crafting a TGTS on the other 10 corrModel.save(null) hand, the transformation order is fully under the con- 11 sourceModel.save(null) 12 } trol of the user. We chose to strictly follow a top- 13 def Corr getCorrModelElem(EObject ob) { down approach on the highest level (i.e. on the el- 14 corrModel.contents.get(0).correspondences ement level). As a consequence, when transforming 15 .findFirst[ c | c.umlElement == ob || c. child elements, e.g. attributes or methods of classes, javaElement == ob] we can always be sure that the respective containers 16 } and the referred types already exist. Therefore, our 17 def getOrCreateCorrModelElement(EObject ob, String description) { transformation starts at the respective root elements 18 var Corr c = ob.getCorrModelElem (i.e. the Model in both cases) and the primitive types. 19 if (c == null){ Next, the Package hierarchy is established. Once this 20 c = corrFactory.createBasicElem => [ is finished, type declarations (classes, interfaces, enu- 21 if (ob.eClass.EPackage instanceof meration) and associations are transformed followed UMLPackage) by the respective inheritance relationships. We further 22 umlElement = ob tackle properties and methods afterwards. 23 if (ob.eClass.EPackage instanceof JavaPackage) As we are hand-crafting our TGTS (unlike in pre- 24 javaElement = ob vious approaches (Greiner et al., 2016; Buchmann 25 desc = description and Westfechtel, 2013), where bidirectional model 26 ] transformation formalisms were used), we need to ex- 27 corrModel.contents.get(0).correspondences plicitly specify both transformation directions. Fur- += c thermore, we need to address creation, deletion or up- 28 } 29 returnc date of existing elements. To reduce the specification 30 }} effort, we made use of the fact that Xtend builds on the Java VM and it provides mechanisms for inheri- tance and method overloading. Listing 1 provides a The methods getOrCreateModelElement and get- cutout of the abstract base class for all transformation CorrModelElem maintain the traceability links in the rules. correspondence model. Within the transformation rules sourceToTarget and targetToSource the method The base class consists of the three resources getOrCreateModelElement is called (e.g., Listing 2, sourceModel, targetModel and corrModel, which are line 5,14) to extract the element to be created. The not shown in Listing 1 due to space restrictions and call parameters are: which are created or kept consistent during the trans- formations. The methods sourceToTarget() and tar- EObject ob The context object on which the method getToSource() are overridden in each class inheriting is called from Elem2Elem. The respective implementations String description The description identifying the contain the transformation rule for the corresponding correspondence elements elements for each transformation direction. The su- per rule, which is executed in the overriding meth- This method calls getCorrModelElem which re- ods at last (e.g., Listing 2, line 9,18), ensures that trieves the requested object from the correspondence

32 Handcrafting a Triple Graph Transformation System to Realize Round-trip Engineering Between UML Class Models and Java Source Code

model if it is already present. If a correspondence ob- 17 ] ject cannot be found for the given element, it will be 18 super.targetToSource("model") created (Listing 1, line 20) and stored in the respec- 19 }} tive EReference (umlElement or javaElement). Please note that for each of the subsequent descriptions the For the Model2Model rule seen in Listing 2 this only source represents the UML model and the target in- comprises the name attribute. Afterwards, the cre- dicates the Java model. Accordingly, if the method ated or updated model is added to the targetModel or sourceToTarget is called, a transformation from the sourceModel respectively. The metaclass Model is the UML model to the Java model is performed and vice root for the respective metamodel, i.e. there should versa in case of calling targetToSource. We further only exist one Model element. Other references of the denote the source to target as forward and the oppo- Models, e.g. the orphanTypes of the Java Model, are site as backward direction. maintained in the transformation of the referenced el- The redefinitions of the methods sourceToTarget ements. and targetToSource always consist of the following The transformation of models (and, e.g. pack- basic steps: First, the resource of the specified direc- ages and classes) are declared fairly straightforward tion is searched for the element transformed in the re- because the metamodels share many features and are spective rule. Next, the correspondence element is almost 1:1 mappings. Treating UML associations, extracted with the aforementioned method getOrCre- which have no corresponding concept in the Java ateCorrespondenceModelElement. From the returned model, is more complex, for instance. We decided element the target object for the respective direction to add a ClassDeclaration in the Java model for every is either extracted – if it already exists – or created association. This class contains both memberEnds of and added to the correspondence element as umlEle- the association as fields and corresponding accessor ment or javaElement by the methods getOrCreate- methods with proper visibilities that reflect the navi- SourceElem and getOrCreateTargetElem respectively gability as specified in the UML model5. The corre- (Listing 2, line 5,14). This way an already existing spondence element with the description "association" correspondence and target element can be altered in- always points to an Association as umlElement and a crementally4. Thereafter, the basic properties of the ClassDeclaration as javaElement. target element for the respective direction are updated Listing 3 presents a simplification of how a class or added. is created for an association and vice versa. The cre- ated class is added to the package of the association Listing 2: Class to transform the root elements of both models. (Listing 3, line 7), receives the name of the asso-

1 class Model2Model extends Elem2Elem { ciation and stores all memberEnds as bodyDeclara- 2 override void sourceToTarget(String s) { tions. As each classifier needs a CompilationUnit in 3 sourceModel.contents.filter(typeof(org. the Java model, it is created or updated by reusing the eclipse.uml2.uml.Model)) method getOrCreateCompU in line 8 that supports all 4 .forEach[m | kinds of AbstractTypeDeclarations. The Compilatio- 5 var targ = m.getOrCreateCorrModelElement(s nUnit ).getOrCreateTargetElem(JavaPackage. is added to the Java model without creating a eINSTANCE.model) separate correspondence element because the UML 6 targ.name = m.name association is already mapped to the corresponding 7 targetModel.contents += targ Java class. Thus, it is necessary to manually update 8 ] or delete the CompilationUnit in case the correspond- 9 super.sourceToTarget("model") ing association is modified or removed. The update 10 } is performed in the method getOrCreateCompU, the 11 override void targetToSource(String s) { deleteUnreferencedTargetEle- 12 targetModel.contents.filter(typeof(Model)) deletion in the method 13 .forEach[ m | ments (Listing 1, line 4). 14 var src = m.getOrCreateCorrModelElement(s ).getOrCreateSourceElem(UMLPackage. Listing 3: Class to transform the UML associations to Java classes. Literals.MODEL) 15 src.name = m.name 1 class Association2Class extends Elem2Elem { 16 sourceModel.contents += src 2 override sourceToTarget(String s) { 3 sourceModel.allContents.filter(typeof( 4Incremental means that the target and correspondence ele- Association)) ment will not be created anew if they already exist. Their properties, on the other hand, are overwritten. Otherwise, 5This class serves as 1:1 mapping for the association (but one would have to calculate or track the differences be- not for its ends) and can be extended for more general tween the previous and the current version first. UML concepts like, e.g. n-ary associations.

33 ICSOFT-PT 2016 - 11th International Conference on Software Paradigm Trends

4 .forEach [ a | eINSTANCE.fieldDeclaration) 5 var cl = a.getOrCreateCorrModelElement(s 5 setOwnerJava(p, fd) ).getOrCreateTargetElem(JavaPackage 6 fd.originalCompilationUnit = fd. .eINSTANCE.classDeclaration) abstractTypeDeclaration. 6 cl.name = a.name.toFirstUpper() originalCompilationUnit 7 a.package.corrModelElement.javaElement. 7 setNameJava(p,fd) ownedElements += cl 8 setTypeJava(p, fd) 8 cl.originalCompilationUnit = 9 setVisibility(p,fd) getOrCreateCompU(cl) 10 ] 9 if (cl.comments.size == 0) 11 super.sourceToTarget(s) } 10 cl.comments += jFact.createJavadoc 11 cl.comments.get(0).content = "/** In the backward direction depicted in Listing 5 these 12 @associationClass" + cl.name + " /" * * comments are used to construct the memberEnds. 13 ... 14 ] The method setOwnerUML (Listing 5, line 7) deter- 15 super.sourceToTarget(s) mines from the annotation whether the end is navi- 16 } gable or not and whether it is owned by the associa- 17 override targetToSource(String s) { tion. As a consequence, it will add the created prop- 18 targetModel.allContents.filter(typeof( erty to either one of the classes participating in the ClassDeclaration)).filter[ cd | association or to the association as one of the owne- 19 cd.comments.size > 0 && cd.comments.get(0). content.contains(’@associationClass’)] dEnd or the navigableOwnedEnd references. The type 20 .forEach [ cd | is determined with the method setTypeUML. In case 21 var assoc = cd.getOrCreateCorrModelElement the type of the property is primitive, the property is (s).getOrCreateSourceElem(UMLPackage. simply added to the UML classifier corresponding eINSTANCE.association) with the abstractTypeDeclaration of the Java field. If 22 assoc.name = cd.name.toFirstLower the type is a ParameterizedType or an ArrayType, the 23 assoc.package = cd.package. value upper of the UML Property will be set to infin- corrModelElement.umlElement 24 ] ity. Moreover, in the latter case the UML type can- 25 super.targetToSource(s) not be retrieved from the correspondence element in a 26 }} straightforward way but the typeArguments and types respectively must be used to obtain the corresponding To distinguish between association classes and umlElement. “regular” classes, we annotate them with a Javadoc comment (Listing 3, line 11f.). Thus, we can identify Listing 5: Transformation of Java FieldDeclarations. annotated classes in the backward direction and build 1 override targetToSource(String s) { up the Association correspondingly. The name is ex- 2 targetModel.allContents.filter(typeof( tracted from the ClassDeclaration (Listing 3, line 22) FieldDeclaration)) and the right package (Listing 3, line 23) is set. The 3 .forEach [ fd | var p = fd.getOrCreateCorrModelElement(s). memberEnds are treated like other properties with the 4 getOrCreateSourceElem(UMLPackage. next rules. Literals.PROPERTY) Listing 4 shows the forward transformation of 5 p.name = fd.fragments.get(0).name properties of all kinds. If they are of primitive type, 6 setTypeUML(fd, p) they will be added to the containing classifier. If they 7 setOwnerUML(fd,p) belong to an association, the method setOwnerJava 8 ... (Listing 4, line 5) will add both memberEnds as body- 9 ] 10 super.targetToSource(s) } Declarations to the corresponding introduced associ- ation class. Furthermore, this method applies com- ments whether the end is owned by the association or the class and whether it is navigable. 4.3 Round-trip Example

Listing 4: Transformation for UML properties. This section provides a brief example to illustrate a simple round-trip scenario in our use case. 1 override def sourceToTarget(String s) { Figure 5 depicts the single transformation steps. It 2 sourceModel.allContents.filter(typeof( Property)) provides cutouts of the UML abstract syntax as well 3 .forEach [ p | as of the resulting Java model in the Ecore tree rep- 4 var fd = p.getOrCreateCorrModelElement(s). resentation. The transformation starts with a given getOrCreateTargetElem(JavaPackage. UML model and an empty Java model. Subsequent

34 Handcrafting a Triple Graph Transformation System to Realize Round-trip Engineering Between UML Class Models and Java Source Code

Figure 5: Example round-trip scenario. changes are added incrementally. In the initial model 5 DISCUSSION many persons may live at one Address where the ends of the association lives at are contained in the re- This section discusses the lessons learned from im- spective opposite class. This indicates an association plementing a bidirectional model transformation with which is navigable in both directions. Transform- a hand-crafted TGTS written in Xtend. The integra- ing in the forward direction results in three classes tion of the system, on the other hand, is yet to come where the ends are added as fields in the associa- and the evaluation will be published separately. tion class. However, the comment of the fields reg- Basically, we can categorize the relations between isters the classes participating in the association as source and target model elements into 1:1 mappings owner of the fields (1) by noting a "type" instead of (e.g., a UML package and a Java package) and 1:n (a an "association". Transforming backward correctly UML class and a Java ClassDeclaration, a Java Com- results in the original model. Next, the association be- pilatonUnit and a ParameterizedType) mappings. We comes owner of the person end in the UML instance found out that 1:1 mappings are straightforward and (2). Transforming forward again adapts the comment easy to implement and that additional elements in the of the corresponding field and notes that the owner involved models may be added without restrictions: is now the association (3). Thereafter, it is decided For instance, a UML class needs a corresponding Java that a person might live at different addresses so the ClassDeclaration and the ClassDeclaration always be- class Address is replaced by an ParameterizedType longs to a CompilationUnit which must be included ad- that serves as a collection for many Address instances ditionally in the Java model. (4). These changes are propagated back to the UML In contrast to purely declarative approaches, lan- model when applying an incremental backward trans- guage features, like inheritance or generics, can be formation: the property address is now multi-valued used seamlessly in the Xtend language. While the (5) and the person end is still contained in the associ- lack of these features in the QVT-R or the TGG ap- ation (6). proach leads to a combinatorial explosion in the num- ber of rules which have to be copied and pasted, e.g. in case that a rule needs to be invoked for subclasses of an (abstract) super type, we were able to express

35 ICSOFT-PT 2016 - 11th International Conference on Software Paradigm Trends

the same behavior within a single rule in the TGTS. (which should provide a more concise and compact Listings 4 and 5 show that complex assignments solution) required almost three times the number of can easily be moved to operations, which may be lines of code than using a modern imperative lan- reused from various places – a feature which is com- guage with lambda expressions. mon in object-oriented programming languages but One note on testing our implementation: Another which is lacking in (declarative) model transforma- benefit of the approach presented in this paper is tion languages. Please note, that QVT-R allows to the fact that each Xtend specification can easily be specify queries which could also be reused in arbi- tested automatically with the help of JUnit test cases. trary places but only without side-effects, while non- Moreover, even those test cases may be written us- top level relations can also be called from other rules ing Xtend. We supplied an extensive set of test cases and may contain side-effects. for each rule and tested model modifications for both The downside of the presented approach is that transformation directions (creation, update and dele- both transformation directions have to be specified tion of respective model elements). Being able to explicitly. Hence, whenever the metamodels are run automated tests is a considerable improvement changed in a way that requires adapting the transfor- over our previous TGG (Buchmann and Westfechtel, mation rules, these changes have to be performed at 2013) and QVT-R (Greiner et al., 2016) implemen- different places inside the transformation script. It tations, where all of those tests had to be carried out is up to the software engineer to ensure a consistent manually in a tedious and time consuming procedure. modification throughout the script. Moreover, allow- Apart from this use case, our correspondence ing only 1:1 correspondences affords to keep the 2- model is generic enough to be reused with other bidi- n other elements manually consistent in incremental rectional model transformations. Having correspon- transformations which results in an imminent danger dence elements that map one element of a source to of introducing inconsistencies by mistake. one element of a target model is the most natural map- The alternative of using 1:n correspondences in ping present in transformations. Non-bijective map- the trace model would require to keep track which pings always need further consideration and are more additional elements are mapped and stored at which likely to be established manually since these trans- position. This complicates the rules significantly and formations are hard to automate. For traceability and requires users to know the mapping assumptions. If, managing the transformation incrementally the result- for instance, a class was mapped to a class, a Compi- ing correspondence graph serves as persisted trace in- lationUnit, and a ParameterizedType, this would result formation. As a consequence, one could think about in a collection of three different Java elements that writing a DSL on top of Xtend allowing to specify must be treated separately. Thus, the user must be transformation patterns. sure which of the mapped elements is of which type. Another problem of the current approach are ele- ments that have no corresponding partner in the op- 6 RELATED WORK posite model, i.e. "0:1" mappings. In general, these elements cannot be created in advance or at the end Common approaches that are used to transform text of the transformation since they may reference other (e.g. source code) to models are based on parsers for elements that are created during the transformation or the specific text languages. Usually, these approaches they may be referenced by other elements. For in- work on the resulting parse trees and map the tree stance, the collection container in the Java model has items to corresponding model elements. Typical lim- no partner element in the opposite model. Thus, the itations are maintenance problems when the underly- user needs to manually add and update such an ele- ing M2T templates are changed. ment by calling a respective operation when required In (Bork et al., 2008), Bork et al. describe an ap- during the transformation. proach towards model and source code round-trip en- Nevertheless, in a generic base rule the current ap- gineering, which is based on reverse engineering of proach is able to describe the parts dealing with the M2T transformation templates. The idea of this ap- trace links between the model elements and locating proach is to use (customizable) code generation tem- changes. Consequently, the concrete rules only de- plates as a grammar to parse the generated (and later scribe the changes using Xtend’s lambda expressions. modified) code. The benefit of this approach com- In total, it took 1121 lines of Xtend code to specify pared to other approaches using plain Java parsers the transformation rules, compared to 2947 lines of and the resulting parse tree as a source for the code QVT-R code. Hence, for the transformation problem to model transformation is that changes to the tem- in this case study, the usage of a declarative language plates are automatically taken into account during re-

36 Handcrafting a Triple Graph Transformation System to Realize Round-trip Engineering Between UML Class Models and Java Source Code

verse engineering. While the approach described in of object-oriented application frameworks. In con- (Bork et al., 2008) requires considerable implemen- trast to general round-trip engineering approaches, tation effort since a template parser, reasoner and to- the approach presented in (Antkiewicz and Czarnecki, ken creator have to be implemented, our approach just 2006) does not have to deal with non-isomorphic required the specification of respective Xtend rules mappings between the artifacts, as the problem do- that relate two elements of the respective metamod- main is much smaller and only code for a specific els. Since MoDisco is able to parse source code which framework is generated by the code generators of the even contains syntax or compile errors into a corre- FSML. The synchronization of the involved imple- sponding Java model, our approach is also indepen- mentation model is based on a comparison inspired dent of the style of the generated code and it also does by CVS and reconciliation. In a last step, conflict res- not depend on a (usually) fine grained parse tree. Fur- olution has to be carried out interactively by the user. thermore, Javadoc tags can be used to add additional Hettel et al. (Hettel et al., 2009) propose an ap- meta-information to the code. While the approach proach towards model round-trip engineering based presented in (Bork et al., 2008) is able to round-trip on abductive logic programming. In particular, this engineer only code that has been generated with the approach does not place restrictions such as injective corresponding templates, our approach is able to han- behavior on the underlying transformations. A ref- dle any code which complies to Java language speci- erence implementation is given which can be used fication version 5. In addition, the approach by Bork to reverse unidirectional transformations based on the et al. requires bijective reversible templates. E.g. the Tefkat language. It is a general approach, which could approach will fail if an attribute name in a class con- also be applied to other model transformation lan- tains the class name. guages, like QVT. However, since the source transfor- Angyal et al. present in (Angyal et al., 2008) an mation does not necessarily need to be injective, am- approach for model and code round-trip engineering biguities have to be solved when reversing the trans- based on differencing and merging of abstract syntax formation. At the end, the “best” solution has to be trees (AST). In this approach, the AST is regarded picked by the user or it has to be determined using to be the platform-specific model (PSM) according to some kind of heuristics. the taxonomy of models in MDA (Mellor et al., 2004). Nevertheless, in this approach the AST model has a very low level of abstraction because it exactly rep- 7 CONCLUSION AND FUTURE resents the code. Contrastingly, the discovered Java WORK model which is used in our approach is on a higher level of abstraction. The round-trip engineering ap- In this paper, we presented a solution for incremen- proach comprises two different round-trip tasks: one tal round-trip engineering between UML class mod- between PIM and PSM and one between PSM and els and Java source code, using a hand-crafted triple code. The approach tries to prevent information loss graph transformation system (TGTS) written with the during round-trip engineering by using a so called Xtend programming language. trace model which is used to synchronize the PIM and While nowadays tool support for model trans- the PSM (the AST). Furthermore, the AST and the formation mostly covers unidirectional batch trans- source code are updated using a fine grained bidirec- formation, this use case demands for a bidirectional tional incremental merge based on three-way differ- transformation, which works in an incremental man- encing. In our approach, information loss is prevented ner. However, our previous research revealed that by using Javadoc tags as annotations. In case model there is no adequate tool support to solve this prob- and code are changed simultaneously and the changes lem. are contradicting, one transformation direction has to To this end, we chose to code both transformation be chosen, which causes that some changes might get directions explicitly using the Xtend language. We lost. exploited lambda expressions to describe the graph There are also approaches that are dedicated patterns of our TGTS in a declarative way and made to model-to-model round-trip engineering. This use of the traditional style task involves synchronizing models and keeping whenever it was appropriate. them consistent. Antkiewicz and Czarnecki pro- Future work comprises a quantitative and qualita- pose an approach towards round-trip engineering tive evaluation of our three implemented solutions for for framework-specific modeling languages (FSML) incremental round-trip engineering. (Antkiewicz and Czarnecki, 2006). FSMLs are a special category of DSLs which are defined on top

37 ICSOFT-PT 2016 - 11th International Conference on Software Paradigm Trends

REFERENCES Jouault, F., Allilaire, F., Bézivin, J., and Kurtev, I. (2008). Atl: A model transformation tool. Science of Com- Angyal, L., Lengyel, L., and Charaf, H. (2008). A synchro- puter Programming, 72:31 – 39. Special Issue on Sec- nizing technique for syntactic model-code round-trip ond issue of experimental software and toolkits (EST). engineering. In Proceedings of the 15th International Mellor, S. J., Kendall, S., Uhl, A., and Weise, D. (2004). Conference on the Engineering of Computer Based MDA Distilled. Addison Wesley Longman Publishing Systems (ECBS 2008), pages 463–472. Co., Inc., Redwood City, CA, USA. Antkiewicz, M. and Czarnecki, K. (2006). Framework- OMG (2015a). Meta Object Facility (MOF) 2.0 specific modeling languages with round-trip engineer- Query/View/Transformation Specification. Needham, ing. In Proceedings of the 9th International Confer- MA, formal/2015-02-01 edition. ence on Model Driven Engineering Languages and OMG (2015b). Unified Modeling Language (UML). Object Systems (MoDELS 2006), LNCS 4199, pages 692– Management Group, Needham, MA, formal/15-03-01 706, Genova, Italy. edition. Bork, M., Geiger, L., Schneider, C., and Zündorf, A. (2008). Rozenberg, G., editor (1997). Handbook on Graph Gram- Towards roundtrip engineering - a template-based re- mars and Computing by Graph Transformations, vol- verse engineering approach. In Schieferdecker, I. ume 1: Foundations. Singapore. and Hartman, A., editors, ECMDA-FA, volume 5095 Schürr, A. (1994). Specification of Graph Translators with of Lecture Notes in Computer Science, pages 33–47. Triple Graph Grammars. In Proceedings of the 20th Springer. International Workshop on Graph-Theoretic Concepts Bruneliere, H., Cabot, J., Jouault, F., and Madiot, F. (2010). in Computer Science (WG 1994), volume 903 of MoDisco: a generic and extensible framework for LNCS 903, pages 151–163, Herrsching, Germany. model driven reverse engineering. In Proceedings Steinberg, D., Budinsky, F., Paternostro, M., and Merks, of the IEEE/ACM international conference on Auto- E. (2009). EMF Eclipse Modeling Framework. The mated software engineering, ASE ’10, pages 173– Eclipse Series. Boston, MA, 2nd edition. 174, New York, NY, USA. ACM. Stevens, P. (2007). Bidirectional Model Transformations Buchmann, T., Dotor, A., and Westfechtel, B. (2008). Triple in QVT: Semantic Issues and Open Questions. In graph grammars or triple graph transformation sys- Proceedings of the 10th International Conference on tems? In Chaudron, M. R. V., editor, Models in Soft- Model Driven Engineering Languages and Systems ware Engineering, Workshops and Symposia at MOD- (MoDELS 2007), LNCS 4735, pages 1–15, Nashville, ELS 2008, Toulouse, France, September 28 - October USA. 3, 2008. Reports and Revised Selected Papers, volume Westfechtel, B. (2016). A Case Study for a Bidirectional 5421 of Lecture Notes in Computer Science, pages Transformation Between Heterogeneous Metamodels 138–150. Springer. in QVT Relations. In Maciaszek, L. A. and Filipe, Buchmann, T. and Westfechtel, B. (2013). Towards in- J., editors, Evaluation of Novel Approaches to Soft- cremental round-trip engineering using model trans- ware Engineering, volume 599 of Communications formations. In Demirors, O. and Turetken, O., edi- in Computer and Information Science (CCIS), chap- tors, Proceedings of the 39th Euromicro Conference ter 8, pages 141–161. Springer International Publish- on Software Engineering and Advanced Applications ing. Revised Selected Papers from ENASE 2015. (SEAA 2013), pages 130–133. IEEE Conference Pub- lishing Service. Czarnecki, K. and Helsen, S. (2006). Feature-based sur- vey of model transformation approaches. IBM Sys- tems Journal, 45(3):621–645. Ehrig, H., Engels, G., Kreowski, H.-J., and Rozenberg, G., editors (1999). Handbook on Graph Grammars and Computing by Graph Transformation, volume 2: Ap- plications, Languages, and Tools. Singapore. Greiner, S., Buchmann, T., and Westfechtel, B. (2016). Bidirectional Transformations with QVT-R: A Case Study in Round-trip Engineering UML Class Models and Java Source Code. In Proceedings of the 4th In- ternational Conference on Model-Driven Engineering and Software Development (MODELSWARD 2016). accepted for publication. Hettel, T., Lawley, M., and Raymond, K. (2009). To- wards model round-trip engineering: An abductive approach. In Proceedings of the 2nd International Conference on Theory and Practice of Model Trans- formations (ICMT 2009), LNCS 5563, pages 100– 115, Zurich, Switzerland.

38