scieee AI-readable full text Open interactive document viewer

Lightweight trustworthy high-level software design

Liu, Chong

Abstract

A modelação e análise formal de software é essencial para obter um projecto de software confiável antes da implementação. O Alloy, uma linguagem de especificação com uma ferramenta de análise automática, é uma abordagem popular para esta tarefa. Frequentemente, um projecto de software inclui muitas variantes com grande partilha de código. Em vez de considerar cada variante individualmente, o desenvolvimento de software orientado à funcionalidade procura desenvolver em conjunto toda a família de variantes, também designada por linha de produtos de software (LPS). Aspectos em comum são organizados em funcionalidades, implementando cada variante um sub-conjunto das mesmas. Existem duas abordagens típicas para implementação de uma LPS: abordagens composicionais, onde cada funcionalidade é implementada num módulo distinto, e abordagens anotativas, onde o código específico de cada funcionalidade é assinalado com uma anotação. A primeira é melhor para adicionar grandes blocos de código a uma funcionalidade, por exemplo uma nova classe, enquanto que a segunda suporta melhor pequenas extensões, tais como adicionar uma instrução a um método. O primeiro objectivo desta tese é propor uma extensão anotativa para o Alloy, para suportar a concepção formal de software orientada à funcionalidade. A ideia é suportar pequenas extensões a um modelo mas sem os problemas de compreensão que derivam das típicas anotações #ifdef usadas na implementação de uma LPS. Para tal, permitimos cores de fundo para identificar os fragmentos associados com cada funcionalidade, dando origem à linguagem Colorful Alloy. Também propusemos uma técnica de análise amalgamada para verificar toda uma família de variantes de uma só vez. O segundo objectivo é propor uma técnica para migração de um conjunto de variantes, possivelmente desenvolvidos com a abordagem clone-and-own, para um único modelo em Colorful Alloy. Para tal, propusemos um catálogo de refatorações e mostramos como podem ser usadas para iterativamente migrar modelos Alloy clonados para um único modelo “colorido”. Também desenvolvemos uma técnica de migração que automatiza todo este processo. Este trabalho foi avaliado com recurso a vários casos de estudo de LPSs, desenvolvidos quer pro-activamente com Colorful Alloy, quer com a abordagem clone-and-own com Alloy normal. Esta avaliação mostrou que a técnica de análise amalgamada pode aumentar consideravelmente a eficiência da verificação de uma família de variantes, quando comparada com a análise variante a variante. Também mostrou que a técnica de migração (incluindo a completamente automática) pode reduzir significativamente a quantidade de código clonado, o que em princípio permitirá simplificar a compreensão de um projecto de uma LPS.

Full text

This work is financed by the ERDF – European Regional Development Fund through the Operational Programme for Competitiveness and Internationalisation - COMPETE 2020 Programme and by National Funds through the Portuguese funding agency, FCT - Fundação para a Ciência e a Tecnologia, within project POCI-01-0145-FEDER-016826. Lightweight Trustworthy High-Level Software Design Liu Chong UMinho | 2022 Departamento de Informática Liu Chong Lightweight Trustworthy High-Level Software Design Programa de Doutoramento em Informática das Universidades do Minho, de Aveiro e do Porto January 2022 Universidade do Minho Escola de Engenharia Departamento de Informática Liu Chong Lightweight Trustworthy High-Level Software Design Tese de Doutoramento Programa de Doutoramento em Informática das Universidades do Minho, de Aveiro e do Porto Trabalho realizado sob a orientação do Professor Doutor Manuel Alcino Cunha e do Professor Doutor Nuno Moreira Macedo January 2022 DIREITOS DE AUTOR E CONDIÇÕES DE UTILIZAÇÃO DO TRABALHO POR TERCEIROS Este é um trabalho académico que pode ser utilizado por terceiros desde que respeitadas as regras e boas práticas internacionalmente aceites, no que concerne aos direitos de autor e direitos conexos. Assim, o presente trabalho pode ser utilizado nos termos previstos na licença abaixo indicada. Caso o utilizador necessite de permissão para poder fazer um uso do trabalho em condições não previstas no licenciamento indicado, deverá contactar o autor, através do RepositóriUM da Universidade do Minho. Licença concedida aos utilizadores deste trabalho Atribuição CC BY https://creativecommons.org/licenses/by/4.0/ i ACKNOWLEDGEMENTS I still remember when I walked out of Professor Alcino’s office for the first time five years ago, at the beginning of my five-year doctoral journey. I am very grateful to Professor Alcino for choosing me as his PhD student and introducing me to the wonders of scientific research. These five years have been the most unforgettable and happiest time for me. This experience will be one of the most memorable moments of my life. Foremost, I would like to express my sincere gratitude to my supervisors Professor Alcino and Professor Nuno for the continuous support of my studies and research. I am sure that without your patience, enthusiasm, and immense knowledge, this journey wouldn’t be possible. I could not have imagined having better advisors. Besides my supervisors, I would like to thank Professor Alexandre Santos, Professor Joaquim Macedo, and Professor António Duarte Costa, who gave me a lot of help during my studies at the University of Minho. I thank my Master’s supervisor, Professor Liu Dayou – without his help I would never have the opportunity to study in Portugal as an exchange student and would never choose to pursue my PhD in Portugal. I am very grateful to my country. During the COVID-19 epidemic, I received masks, disinfectants, and medicine from the embassy many times, which made me feel the warmth of home outside. I would like to thank my friends and my colleagues in Lab Room 207 who helped and colored my life in Portugal. Although we hadn’t seen each other for a long time since the outbreak, we spent a lot of happy times together. Finally, I would like to express my heartfelt thanks to all the professors who participated in the thesis evaluation and defense. ii STATEMENT OF INTEGRITY I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. iii RESUMO A modelação e análise formal de software é essencial para obter um projecto de software confiável antes da implementação. O Alloy, uma linguagem de especificação com uma ferramenta de análise automática, é uma abordagem popular para esta tarefa. Frequentemente, um projecto de software inclui muitas variantes com grande partilha de código. Em vez de considerar cada variante individualmente, o desenvolvimento de software orientado à funcionalidade procura desenvolver em conjunto toda a família de variantes, também designada por linha de produtos de software (LPS). Aspectos em comum são organizados em funcionalidades , implementando cada variante um sub-conjunto das mesmas. Existem duas abordagens típicas para implementação de uma LPS: abordagens composicionais, onde cada funcionalidade é implementada num módulo distinto, e abordagens anotativas, onde o código específico de cada funcionalidade é assinalado com uma anotação. A primeira é melhor para adicionar grandes blocos de código a uma funcionalidade, por exemplo uma nova classe, enquanto que a segunda suporta melhor pequenas extensões, tais como adicionar uma instrução a um método. O primeiro objectivo desta tese é propor uma extensão anotativa para o Alloy, para suportar a concepção formal de software orientada à funcionalidade . A ideia é suportar pequenas extensões a um modelo mas sem os problemas de compreensão que derivam das típicas anotações #ifdef usadas na implementação de uma LPS. Para tal, permitimos cores de fundo para identificar os fragmentos associados com cada funcionalidade, dando origem à linguagem Colorful Alloy. Também propusemos uma técnica de análise amalgamada para verificar toda uma família de variantes de uma só vez. O segundo objectivo é propor uma técnica para migração de um conjunto de variantes, possivelmente desenvolvidos com a abordagem clone-and-own , para um único modelo em Colorful Alloy. Para tal, propusemos um catálogo de refatorações e mostramos como podem ser usadas para iterativamente migrar modelos Alloy clonados para um único modelo “colorido”. Também desenvolvemos uma técnica de migração que automatiza todo este processo. Este trabalho foi avaliado com recurso a vários casos de estudo de LPSs, desenvolvidos quer pro-activamente com Colorful Alloy, quer com a abordagem clone-and-own com Alloy normal. Esta avaliação mostrou que a técnica de análise amalgamada pode aumentar consideravelmente a eficiência da verificação de uma família de variantes, quando comparada com a análise variante a variante. Também mostrou que a técnica de migração (incluindo a completamente automática) pode reduzir significativamente a quantidade de código clonado, o que em princípio permitirá simplificar a compreensão de um projecto de uma LPS. P a l a v r a s - c h a v e Concepção formal de software, Alloy, linhas de produtos de software, variabilidade, refatoração, clone-and-own. iv ABSTRACT Formal modeling and analysis is essential to achieve a trustworthy software design prior to its implementation. Alloy, a specification language with a lightweight model finder, is a popular approach to accomplish this task. Frequently, a software design encompasses many variants with a large commonality between them. Instead of considering each variant individually, feature-oriented software development tackles at once the whole family of variants, also known as a software product line (SPL). Commonalities are organized as features , with each variant implementing a particular set of features. SPL implementation techniques mainly fall into two groups: compositional approaches, which implement features in distinct modules, and annotative approaches, that wrap feature-specific code with annotations. The former is well suited to coarse-grained feature extensions, such as adding a new class, while the latter is better for fine-grained extensions, like adding a statement in a method. The first goal of this thesis is to propose an annotative extension to Alloy, to support formal featureoriented software design . Our aim was to easily support fine-grained extensions to a model, but without the comprehension obstacles of the typical #ifdef annotations used in SPL implementation. To that end, we added support for background colors to identify the fragments associated with each feature, ending up with the Colorful Alloy language. We also proposed an amalgamated analysis technique that can verify a full family of design variants at once. Our second goal was to propose a technique for migrating a collection of variants, possibly developed with the clone-and-own approach, into a single managed Colorful Alloy design. To achieve this, we proposed a catalog of refactorings and showed how they can be used to iteratively merge cloned Alloy models into a colorful model. We also proposed a one-step merging strategy that automates this technique. We evaluated our work with several SPL case studies that were either developed proactively directly with Colorful Alloy or using clone-and-own using normal Alloy. The evaluation showed that the amalgamated analysis strategy can considerably speed-up the verification of a full family of design variants, when compared to the iterative and separate analysis of each variant. It also showed that the clone merging technique (including the automatic one) can substantially reduce the amount of cloned code, which in principle simplifies the understanding of an SPL design. K e y w o r d s Formal software design, Alloy, software product lines, variability, refactoring, clone-and- own. v CONTENTS 1 Introduction 1 2 Formal Software Design with Alloy 6 2.1 Alloy by Example 6 2.1.1 E-commerce Example 7 2.1.2 Signature and Field Declaration 8 2.1.3 Type System 9 2.1.4 Exploring Scenarios 11 2.1.5 Specifying Constraints 13 2.1.6 Verifying Assertions 15 2.1.7 Modularization 17 2.2 Formal Presentation of the Language 21 2.2.1 Formal Syntax 21 2.2.2 Formal Semantics 24 2.2.3 Type Inference 27 2.2.4 Analysis 29 2.3 Refactoring Alloy Models 32 2.3.1 Laws for Signatures 33 2.3.2 Laws for Fields 34 2.3.3 Laws for Formulas 36 2.4 Alloy Extensions 37 3 Feature-oriented Software Design 44 3.1 Feature Modeling 45 3.1.1 Specifying Feature Models 45 3.1.2 Analyzing Feature Models 49 3.2 Modeling in Feature-oriented Design 55 vi LIST OF TABLES Table 1 A bestiary of binary relations. 23 Table 2 Rules for translating FMs to propositional formulas. 52 Table 3 Evaluation results. 163 Table 4 Evaluation of the amalgamated and iterative approaches for the proactive examples. 164 Table 5 Evaluation of the amalgamated and iterative approaches for the extractive examples. 165 xiii 1 INTRODUCTION Nowadays, computers have become increasingly powerful and essential in our life. Therefore, rigorous software design techniques for dependable systems become an imperative requirement in the software developing process. A simple straightforward approach to develop a new system is to write the requirements (usually in natural language) that specify the desired behavior of the system, and then attempt to implement it directly into code by the programmer. Finally, the functionality of the system can be tested during and after the coding to ensure that the generated program meets the specification and is free of errors or bugs. However, this process is not easy to achieve, especially for some safety-critical systems. First of all, a complete and unambiguous specification is difficult to have; second, programmers must fully and correctly understand the content of the requirements and handle all possible ambiguities; third, the testing must be exhaustive, that is, all possible states of the system must be rigorously tested. However, for some safety-critical systems such as medical devices or aerospace systems, we have to fully ensure its correctness, otherwise their operation may result in severe consequences. Furthermore, testing some large and complex systems can be time-consuming, and due to the size of the system, exhaustive testing may not even be possible in practice. Therefore, in addition to exhaustive testing, techniques based on mathematical analysis should be used to ensure the correct implementation of requirements. In particular, formal software development methods, including specification, verification, and validation, are mathematical techniques to identify errors and discrepancies in the early phases of the software development process. Specifically, formal methods allow us to formally check that an implementation (or a formal model of an implementation) of a system (or parts of a system) meets the expected requirements (specified in some formal language). Among the myriad of the proposed formal methods, lightweight ones – which rely on automatic analyses to verify (often partial) specifications – have become increasingly popular, since they bring the power of fast verification and validation to most software developers. That is the case of model checkers like NuSMV (Cimatti et al.,2000) or SPIN (Holzmann,1997), for verifying temporal logic properties of (behavioral) designs (modeled as transition systems), or model finders like Alloy (Jackson, 1 1. Introduction 2012), more geared towards verifying first-order properties of structural designs specified at a high level of abstraction (using simple mathematical concepts like sets and relations). Given its popularity, lightweight analysis, and suitability for high-level design, Alloy will precisely be the focus of this thesis. In order to suit the wide variety of (different) customer requirements, many systems are actually developed as a family of systems, many times with only slight differences in the implementation between different family members. Using conventional formal methods, each family member of those systems would be designed and analyzed individually. The engineers conducting the design have to perform tedious and repeated work, especially when a new functionality is added that affects all family members. Therefore, such classic single variant formal methods are not suitable for the development of software families. In this context, techniques for designing, analyzing, and implementing a full family of systems at once are mandatory. A common paradigm that is adopted when developing such large-scale software systems is feature-oriented software development (Apel and Kästner,2009), a paradigm that organizes software around the key concept of feature , a unit of functionality that satisfies some of the requirements and that originates a configuration option. If the implementation is properly decomposed, it is possible to deliver many variants of the system just by selecting the desired features. The set of all those variants is usually called a software product line (SPL). Ideally, the design of SPLs should already explicitly take features into account, and formal methods should be adapted to support such feature-oriented design (Apel et al., 2010). In fact, even when developing a single software product, it is still convenient to explicitly consider features and multi-variant analysis during design to support the exploration of different implementation alternatives. In feature-oriented design, the set of all product line features together with their relationships should be specified in a feature model, and the system itself should be modeled in feature-aware extensions of common modelling formalisms such as transition systems. Having proper language and tool support for feature-oriented design is a key enabling technology for developing a wide variety of software systems of high quality in a fast, consistent, effective, and comprehensive way. The key for effective variability modeling is to design a system family exploiting its commonalities and efficiently express and manage its variability. Most general-purpose programming and modeling languages can already somehow support feature-oriented design with their standard constructs in an ad-hoc fashion, a technique that is often cumbersome and error-prone for realistic SPLs. In addition to these ad-hoc techniques, proper feature-oriented programming languages fall into one of two categories: compositional approaches, which implement features as distinct modules and have some sort of module composition technique to generate a specific variant; and annotative approaches, which implement features with explicit (or sometimes implicit) annotations in the source code, that dictate which fragments will be present in 2 1. Introduction a specific variant. The former are well suited to support coarse-grained feature extensions, for example adding a complete new class to implement a particular feature, but are not good for fine-grained extensions, for example adding a sentence to a method or changing the expression in a conditional, to affect the way a code fragment works with different features (Kästner et al.,2008). Annotative approaches are much better suited for such fine-grained variability. Unfortunately, explicit support for feature-oriented design in formal methods, providing a uniform formalism for feature, architectural and behavioral modeling, as advocated for SPL engineering (Schaefer and Hähnle,2011), is still scarce. Support for features in model checking has been proposed, namely a compositional approach for the SMV modeling language of NuSMV (Plath and Ryan,2001;Classen et al., 2014) and an annotative approach for the Promela modeling language of SPIN (Cordy et al.,2013). A compositional approach has also been proposed to explicit support features in Alloy (Apel et al.,2010). However, modeling and specifying in Alloy is usually done at high levels of abstraction, and adding a feature can require only minimal and very precise changes, for instance, adding one new relation to the model or changing part of the specification of a desired property, and such compositional approach is not well suited for these fine-grained extensions. This thesis addresses precisely this problem. As such, the first main goal of our work is to propose an annotative approach to add explicit support for features to Alloy and its Analyzer. This involves developing a new language extension as well as adapting the existing or proposing novel analysis techniques. A classic annotative approach for source code is the use of #ifdef and #endif C/C++ compiler preprocessor directives to delimit the code fragments that implement a specific feature. Unfortunately, such annotation style obfuscates the code and makes it hard to understand and maintain, leading to the well-known #ifdef hell (Feigenspan et al.,2013). To alleviate this problem, while retaining the advantages of annotative approaches, Kästner et al. (2008) proposed to annotate code fragments associated with different features with different background colors, which was later shown to clearly improve SPL code comprehension and be favored by developers (Feigenspan et al.,2013). Inspired by this colorful approach, we developed a colorful extension to Alloy and its Analyzer, denoted Colorful Alloy , that allows users to annotate model and specification fragments belong to distinct features with different background colors, and run analysis commands to verify either a particular variant, or several variants at once. To the best of our knowledge, this is the first color-based annotative approach formal method for feature-oriented design focusing on structural requirements. Evolution is an important software development activity, as the original design usually does not comply with new requirements. One approach widely used by software developers when developing new software 3 1. Introduction variants is the clone-and-own approach , where new variants are implemented by copying code from existing variants and then adapting it to fit the new requirements. Since the cost to maintain the clones and synchronize changes in replicas increases rapidly with the number of clones, developers may benefit from migrating (by merging) such variants into a single proper SPL implementation, where the common parts of the clones are factored out and implemented only once. The resulting code provides significant benefits for management and requires less effort in subsequent maintenance and design evolutions. Many techniques have been proposed to migrate product variants into managed SPLs, as detailed in the survey conducted by Assunção et al. (2017). However, most of these techniques work at the code level, and only a few have been proposed specifically for design models. The second main goal of our work is to propose a technique for migrating legacy Alloy models developed with a clone-and-own approach into a single SPL Colorful Alloy model. We achieve this by a step-by-step automated refactoring technique. A refactoring is a kind of transformation that changes the structure of the source code while preserving its external behavior. However, classical refactoring is not well-suited for feature-oriented development, since both the set of possible variants and the behavior of each variant must be preserved (Schulze et al.,2012), and refactoring laws are typically too coarse-grained to be applied in this context, focusing on constructs such as entire functions or classes. In this thesis, we propose a catalog of variability-aware refactoring laws for Colorful Alloy, covering all model constructs – from structural declarations to axioms and assertions – and granularity levels – from whole paragraphs to formulas and expressions. Then, we show how these refactorings can be used to migrate a set of legacy Alloy clones into a colorful SPL using an approach similar to the one previously proposed by Fenske et al. (2017) for Java code. To simplify this process we also proposed a one-step fully automatic merging strategy that composes a sequence of refactorings. The organization of this thesis is as follows. Chapter 2 gives an overview of formal software design with Alloy. It starts by showing an application of the Alloy language in the design of a catalog structure of an e-commerce site. Then it gives a formal presentation of the language and, finally, presents some work on Alloy refactoring and extensions. Chapter 3 presents a literature review on feature-oriented software design, including an overview about feature modeling, a collection of approaches that can be used to model and analyse feature-oriented systems, and some approaches for migrating clones into an SPL. Chapter 4 formally presents the Colorful Alloy language, including its syntax, typing rules, and semantics. It also presents the multi-variant analysis technique developed for this new language extension. 4 1. Introduction Chapter 5 presents a catalog of variability-aware refactoring laws and shows how they can be used to migrate a set of cloned Alloy variants into a Colorful Alloy model. Chapter 6 presents the implementation and evaluation of this work. We first present a description of the implementation of Colorful Alloy language, analysis, as well as the catalog of refactoring rules in the so-called Colorful Analyzer. The evaluation includes a qualitative analysis where we show how Colorful Alloy was used to develop several case-studies, and a quantitative analysis focused on evaluating the effectiveness of the proposed automatic analysis and clone migration techniques. Chapter 7 summarizes the research in this thesis and identifies possible directions for future work. Appendix A presents the Colorful Alloy models of the case studies used in the evaluation. The work in this thesis originated two publications: the first (Liu et al.,2019) was accepted at the 5th International Symposium on Dependable Software Engineering Theories, Tools and Applications (SETTA), and describes a preliminary version of the Colorful Alloy language and analysis technique that are presented in Chapter 4; the second (Liu et al.,2020) was accepted at the 23rd Brazilian Symposium on Formal Methods (SBMF) and describes a preliminary version of the catalog of variability-aware refactoring laws and the clone migration technique presented in Chapter 5. The latter paper won the 2nd place for best paper award at the symposium and was invited to be submitted as a journal version to a special issue of Science of Computer Programming (Elsevier). We have recently submitted this paper, which presents the final version of the Colorful Alloy language and of the clone migration technique. 5 2 FORMAL SOFTWARE DESIGN WITH ALLOY A good software design is key to achieve a high-quality system that meets all the expected requirements. In particular, it is very important to have clear specifications for the structure and behavior of a software system prior to its implementation. Among the various approaches proposed currently to help software developers reason about a software design, those that combine simple but formal specification languages with automatic analysis tools, that allow users to quickly explore different design alternatives and verify model assumptions, have more potential to be widely adopted. Alloy, which consists of a lightweight declarative modeling language and an automatic analysis tool, the Alloy Analyzer, is a prime example of such formal approaches and is becoming increasingly popular for validating software designs in the early stages of development. In this chapter, we present the Alloy language and its Analyzer in detail, as well as how to use them for software design. Specifically, Section 2.1 illustrates the application of Alloy in the design of the catalog structure of a simple e-commerce system, including how to model the catalogue structure, how to specify its constraints, how to use the Analyzer to simulate different scenarios and check expected properties, as well as how to structure an Alloy model for reuse and better understanding. Section 2.2 gives a formal presentation of the Alloy language, including its syntax, core semantics, type inference mechanism, as well as the analysis procedure implemented in its Analyzer. Section 2.3 presents some work on refactoring Alloy specifications and, finally, Section 2.4 briefly presents some Alloy extensions and variants that have been developed to address some of its shortcomings. 2.1 Alloy by Example Alloy is a lightweight declarative modeling language that provides a simple syntax to introduce sets and relations, as well as a powerful relational logic syntax to express constraints. A model written in Alloy can be automatically analyzed by the Alloy Analyzer, and the obtained results are displayed through a user-friendly 6 2.1. Alloy by Example visualizer. In this section, we will step through the use of the Alloy language as well as its Analyzer by an example of an e-commerce platform, namely by modeling the catalog structure of such a system. 2.1.1 E-commerce Example Nowadays, with the rapid development of computer network and communication technology, people can not only conduct face-to-face traditional transactions on tangible goods, but also through websites offering a wide range of products, supported by an advanced logistics and distribution system, and a secure payment system to complete transactions. This increasingly popular way of using the Internet to buy and sell goods or services is called e-commerce and it has begun to become an important part of everyday life. There are many types of e-commerce systems, all of which provide a web interface, generally a HTML page, which displays the catalog of products offered by the company. Buyers can view a company’s entire product offer through this catalog. The main purpose of the catalog is to advertise the products and thus attract the attention of the customer, so each product is typically illustrated by a set of images and catalogues are illustrated by thumbnails . An e-commerce platform can implement several variants of this basic catalogue structure, to support different needs from different e-commerce sites. For example, some sites organize products in categories listing together similar products, in which case, a catalog is organized as a set of categories, each containing some products. Also, in some sites categories may be organized in a hierarchy , and in some each product may belong to more than one category. This means that an e-commerce platform can be designed as an SPL, where each variant supports a different set of features. In this example a possible feature is having categories or not, and when this feature is present, two additional optional features are available: hierarchical categories and multiple categories per product. In this chapter we will focus on the design of a single variant of this system, the one having all the aforementioned features. Later in this thesis, we will see how the proposed Alloy extension allows us to develop all the five variants in a single model. In the following sections, we will detail how to model this simple example from scratch using the Alloy language, and how to analyze it with the Alloy Analyzer. This example is an adaptation of a similar one proposed by Czarnecki and Pietroszek (2006) also in the context of SPL design. 7 2.1. Alloy by Example 2.1.2 Signature and Field Declaration An Alloy model typically declares some signatures , each with an arbitrary number of field declarations. Signatures introduce sets of elements (also known as atoms in Alloy) and fields capture the relations between them. Everything in Alloy can be viewed as a relation , which is a set of tuples that relates atoms to each other. The size of a relation is the number of tuples it contains and the arity of a relation is the length of its tuples. Note that all tuples of a relation must have the same length. Relations with arity one, two, three are called unary, binary, and ternary, respectively. Those with an arity greater than two are called multi-relations. A set in Alloy is just a unary relation. In particular, signatures are unary relations. A signature is declared with the keyword sig followed by a user-defined name and a body enclosed in braces. For example, the following code fragment introduces four signatures, which capture the main concepts of an e-commerce framework, namely the catalogs and the respective categories, the products provided by the company, and the images illustrating these products. sig Catalog {} sig Category {} sig Product {} sig Image {} Each signature declaration can include an (optional) multiplicity constraint to limit the number of atoms in the respective set. For example, we could restrict Product to be non-empty to capture the fact that an e-commerce site must have some products for sale. some sig Product {} The some qualifier before the sig keyword states that signature Product has at least one atom. In addition to some, the lone or one qualifiers can also be used in signature declarations, indicating that at most one or exactly one atom must be present in the respective set. A signature declaration can also introduce a number of fields separated by commas, each field relating the atoms of the enclosing signature with other atoms in the universe of elements. For instance, to declare fields to relate products with the respective images and catalogs, the declaration of Product could be changed as follows. sig Product { images: set Image, category: some Category } 8 2.1. Alloy by Example This declaration now introduces two binary relations, images and category that, respectively, associate each product with its set of images and categories. The set multiplicity imposed on images means that images relates each Product to any number of atoms from Image (possibly zero). The some quantifier imposed on category means that category relates each Product to at least one Category. To capture the relation between catalogues and their thumbnails, and the hierarchy between categories, we introduce fields thumbnails and inside in the declarations of Catalog and Category , respectively. sig Catalog { thumbnails: set Image } sig Category{ inside: one Catalog+Category } Notice that inside relates each category with either one category or a catalog, to capture the fact that a category can be inside a catalog or inside another category. In this field declaration, + denotes set union, and is one example of the relational logic operators that will be introduced in Section 2.1.5 for specifying constraints on our model. 2.1.3 Type System The image of a product may have a variety of formats, such as JPG or PNG. Alloy’s type system allows users to specify a hierarchy between signatures. Similarly to other languages, a signature can be introduced as an extension of another signature (declared with an extends keyword). Sibling extension signatures represent disjoint subsets of the parent signature. The parent signature can optionally be marked as abstract (with the keyword abstract ). An abstract signature has no elements other than those that belong to its extensions. For example, to introduce the different image formats in our running example, we could refine the declaration of images as follows. abstract sig Image {} sig Jpg,Png extends Image {} By declaring Image as abstract, each atom of Image must belong to either Jpg or Png. 9 2.1. Alloy by Example Figure 3: An instance of the single-variant e-commerce example considering facts. assert AllCataloged { all p:Product | some (p category ^inside & Catalog) } formulates the expectation that every product is contained inside a catalog. In this assertion, pcategory determines all categories that directly contain product p , while pcategory ^inside determines all categories or catalogs that might contain those (directly or indirectly): by intersecting with Catalog we require that at least one of these is a catalog. An assertion can be verified with a check command, that instructs the analyzer to find a counterexample for the specified property. Similarly to run commands, a scope that limits the number of atoms that can be contained in top-level signatures can be given after the name of the assertion to be verified, with a default of 3 if none is given. By issuing command check AllCataloged for 2 , a counter-example is found, meaning our assertion is not valid. The counterexample is shown in Fig. 4, and depicts a category that is contained in itself. This counterexample exposes a problem with our specification. To fix this problem we can add the fact fact Acyclic { all c:Category | c not in c^inside } 16 2.1. Alloy by Example Figure 4: A counterexample for an expected assertion of the single-variant e-commerce example. that enforces the inside relation to be acyclic. Rerunning the check command gives no counterexample. Notice however that the assertion is being checked considering only a maximum of 2 atoms for each signature. To increase the confidence in the analysis, we can execute the command with a larger scope, for example check AllCataloged for 8 . Now the Analyzer takes more time to finish the verification but still does not find a counterexample. Although we can not conclude that the assertion is valid, as the analysis is always bounded, it gives us some assurance concerning the validity of the desired property. Actually, there is no fundamental difference between running a predicate and checking an assertion in the analysis process. A check command is equivalent to a run command that searches for an instance that satisfies the negation of the constraints in an assertion. 2.1.7 Modularization There may be some expressions that one might want to factor out of constraints, for example to improve readability and reusability when they occur repeatedly in the model. To support that, Alloy allows the declaration of auxiliary predicates and functions. 17 2.1. Alloy by Example A predicate (declared with pred keyword) declares a reusable constraint. Its declaration consists of the name of the predicate, some optional argument declarations inside square brackets, and a block with formulas. A function (declared with fun ) declares a reusable expression. Its declaration consists of the name of the function, some optional argument declarations inside square brackets, a return type after a colon, and a relational expression inside a block. The result of a predicate is a Boolean value, while the result of a function is a value of its return type. Predicates and functions are called by providing an expression for each parameter. In our running example we can declare an auxiliary function that calculates the catalogs of a product as follows. fun catalog [p : Product] : Catalog { pcategory ^inside & Catalog } The function receives a Product as parameter and returns a set of catalogs as a result. Using this function, the assertion AllCataloged could be redefined as follows. assert AllCataloged { all p: Product | some catalog[p] } A typical usage for predicates is to encode different specific scenarios, for example to act as (kind of) unit tests for a model (examples that the user knows to be valid instances). For example, the following predicate Scenario will only be true in instances where at least one product has images. A run command can then directly ask for an instance satisfying the predicate. If the predicate had parameters, the command would automatically instantiate them when searching for a satisfying instance. pred Scenario { some Product images } run Scenario for 2 In addition to predicates and functions, Alloy also has a module system that allows the modularization and reuse of models. A module describes a model that can be used as a submodel, imported by another with an open statement before all paragraphs. There are a number of utility modules, pre-packaged with the Analyzer, that provide common operations. In particular, module util/relations declares common 18 2.1. Alloy by Example operations for computing the domain and the range of a binary relation, as well as a collection of typical constraints one might want to impose on those. For instance, it contains a predicate acyclic that constraints a relation r to be acyclic over a given set. This predicate is declared in the util/relations module as follows. pred acyclic[r: univ→univ, s: set univ] { all x: s | x !in x^r } Here we see that Alloy allows predicates and functions to receive as parameters arbitrary relations and sets, and not just singletons. The constant univ represents the universe of all atoms, and thus a value of type univ→univ is any binary relation. By declaring parameter s to be of type set univ we state that s is any subset of univ , that is, an arbitrary set. Using this module, the fact Acyclic could be expressed as follows. open util/relation fact Acyclic { acyclic[inside,Category] } The util/ordering module is one of the most popular modules pre-packaged with Alloy. This is a parameterized module that can be used to impose a total order over a signature. It provides functions for capturing the total order structure, such as the first element ( first ), the last ( last ), the predecessor relation ( prev ), or the the successor relation ( next ), and predicates for reasoning about its elements, for example to check whether a given element precedes another ( lt ). For example, we could have used this module to impose a total order on a signature that represents the star ratings that customers give to the products. open util/ordering[Rating] some sig Rating {} sig Product { rating : one Rating } The final model of the running example described in this section is shown in Fig. 5. This model has no ratings and includes an extra restriction, requiring all catalogues to display at least one thumbnail of all on sale products contained in them. 19 2.1. Alloy by Example open util/relation sig Product { images: set Image, category: some Category } sig onSale in Product {} sig Image { format: one Format } abstract sig Format {} one sig Jpg, Png extends Format {} sig Catalog { thumbnails: set Image } sig Category { inside: one Catalog+Category } fact Thumbnails { all c:Catalog | c thumbnails in (category (^inside) c) images } fact OnSaleThumbnails { all p:onSale, c:catalog[p] | some pimages & c thumbnails } fact Acyclic { acyclic[inside,Category] } pred Scenario { some Product images } run Scenario for 2 fun catalog [p : Product] : Catalog { pcategory ^inside & Catalog } assert AllCataloged { all p:Product | some catalog[p] } check AllCataloged for 2 Figure 5: Single-variant e-commerce model in Alloy. 20 2.2. Formal Presentation of the Language spec ⋅ ⋅⋅ ⋅=[moduleDecl ]import∗paragraph∗ moduleDecl ⋅ ⋅⋅ ⋅=module qualName [[ name,+]] import ⋅ ⋅⋅ ⋅=open qualName [[ qualName,+]] [ as name ] paragraph ⋅ ⋅⋅ ⋅=sigDecl |factDecl |funDecl |predDecl |assertDecl |cmdDecl sigDecl ⋅ ⋅⋅ ⋅=[abstract ] [ mult ]sig name,+[sigExt ]{ decl,∗}[block ] sigExt ⋅ ⋅⋅ ⋅=extends qualName |in qualName [+ qualName ]∗ mult ⋅ ⋅⋅ ⋅=lone |some |one decl ⋅ ⋅⋅ ⋅=[disj ]name,+:[disj ]expr factDecl ⋅ ⋅⋅ ⋅=fact [name ]block assertDecl ⋅ ⋅⋅ ⋅=assert [name ]block funDecl ⋅ ⋅⋅ ⋅=fun name [[ decl,∗]]: expr block predDecl ⋅ ⋅⋅ ⋅=pred name [[ decl,∗]]block expr ⋅ ⋅⋅ ⋅=const |qualName |@name |this |unOp expr |expr binOp expr |expr arrowOp expr |expr [ expr,∗]|expr [!|not ]compareOp expr |expr (⇒|implies )expr else expr |let letDecl,+blockOrBar |quant decl,+blockOrBar |( expr ) |block |{ decl,+blockOrBar } const ⋅ ⋅⋅ ⋅=none |univ |iden |Int unOp ⋅ ⋅⋅ ⋅=!|not |no |mult |set |#|∼|*|^ binOp ⋅ ⋅⋅ ⋅=|| |or |&& |and |⇔|iff |⇒|implies |+|−|&|++ |<: |:> | arrowOp ⋅ ⋅⋅ ⋅=[mult |set ]→[mult |set ] compareOp ⋅ ⋅⋅ ⋅=in |= letDecl ⋅ ⋅⋅ ⋅=name = expr block ⋅ ⋅⋅ ⋅={ expr∗} blockOrBar ⋅ ⋅⋅ ⋅=block || expr quant ⋅ ⋅⋅ ⋅=all |no |sum |mult cmdDecl ⋅ ⋅⋅ ⋅=[check |run ] [ qualName ] ( qualName |block ) [ typeScopes ] typeScopes ⋅ ⋅⋅ ⋅=for number [but typeScope,+] | for typeScope,+ typeScope ⋅ ⋅⋅ ⋅=[exactly ]number qualName qualName ⋅ ⋅⋅ ⋅=[this/] ( name/ )∗name Figure 6: Concrete syntax of the Alloy language. 2.2 Formal Presentation of the Language Up to this point, we have presented a rough idea of the Alloy language with the simple e-commerce catalog example. In this section we will give a formal presentation of this language in terms of its syntax, semantics, type inference, and analysis. 2.2.1 Formal Syntax The syntax of Alloy is presented in Fig. 6 using standard BNF operators: x∗ means zero or more repetitions of symbol x ; x+ means one or more repetitions of x ; x|y represents a choice of x or y ; [x] denotes an optional x . In addition, x,∗ means zero or more occurrences of the x separated by commas, and x,+ means one or more occurrences of such comma-separated x . The name symbol represents a string identifier. Similar to other programming languages, Alloy identifiers may include the alphabetic characters, numbers (except in the first character), underscores and quotation marks, and are case sensitive. Alloy’s reserved keywords are displayed in bold type. 21 2.2. Formal Presentation of the Language An Alloy model consists of one or more files, one of which contains a main module that either directly or indirectly imports (through the use of open ) modules in the other files. A module consists of an optional module header, possibly some imports, and a set of paragraphs, each either a signature, predicate, or function declaration, a fact, an assertion, or an analysis command. The paragraphs can appear in the module in any order. There is no requirement of declaration before the use. The module header provides the relative path and filename of the model and can only appear in the first line of the model. Similar to the Java language, the path is relative to the directory that the importing module is located. Every model that wishes to use a module must have an explicit import statement following the optional header (and before any signatures, paragraphs, or commands), with a simple open statement. A model can import multiple modules, each of which requires a separate open statement that provides the respective paths and names, instantiation of its parameters (if any), and an optional alias. The order of those import statements does not matter. Each parameter of the imported module must be instantiated by a signature, which can be any declared signature or one of the predefined signatures such as Int (a signature containing all integers) or univ . Each imported module can be referenced in the model either by its alias (if given) or by its module identifier. A module can be imported more than once but must declare aliases if their parameters are instantiated differently. A declaration introduces one or more variables (on the left of the colon) with a bounding expression (on the right side of the colon) constraining their value. Declarations can be used inside signature declarations for declaring fields, to introduce quantified variables, in the definition of sets (or relations) by comprehension, and to declare the arguments of predicates and functions. The keyword disj stands for disjoint, indicating that the variables or declared relations are somehow disjoint (their intersection is empty). For example, sig A {disj r,s : e} declares two disjoint binary relations r and s , while the declaration sig A {r: disj e} declares that the r values of different members of signature A are disjoint. To give an example of a relation defined by comprehension consider the following expression that defines a binary relation that maps each product to the respective JPG images: {p : Product, i : Image | i in pimages and iin Jpg} Expressions can denote either Boolean expressions (formulas) or relational expressions. Formulas are used, for example, in facts, assertions, and predicates. Signature declarations can also be followed by a so called signature fact , an implicitly universally quantified formula that somehow restricts the atoms of that signature. In signature facts, this denotes the implicitly universally quantified variable, any mention of a field declared in the signature is implicitly projected over this , and if one wishes to override this 22 2.2. Formal Presentation of the Language Table 1: A bestiary of binary relations. Property Multiplicity constraint Entire rin A→some B Simple rin A→lone B Surjective rin Asome →B Injective rin Alone →B Function rin A→one B Injection rin Alone →one B Surjection rin Asome →one B Bijection rin Aone →one B behavior and refer to all fields, its name should be preceded by the special marking @. For example, fact Thumbnails could have been declared as a signature fact of Catalog as follows: sig Catalog { thumbnails: set Image } { thumbnails in (category (^inside) this)images } Atomic formulas can either be inclusion ( in ) or equality ( = ) checks between relational expressions of equal arity, or multiplicity checks over unary relational expressions (with lone , some , one , or no ). It is also possible to check the multiplicity of both endpoints of a relational expression with a special arrow notation: formula rin A m →n B , where m and n are multiplicity checks, is a shorthand notation for all a:A|nar and all b:B|mrb . This notation can be used to quickly restrict the shape of a binary relation, as presented in Table 1. For example, a relation 𝑟 that maps each element from a set 𝐴 to at most one element of 𝐵 is known as entire and if it maps to at least one element of 𝐵 is known as simple . A relation that maps at least one element of 𝐴 to each element of 𝐵 is surjective and one that maps at most of one element of 𝐴 to each element of 𝐵 is injective . A relation is a function if it is both simple and entire. An injective function is called an injection and a surjective function is called a surjection . A function is a bijection if is both injective and surjective. Atomic formulas can be composed with the standard logical operators and with quantifiers. There are two forms of each logical operator: a shorthand (!, || , && , ⇒ , ⇔ ) and a verbose form ( not , or , and , implies,iff). The two form are completely interchangeable. As seen in the previous section, relational expressions are built with both set and relational operators. The operators + , − , & are the standard set operators of union, difference, and intersection, respectively. 23 2.2. Formal Presentation of the Language As for relational operators we have product ( → ), transpose ( ∼ ), domain and range restriction ( <: and :> ), transitive and reflexive closure ( ^ and * ), and join (  ). There exists an alternative notation for (dot) join, known as box join : expression p[s] is the same as sp , but box join has lower precedence that dot join, hence, pq[s] is equal to (p q)[s] . The override operator ( ++ ) is used to replace some tuples in a relation: the expression p ++ q is the union of p and q after removing from p the tuples that starts with an element in the domain of q. Alloy has limited support for integers. Signature Int contains all the integers present in the universe. Integers are represented in two’s complement notation, and the scope of Int in a command sets the numbers of bits used in the representation. Module util/integer provides some arithmetic functions and predicates to work with integers. For example add is a binary function that adds two integers. All arithmetic operations work in the usual way for two’s complement representation, namely with wrap-around semantics. The cardinality operator ( # ) computes the number of tuples in a relation. There is also a special quantifier sum that can be used to sum the integers somehow associated with all the atoms of a unary expression. Integers should be used very carefully in Alloy due to the wrap-around semantics. For example, if the scope for Int is not chosen correctly the operator # can return the wrong cardinality of a set. Fortunately, when developing abstract models, integers can usually be replaced by structures with less semantics, such as signatures with total orders (imposed with module util/ordering ). An alternative semantics for integers with the goal of preventing arithmetic overflows has been proposed in (Milicevic and Jackson,2014), but it is also rather cumbersome. As such, in this thesis we will not address integers in Alloy. 2.2.2 Formal Semantics After expanding predicates, functions and modules, an Alloy model basically consists of a collection of relation declarations (signatures and fields inside a signature) and a collection of facts and analysis commands. For a given command, the meaning of a model is a set of instances, each of which assigns a value to each of the declared relations, makes the facts true, and makes the formula in the command true or false, depending if the command is a run or a check, respectively. In practice, a check command can be replaced by a run command with the negated assertion, and instead of putting assertions in facts, they can just be conjoined in the command. Hence, an Alloy model can essentially be regarded just as a set of signatures and field declarations together with one run command containing the constraint one wishes to make true. 24 2.2. Formal Presentation of the Language alloyModule ⋅ ⋅⋅ ⋅=sigDecl∗cmdDecl sigDecl ⋅ ⋅⋅ ⋅=sig name [sigExt ]{ decl,∗} sigExt ⋅ ⋅⋅ ⋅=[abstract ]extends name |in name [+ name ]∗ decl ⋅ ⋅⋅ ⋅=name : [set]expr form ⋅ ⋅⋅ ⋅=expr in expr |not expr |expr and expr |all decl | form expr ⋅ ⋅⋅ ⋅=name |const |unOp expr |expr binOp expr |{ decl,+| form } const ⋅ ⋅⋅ ⋅=none unOp ⋅ ⋅⋅ ⋅= ∼ |^ binOp ⋅ ⋅⋅ ⋅=+|&|−||→ cmdDecl ⋅ ⋅⋅ ⋅=run { form } for typeScope,+ typeScope ⋅ ⋅⋅ ⋅=[exactly ]number name Figure 7: Syntax of the core Alloy language. In this section, we will explain the semantics of the Alloy language in terms of such simplified core language, where a model consists only of declarations and a single run command. This core language also does not include some operators that can be defined with others, and does not allow multiplicity restrictions in declarations. It is much smaller than the full Alloy language, but it captures its essential semantics, and it is quite easy to translate the full language into it, as we will briefly explain below. The syntax of the core language is presented in Fig. 7. To translate an Alloy model to this core language, we can start by in-lining all imported modules, and expand all predicate and function definitions at the point they are called. Signature facts can be converted to normal facts by quantifying universally. Multiplicities in declarations can also be trivially replaced by facts. For example, declaration some sig Product {} is equivalent to sig Product {} fact {some Product} And the multiplicity in the declaration of category in signature Product sig Product {category: some Category} can be replaced with sig Product {category: set Category } fact {all p:Product | some pcategory } 25 2.3. Refactoring Alloy Models The resulting Boolean formula is finally passed to a SAT solver. If the solver finds no solution, the Analyzer will generate a message saying that no instance or counterexample is found, otherwise, the solution will be mapped back to an instance, to be graphically depicted. In order to decrease SAT complexity, Kodkod performs a variety of optimizations before sending a formula to the SAT solver. The most significant one is symmetry breaking. Since atom names are meaningless, many instances would in fact be isomorphic (modulo renaming). Kodkod detects which atoms can be considered symmetric based on the declaration of bounds and generates a lex-leader symmetry breaking predicate that is conjoined to the problem’s formula. This not only filters out isomorphic instances from users, but also improves the efficiency of analysis by reducing the search space. In our example problem, the universe can be partitioned into two sets of symmetric atoms, namely {A1,A2} and {A3,A4} . This means that, for example, an instance with no images and a single product A1 can be generated, but the isomorphic instance with the single product A2 will not. 2.3 Refactoring Alloy Models Refactoring , an essential activity in programming, is a technique that enables code quality improvements (for example, improve readability or efficiency) without changing its external behaviour. Refactoring of design models is also important and could provide similar benefits. For Alloy in particular, a catalogue of refactoring bidirectional transformations has been proposed in (Gheyi and Borba,2004;Gheyi,2007). To support more application scenarios, such as refining a model by introducing additional signatures or relations, they use a more flexible notion of equivalence between the models (before and after applying the refactoring), based on bidirectional refinement. The semantics of the models is only compared for a relevant set of signatures and fields Σ. The value of entities not in this set is considered irrelevant and is not compared. Moreover, for elements in Σ that are not present in both models, a view function 𝑣 must be defined, stating how the value of an element in one model can be interpreted using elements of the other. Each refactoring law consists of two templates (patterns) of equivalent Alloy models (according to the above notion), on the left-hand and right-hand sides. A refactoring can be applied whenever one template of the law is matched with a model and some pre-conditions are met. In the following laws, ps represents a collection of paragraphs, frms stands for a set of formulas, ds denotes a set of relations, n refers to identifiers, and exp denotes a relational expression. After each law some pre-conditions are provided for its application to be possible. The symbol (→) indicates a pre-condition that is only required when applying the law from left to right, while (→) indicates a pre-condition that is required when applying the 32 2.3. Refactoring Alloy Models law in the opposite direction. A pre-condition marked with (↔) is necessary in both directions. All the proposed laws were formalized and proved sound using the PVS theorem prover4. We will now present some of the refactoring laws proposed by Gheyi (2007). 2.3.1 Laws for Signatures Law 1 says that we can add or remove an empty signature that is not used elsewhere. The proviso in the bottom of the law states that the name of the new signature can not be declared in the model. Notice that in this case the equivalence between the two models does not consider the value of the new signature. Law 1 (Introduce signature). ps =Σ,𝑣 ps sig n{} provided (↔) (1) n is not in Σ ; (2) for all names in Σ that are not in the resulting model, 𝑣 must have exactly one valid item for it; (→)ps does not declare any signature named n; (←)ndoes not appear in ps. Law 2 allows us to remove the abstract quantifier, and replace it by a constraint. Notice that the number of sub-signatures has no constraint and can be any number greater than zero. Moreover, it can be applied when nextends another signature and there are no pre-conditions for its application. Law 2 (Remove abstract qualifier). ps abstract sig n{ds } sig n1extends n{ds1} ⋯ sig n𝑛extends n{ds𝑛} =Σ,𝑣 ps sig n{ds } sig n1extends n{ds1} ⋯ sig n𝑛extends n{ds𝑛} fact {n=n1+⋯+ n𝑛} Law 3 introduces a generalization between two or more signatures. We can always remove (add) a parent signature that is not used in other places of the model by applying the law from right to left (left to right). If the new signature is to be considered in the equivalence then it must be defined accordingly in the view. 4https://pvs.csl.sri.com 33 2.3. Refactoring Alloy Models Law 3 (Introduce generalization). ps sig n1{ds1} ⋯ sig n𝑛{ds𝑛} =Σ,𝑣 ps sig n{} sig n1extends n{ds1} ⋯ sig n𝑛extends n{ds𝑛} fact {n=n1+⋯+ n𝑛} provided (↔)If nbelongs to Σ,𝑣must contain the view n↦n1+⋯+ n𝑛; (→)ps does not declare any paragraph named n; (←)ndoes not appear in ps,ds1, …, ds𝑛. Law 4 allows us to remove (or add) multiplicity qualifiers for signatures (possibly extending other signatures). No pre-conditions are required for this law. Note that this law together with Law 2 enables the removal (or adding) of multiplicity qualifiers from abstract signatures. Law 4 (Remove signature multiplicity qualifier). ps mlt sig n{ds }=Σ,𝑣 ps sig n{ds } fact {mlt n } where mlt ∈{one,lone,some}. 2.3.2 Laws for Fields Law 5 enables the introduction of a new field named n0 whose value is determined to be exp . Similarly, we can also remove fields that is not being used, by applying the law from right to left. The family of a signature is the set of signatures that extend or are extended by it direct or indirectly. The first pre-condition in (→)is necessary because Alloy does not allow two overloaded fields in the same family. Law 5 (Introduce relation). 34 2.3. Refactoring Alloy Models ps sig n{ ds } =Σ,𝑣 ps sig n{ ds, n0:set T } fact {n0= exp} provided (↔)If n0belongs to Σthen n0does not appear in exp and 𝑣contains the view n0↦exp; (→) The family of n in ps does not declare any field named n0 ; T is a signature name declared in ps or is S;n0does not appear in exp or exp is n0;exp is well-typed in the resulting model; (←)n0does not appear in ps. Similarly to signatures, the multiciplicity qualifiers in a field can be removed, and replaced with a fact by applying Law 6 from left to right. Law 6 (Remove field multiplicity qualifier). ps sig n{ ds, n0:mlt T } =Σ,𝑣 ps sig n{ ds, n0:set T } fact {all x:n |mlt x n0} where mlt ∈{one,lone,some} . Fields declared together can always be separated with Law 7, by applying it from left to right. Law 7 (Separate field declarations). ps sig n{ ds, n0,⋯,n𝑘:set T } =Σ,𝑣 ps sig n{ ds, n0:set T, ⋯ n𝑘:set T } 35 2.3. Refactoring Alloy Models A final example of a refactoring law for relations is Law 8, which allows to replace an expression in a field declaration by its type. Law 8 (Replace field expression). ps sig n{ ds, n0:set exp } =Σ,𝑣 ps sig n{ ds, n0:set T } fact {all x:n|xn0in exp’ } provided (↔)exp has the type T , which is a signature declared in ps or is n ; exp′ replaces each reference to a field relation r of n (whether declared or inherited) not prefixed by @ by xr , and every occurrence of this by x. (←)n0does not appear in exp. 2.3.3 Laws for Formulas Besides laws for signatures and relations, there are also some rules proposed for refactoring formulas. Law 9 states that we can add or remove a formula that can be deduced from other formula specified in the fact of a specification. This law offers a way for remove redundant constraints in Alloy. Since the condition of Law 9 is not syntactic, an extra mechanism must be used to guarantee the its satisfaction. For example, we can use Alloy itself for checking this condition, using a check command to verify if the formula fholds. Law 9 (Introduce formula). ps fact n{ frms } =Σ,𝑣 ps fact n{ frms f } provided (↔)fcan be deduced from the facts in ps and frms. 36 2.4. Alloy Extensions Figure 13: Transition system of a vending machine. Law 10 allows the introduction of an empty fact provided there is no name conflicts. Since facts cannot be referred to by other paragraphs, the elimination of an empty fact is always possible. A similar law can be defined for introducing or removing empty signature facts. Law 10 (Introduce empty fact). ps =Σ,𝑣 ps fact n{} provided (→)ps does not declare any paragraph named n. 2.4 Alloy Extensions In order to achieve distinct goals such as verifying behavioral requirements when designing software systems or improving scenario exploration, a number extensions to (or variants of) Alloy have been proposed. Among them, the Electrum (Macedo et al.,2016;Brunel et al.,2018) extension was proposed for the analysis of dynamic systems with rich configurations, and will soon be included in the official version 6 of the Alloy language. In plain Alloy, the value of all signatures and field relations is immutable. If one wants to model variable relations, it is necessary to introduce an explicit time signature, totally ordered to simulate an execution trace, and all relations whose value might change must include this signature as an extra column in their declaration. As a simple example, let us consider a simple vending machine system adapted from the family of vending machine systems used to introduce feature transition systems (FTSs) (Classen et al.,2010). A basic vending machine system takes a coin, returns change, selects a soda, serves the soda, and eventually opens a compartment for the customer to take their soda. Three additional features were added to the 37 2.4. Alloy Extensions basic model: selling Tea ; allowing buyers Cancel their purchase; offering Free drinks. Here we consider one of the variants of this system, just with the feature cancel, and its behavior is depicted in Fig. 13 with a transition system. After paying, the user can select one of the products in stock. Then if the selection is not canceled, the product is served, and the door opens, so that the user can collect the selected product. After collecting the product or canceling the selection, the change is returned to the user. To model this vending machine in plain Alloy we need to declare singleton signatures for the possible states of the machine, and a signature for the possible products. abstract sig State {} one sig Ready, Paid, Selected, Served, Done extends State {} sig Product {} As mentioned above, to model variable relations and sets, we can to introduce an explicit Time signature, and inside it declare fields for all relations that are supposed to be mutable. By doing this, we allow them to have different values in different Time instants. In this case we would like to have four mutable relations: state , that captures the state the machine is in, stock , that contains the available products, selection , that contains the selected product, and balance , the amount of coins collected by the machine (assuming a price of one coin per product). A total ordering should also be imposed over Time , so that time instants form a trace. For balance the standard library util/natural is used: this library declares a signature Natural to represent natural numbers. open util/ordering[Time] as time open util/natural as nat sig Time { state : one State, stock : set Product, selection : lone Product, balance : one Natural } Operations can be modeled with predicates that relate the value of mutable relations at a given Time instant (parameter pre below) with their value at the next one ( pos ). For example, operation Select can be specified as follows. 38 2.4. Alloy Extensions pred Select [pre,pos : Time, p : Product] { pre state = Paid and pin pre stock pos state = Selected pos selection = p pos stock = pre stock pos balance = pre balance } In the first line we have the pre-condition for this operation to occur: the machine should be in state Paid and the selected product should be in stock . Then we have the effect of the operation: the state will change to Selected and the product will be added to selection . Finally we have the frame-condition that specifies what does not change, in this case the stock and balance. Having specified the operations, it is necessary to axiomatize what are valid traces. In this case, a valid trace should begin with state set to Ready , no selection , some stock , and zero balance . Then all transitions between consecutive time instants should result from one of the specified operations. This behaviour can be specified in the following fact. fact Behaviour { first state = Ready no first selection some first stock first balance = Zero all pre : Time, pos : pre time/next { Pay[pre,pos] or (some p : Product | Select[pre,pos,p]) or Cancel[ pre,pos] or Serve[pre,pos] or Open[pre,pos] or Change[pre,pos] } } Temporal properties can be specified by quantifying explicitly over the time signature. For example, to specify that every time the machine is in the Served state the balance must be strictly positive we could write the following assertion. assert Balance { all t : Time | t state = Served implies gt[t balance,Zero] } check Balance for 3but 10 Time 39 2.4. Alloy Extensions Figure 14: The pre- and post-state of the cancel operation. This property is valid (here we are checking it with traces of size 10). As another example, to specify that every time the machine is in the Done state previously it must have been in the Served state, we could write the following assertion. assert DoneImpliesServed { all t : Time | t state = Done implies some u : t *time/prev | u state = Served } check DoneImpliesServed for 3but 10 Time Notice the use of t*time/prev to compute all time instants that occurred up to instant t. Checking this property yields an obvious counter-example, where the user cancels the selection and thus is not served a product. To better understand trace counter-examples, we could use the projection feature of the visualiser, that allows the user to focus on a particular atom of a signature at a time. In this case, by projecting on the Time signature we can see one time instant at a time. Figure 14 shows the two consecutive time instants corresponding to the Cancel operation (with the theme already configured to hide irrelevant information). Assertion DoneImpliesServed is an example of a safety property. Special care must be had to properly perform bounded model checking of liveness properties, as counter-examples must be infinite traces (Cunha,2014). The need to explicitly model time and traces in plain Alloy ends up often being a tedious, time-consuming, and error-prone task, in particular if we need to verify liveness properties, where back loops must also be considered to represent infinite traces. In contrast, Electrum offers an implicit notion of time and allows both signatures and fields to be declared as mutable using the keyword var . Instances (traces) are infinite (looping) sequences of time instants. The non-variable signatures and fields are still static, meaning that their value remains fixed during the evolution of the system. Facts and assertions can be specified using Linear Temporal Logic operators (including past ones), such as always or eventually , and expressions can be evaluated in the next 40 2.4. Alloy Extensions state by marking them with ' . The Electrum Analyzer supports both bounded-model checking with a translation to Kodkod and complete model checking with a translation to SMV model checkers, such as NuSMV5or nuXmv6. In the vending machine example, instead of declaring them inside the explicit Time signature, the declaration of the three mutable sets could be done simply as follows. var one sig state in State {} var sig stock in Product {} var lone sig selection in Product {} var one sig balance in Natural {} By using ' , the specification of operations is also much simplified (and do not need to be explicitly parametrized with the time instants). For example, the Select operation could be specified as follows. pred Select [p : Product] { state = Paid and pin stock state' = Selected selection' = p stock' = stock balance' = balance } The specification of the Behaviour fact is also much simpler, resorting to the always temporal operator to restrict the valid transitions. fact Behaviour { state = Ready no selection some stock balance = Zero always { Pay or (some p : Product | Select[p]) or Cancel or Serve or Open or Change } } 5https://nusmv.fbk.eu 6https://nuxmv.fbk.eu 41 3.1. Feature Modeling between a child feature and its parent with a sequence of intervals [𝑛..𝑚] , where 𝑛 is the lower bound and 𝑚 is the upper bound. These intervals determine the number of instances of a feature that may be part of a family member. A specification of a feature can have more than one interval. For example, [0..2][6..6] shows that one can take 0 , 1 , 2 or 6 times of the corresponding feature. In particular, the mandatory and optional relationships can be generalized as [1,1] and [0,1] respectively. A group cardinality is an interval ⟨𝑛,𝑚⟩ , with the lower bound 𝑛 and the upper bound 𝑚 , which represents the number of sub features that can be selected from a parent feature. Therefore, a xor-group can be changed to ⟨1,1⟩ group cardinality, and an or-group to ⟨1..𝑛⟩ , where 𝑛 is the number of features in the group. For example, the or-group with PNG and JPEG in Fig. 18 can be labeled with group cardinality ⟨1,2⟩ , meaning that a product has to select at least one and at most two features in the group Thumbnails. The optional features Hierarchical and Multiple would be annotated with feature cardinalities [0..1]. Another typical extension is the ability to introduce feature attributes (Czarnecki et al.,2002,2005), so that a diagram can be more succinctly represented and have improved readability. The attributes of a feature can be introduced by associating it with a type which can either be a primitive data type, such as integer, float, Boolean, string, or a reference type that allows the user to model graph-like connections between features. A feature can have several attributes each of which can be modeled by a distinct subfeature of the given feature, in which case the hierarchy in the diagram increases rapidly and quickly leads to a very large diagram. With feature attributes, the developers can reorganize the tree structure to a more concise and intuitive diagram. Since FMs are ubiquitous in all activities of feature-oriented software development, considerable efforts have been made to develop interchangeable formats for FMs (Sepúlveda et al.,2012;Eichelberger and Schmid,2013). Some of these have have been developed mostly with tool support in mind, so that they are managed through a graphical interface and are not expected to be human-readable, such as XML formats provided by FeaturePlugin (Antkiewicz and Czarnecki,2004), FAMA (Benavides et al.,2007) or FeatureIDE (Thüm et al.,2014). However, graphic representations have poor scalability due to cluttering in large systems. Thus, various human-readable text-based languages have been proposed for feature modeling, including FDL (Van Deursen and Klint,2002), GUIDSL (Batory,2005), SXFM (Mendonça et al., 2009a), VSL (Abele et al.,2010), and TVL (Classen et al.,2011a) (see, for instance, (Eichelberger and Schmid,2013) for a detailed comparison). As an example, we briefly present TVL (Text-based Variability Language), which supports most extensions of FMs and is used as an input language for FMs for some of the analyses that will be presented in Section 3.1.2. TVL is a light and comprehensive feature modelling language. It is a text-based human- 48 3.1. Feature Modeling root Catalog group allOf { Image group someOf { PNG, JPG }, opt Thumbnails, opt Categories group allOf { opt Hierarchical, opt Multiple }, opt OnSale } Figure 19: E-commerce FM encoded in TVL. readable feature modelling language with comprehensive constructs that is usually used as an auxiliary language for the variability modelling languages to specify the differences and common features during the verification process. It has a C-like syntax and a formal semantics which allows the engineer to model FMs intuitively and easily without concerns about ambiguities. The root feature of an FM is specified by the keyword root followed by the name of the root feature. The decomposition relation is introduced by the group keyword, which is followed by the decomposition type. The 𝑎𝑛𝑑 , 𝑜𝑟 , and 𝑎𝑙𝑡𝑒𝑟𝑛𝑎𝑡𝑖𝑣𝑒 decomposition types were renamed to allOf , someOf , and oneOf respectively. The and-decomposition type can also specify cardinality. The cardinalities can be constants, natural numbers, or the asterisk character. If a feature is an optional feature, its name is preceded by the opt keyword. Each feature can declare its own children. Figure 19 shows an example of the FM of the catalog structure of the e-commerce platform from Fig. 18 encoded in TVL. Cardinality-based decomposition relations and attributes can be easily modeled in the body of a feature in TVL Language. Furthermore, a feature can be extended easily since its just a name showing below the decomposition operator. 3.1.2 Analyzing Feature Models The analysis of system families concerned to the verification and specification of family members has been paid a lot of attention in the research and practical fields. Extracting information from FMs manually is really time-consuming and error-prone. Hence, effective methods to provide automated analysis mechanisms have led to wide research interest since FMs were proposed. A set of operations, techniques, and tools has 49 3.1. Feature Modeling been proposed in the literature. In this section, we give an overview of some of the most useful operations as well as the approaches for their automatic analysis. Analysis Operations Since the introduction of FMs, a number of operations have been proposed in the literature and play a significant role in the domain analysis step. Here, a brief review of some widely used operations will be given. To get more acquainted with the operations please see (Benavides et al.,2010). Analyses of FMs are categorized as correctness checking and configuration support (Mendonça et al.,2009b). Examples of correctness checking include the consistency checking and dead or common features finding, while examples of configuration support include finding optimal products or multi-step configuration. Void Feature Model The void feature model operation is used to validate whether an FM is void or not. An FM is void if it represents no product instance. Usually, the major causes of a void FM are the wrong usage of cross-tree constrains. This operation is widely used in the debugging process especially in large-scale FMs (Benavides et al.,2010). In such models, the detection of this kind of problem is an error-prone and time-consuming task. N u m b e r o f P r o d u c t s This operation returns the number of valid product instances modelled by an FM. Obviously, the return number of a void FM is zero. The result of this operation shows the flexibility and complexity of a system family and may also help the developers to detect potential product instances. V a l i d a t i n g P r o d u c t s Most of the time, it is useful to check whether a product (also called specification in the literature) is valid or not when analyzing and managing system families. The validate operation, also referred as product checking or product specification completeness , determines whether a product belongs to the system family. Finding Dead and Common Features A dead feature is a feature that does not belong to any of the valid products in a system family. Generally, dead features are caused by the wrong usage of cross-tree constraints between features. Notably, all features depicted in a void FM are dead features. A common feature is a feature that is shared by all product instances. 50 3.1. Feature Modeling I d e n t i f y i n g A t o m i c S e t s An atomic set is a group of features that can be treated as a unit when analyzing an FM. The complexity of an FM is reduced since features of an atomic set always appear together. Obviously, features related by mandatory relations are always part of the same atomic set. F i n d i n g a l l F a m i l y M e m b e r s In an FM, a product represents a unique set of feature selection. Sometimes, the developer would like to find all valid products for the system family in order to identify new members that are not considered in the initial design step. The result of this operation is a set containing all valid products described in the FM. S e l e c t i n g O p t i m a l P r o d u c t s This operation is used to find a product instance that fulfills a criterion decided by the user. The criterion is a function that determines how good a solution is for a particular product instance. In general, this operation is used in FMs extended with attributes with the parameters of the function constrained in the attribute field. This operation is well suited for CSP-based analysis approaches, as described later in this section. M u l t i - s t e p C o n f i g u r a t i o n Multi-step configuration is a process to find a series of intermediate configurations that satisfy a series of configuration constraints and edge constraints. The set of edge constraints may include numerous types of constraints on the transition from one configuration to another. Configuration constraints must be satisfied at each step, such as the FM rules. This operation requires the initial configurations, desired final configurations, a number of steps for the configuration, and a function determining the cost to transition configurations through the steps. The result of this operation is an ordered list of configurations. Automated Analysis Support There is extensive work on supporting such FM analysis operations (see for instance (Benavides et al., 2010) for a survey). Most of the analyses concern the operations just described. Here we divide them into three groups according to the underlying logic paradigm. Particularly, we present SAT-based analysis approaches, CSP-based approaches, and other paradigms. The main idea of SAT and CSP approaches is to translate an FM to a property in the respective logic, and then automatically analyze that property using an off-the-shelf solver. Besides the binary decision operations, CSP-based methods can deal with operations yielding integer or set values, which cannot be handled natively by SAT-based approaches. 51 3.1. Feature Modeling Table 2: Rules for translating FMs to propositional formulas. Relationship Graphical notation Mapping to a formula root 𝑟 mandatory 𝑝↔𝑐 optional 𝑐→𝑝 or-group 𝑝↔(𝑐1∨𝑐2∨...∨𝑐𝑛) xor-group (𝑐1↔(𝑝∧¬𝑐2∧...∧¬𝑐𝑛))∨ (𝑐2↔(𝑝∧¬𝑐1∧¬𝑐3∧...∧¬𝑐𝑛))∨...∨ (𝑐𝑛↔(𝑝∧¬𝑐1∧¬𝑐2...∨¬∧𝑐𝑛−1)) S A T - b a s e d A n a l y s i s SAT-based approaches have attracted considerable attention especially after Batory (2005) proposed the rules for translating FMs to propositional logic formulas. In particular, the features in the model are encoded as Boolean variables, while the relationships as well as the additional constraints, are translated to formulas expressed over these variables. Table 2 shows the translation of relations between a parent and its child features. Feature 𝑟 represents the root feature of an FM and will be translated to a simple formula 𝑟 that forces the respective variable to be true. The relationship between a parent feature and its child features are represented by the implication operator. More specifically, there is an implication from every child feature 𝑐 to its parent 𝑝 . However, only the mandatory child features are implied by its parent. An or-group is represented by an implication from the parent feature 𝑝 to at least one of its child features 𝑐1,𝑐2,...,𝑐𝑛 , while in a xor-group the parent implicates exactly one of its child features. To obtain the semantics of an FM, all formulas for its individual relations are conjoined together, and then some of the operations described above can be implemented trivially by invoking a SAT solver (for example, determining if the FM is void or validating a product). Some works use higher level modelling languages instead of SAT directly. For example, considerable work has been performed on analyzing FMs using Alloy (Sree-Kumar et al.,2016). The implementation of FMs needs to be made manually since there is no standard format to represent FMs in Alloy. In general, the possible features are described as a collection of singleton signatures and the relation and the cross-tree constraints among features are encoded using predicates following the semantics described 52 3.1. Feature Modeling above. Regarding the automatic analysis, assert commands can be used for operations such as product validation or checking common features, while run commands can be used for operations such as finding all family members. This approach was followed, for example, in one of the Alloy encodings proposed in (Gheyi et al.,2006), the so-called R-theory of FMs. In this encoding, an FM is just a collection of feature names (to be instantiated with singleton signatures). sig FM { features: set Name } sig Name {} The semantics of the FM can then be encoded with predicates that enforce a particular restriction over a configuration (a set of feature names), for example: pred mandatory(A,B:Name, config:set Name) { Ain config ⇔Bin config } In this work another encoding was proposed, the so-called G-theory, where an FM includes an explicit representation of its relations and cross-tree constraints. For example, for capturing relations we have the following signature. sig Relation { parent: Name, child: set Name, type: Type } abstract sig Type {} one sig Optional, Mandatory, OrFeature, Alternative extends Type {} Many operations, namely checking valid/invalid configurations, detecting dead and common features, or checking if a transformation is a refactoring, can be implemented with both encodings, but some can only be implemented with the G-Theory. However, the R-Theory is more efficient due to the much reduced number of signatures to encode a particular FM. Another work that used an encoding of FMs in Alloy very similar to the G-theory is (Ripon et al.,2012). 53 3.1. Feature Modeling C S P - b a s e d A n a l y s i s A Constraint Satisfaction Problem (CSP) is a mathematical problem that consists of a set of variables, a domain for each variable, and a set of constraints restricting the values of the variables. The aim of a CSP is to choose a value for each variable so that all constraints are satisfied. Constraint programming is a powerful and flexible technique for dealing with CSPs, in particular those with lots of constraints. In the research literature, there are some works (Benavides et al.,2005a,b,2010) that propose the use of constraint programming for the automated analysis of FMs. When translating an FM to a CSP, the features are mapped to variables with {True,False} or {0,1} domain, depending on the solver that will be selected. The relations between features are translated to different kinds of constraints over feature variables. Let us suppose 𝑝 is the parent of child features 𝑐1,...,𝑐𝑛 , and the domain of the feature variables is {0,1} . The mandatory relation between 𝑝 and 𝑐1 will be encoded as 𝑐1=𝑝 , while the optional relation between 𝑐1 and 𝑝 will be mapped to the conditional expression if (𝑝 = 0)then (𝑐1= 0) . An or-group relation in the children will be transformed into expression if (𝑝>0)then (1≤𝑐1+...+𝑐𝑛≤𝑛)else 𝑐1=...=𝑐𝑛=0 , and a xor-group relation would be encoded with constraint if (𝑝>0)then (𝑐1+...+𝑐𝑛=1)else 𝑐1=...=𝑐𝑛=0 . In many real-life development scenarios, we do not want to find any solution but a good solution. Constraint programming is more effective that SAT for finding an optimal solution for a particular requirement. The criterion to assess the quality of a solution can be modeled as an objective function based on the variables described in the feature and attributes. As such, this approach is better fitted for dealing with FMs extended with attributes. After the transformation, an off-the-shelf CSP solver, such as IBM’s CPLEX Optimizer 1 , can be used to conduct an automatic analysis. Most of the analysis operations for FMs can be performed by constraint programming (Benavides et al., 2007). A detailed presentation of such analyses, for example computing the number of products, validation of an FM, or finding valid products can be found in (Benavides et al.,2005b). The result for the same operation can be different if different solvers are chosen. The performance may be improved if several solvers are working together (Benavides et al.,2007). In this context, a multi-platform and extensible framework, FAMA (Benavides et al.,2007) was proposed. It allows the integration of different solvers (including SAT solvers) to optimize the analysis process. FAMA can be configured to use the most efficient available solver for each operation during execution time. The configuration parameters are set based on the priority between each operation for the available solver. Usually, the performance of analysis using SAT 1https://www.ibm.com/analytics/cplex-optimizer 54 3.2. Modeling in Feature-oriented Design solvers is slightly better than of CSP, but, as mentioned above, the latter can handle FMs extended with attributes and finding optimal solutions according to criteria that maximize or minimize attribute values. O t h e r K i n d s o f A n a l y s i s There are some works that use neither SAT nor CSP to perform automatic analysis of FM. For example, in (Segura,2008) an algorithm is proposed to simplify FMs by calculating atomic sets. The idea is reduce the number of variables that are needed for its analysis, by replacing each feature variable by a new variable that identifies the atomic set it belongs to. This algorithm proceeds by recursively checking all the child features of the FMs. A child feature is added to the current atomic set if it is mandatory. Otherwise, a new atomic set including the child feature is created and added to the collection of atomic sets. A set of atomic sets is returned when all the features are checked. In (Wang et al.,2007) a method is proposed that uses description logics to analyse FMs. Description logics are a family of knowledge representation languages enabling the reasoning within knowledge domains by using specific logic reasoners. It consists of a set of concepts, a set of roles, and set of individuals (or instances). The problem is solved by a solver providing facilities for consistency and correctness checking. In this method, Web Ontology Language (OWL) ontologies were used to capture the relationships among the features. The analysis of an FM can then performed with off-the-shelf OWL reasoning engines, which can for example be used to check for inconsistencies of feature configurations. As a final example, in (Hemakumar,2008) a method is described to statically detect conditional dead features in a system family. A contradiction in an FM is a specification error. Finding such errors is important, both for designers and customers. An FM is 𝑘 -contradiction-free where 0<𝑘≤𝑛 , if every selection of 𝑘 features does not expose a contradiction (i.e. they are compatible). The FM is proven to be contradiction-free if 𝑛 is the number of selectable features for the user. 3.2 Modeling in Feature-oriented Design Specification languages are textual computer languages that define the system models as well as the system properties by a systematic set of rules and frameworks, and are used to model the system under development during design. General-purpose specification languages are often sufficiently rich to support the explicit encoding of features and variability points. However, as the complexity of the system increases, managing variability may become impractical, and languages have been developed or adapted to natively support feature-oriented design when developing a family of similar systems. This also applies to formal specification languages if designs are expected to be validated and verified (see, for instance, the survey by 55 3.2. Modeling in Feature-oriented Design Composition Base Model 𝐹1 ⋮ 𝐹𝑁 Combined Model (a) Composition-based approach #include <stdio.h> #define 𝐹1 #define ... #define 𝐹𝑁 int main(){ #ifdef 𝐹1 printf("Feature 1 is selected!"); #endif ... #ifdef 𝐹𝑁 printf("Feature N is selected!"); #endif return 0; } (b) Annotation-based approach Figure 20: Language categorization based on variability representation. Benduhn et al. (2015)). Likewise SPL implementation, feature-oriented design approaches also typically fall in two groups depending on how variability is represented: composition- and annotation-based approaches. Composition-based approaches model a system with a base model and a set of delta models describing distinct feature units and specifying the additional variants of the system. As show in Fig. 20a, a variant modeled in such kind of language is derived by compositing the base model with a set of valid features ( 𝐹1,⋯,𝐹𝑛 ) one by one using a composition tool. Hence, the order in which these features are composed matters for generating the final model, since the behaviour specified by one feature maybe rewritten by another that appears later in the composition list. This approach allows the modular development of features and provides a clear mapping from the features to their implementations promoting feature traceability. Therefore, when a developer wants to debug errors that occur in a particular feature, they only needs to work with the code associated with that feature, rather than walk through the entire code. This kind of approach is best suited for coarse granularity variability, such as changing the entire method of a class. Fine grained variability, such as small changes in the body of a method, are often very difficult or impossible to achieve due to the conceptual limitations (Kästner et al.,2008). In annotation-based approaches all variants are superimposed in a single code unit and variability implemented by annotating certain parts of the code with the variant they belong to. During variant derivation, all code that belongs to deselected features or invalid feature combinations is removed from the source code. A typical example of this kind of approaches is the explicit usage of #ifdef and #endif annotations of the C/C++ preprocessors which surrounds related feature code fragments as shown in Fig. 20b (code belonging to distinct features is presented in different colors). In contrast to compositionbased approaches, annotation-based approaches add feature annotations in the actual lines of the source 56 3.2. Modeling in Feature-oriented Design code, which naturally supports fine-grained variability. However, it poorly supports feature traceability, since a feature is not encapsulated in a single code unit but scattered in the code as feature annotations, which can lead to maintainability issues. Although tools such as CIDE (Kästner et al.,2008) provide virtual views and navigation support of feature traceability at the tool level, feature traceability in such approaches is still a matter of tool support (Kästner and Apel,2008). Although the composition-based approach offers an explicit mapping between features and their implementations, which brings a straight forward trace and easy maintenance of the features, in practice the annotative approaches are more popular (Le et al., 2013). The industry is very careful when adopting a composition-based approach because it will have too much impact on the existing code base and the development process. Annotative approaches, by contrast, can be adopted more quickly because they require only lightweight tools which do not change much of the code or development process (Kästner and Apel,2008). This section reviews existing work on feature-oriented modelling of SPLs. The focus is on formal high-level specification languages, although we also explore some graphical conceptual modelling languages. We briefly explore how general-purpose modelling languages can be used to model multiple variants in an ad hoc manner in Section 3.2.1. Then we explore composition- and annotation-based modelling languages for feature-oriented design in Section 3.2.3 and Section 3.2.2, respectively. 3.2.1 Ad-hoc Approaches Some general-purpose modelling languages are sufficiently expressive to support some kind of featureoriented design. The main advantage of such approaches is that they inherit all existing support for a well-established language, including subsequent analyses using existing model checkers or theorem provers. The caveat is that the implementation of the FM must be performed manually, which is cumbersome and error-prone for realistic SPLs. Moreover, it also limits the ability to perform more advanced feature-aware analyses since features are not first-class entities in this context. Some authors explore the decomposition capabilities of general-purpose modelling languages to simulate the implementation of a composition-based approach. For structural modelling, (Shiraishi,2010) proposed a variability modeling approach for the Architecture Analysis and Design Language (AADL), a language for modeling system architectures. AADL supports the specification of several types of components, such as process or threads, as well as their communication through ports. The interface of a component is given by a type definition, and its internal specification by an implementation . Components can be extended or refined , and the authors explore how these mechanisms can be used to model variability. Considering 57 3.2. Modeling in Feature-oriented Design MODULE Main VAR State : {Ready, Paid, Selected, Served, Done}; ASSIGN init(State) := Ready; next(State) := case State = Ready : Paid; State = Paid : Selected; State = Selected : Served; State = Served : Done; State = Done : Ready; esac; Figure 24: Base vending machine model in fSMV. assignment defines the transition relation between, defining how the next state depends on the current state. A feature in fSMV is declared with the keyword FEATURE . There are three main sections of the feature construct, defined by the keywords REQUIRE , INTRODUCE and CHANGE . The REQUIRE section describes what entities are required to be present in the base model in order to encode the specific feature. A collection of modules and variables may be involved in this section, and all preexisting modules and variables that are used in the INTRODUCE and CHANGE sections must be described in the REQUIRE section. The INTRODUCE section introduces new modules, variables, assignment clauses or specifications that will be used in the feature. These are directly added to the SMV code when conducting the integration. The CHANGE section specifies the changes of the system behavior in terms of features. It includes a number of TREAT or IMPOSE clauses, associated with an application condition. TREAT replaces all variable occurrences with a different expression when a certain condition holds, otherwise it remains the same. IMPOSE statements deal with assignments of variables, changing the update of a variable when a certain condition holds, otherwise preserving the original behaviour. Let us consider feature Cancel which adds a transition from state Selected back to Done , representing the cancellation of the selection and the return of the inserted change. A feature in fSMV can only update existing assignments by introducing a new guarded expression, which can override existing ones if the guard overlaps. A possible encoding of Cancel as an fSMV feature is shown in Fig. 25. The CHANGE section introduces a new non-deterministic transition when the system is in state Selected , either to Served , as originally, or to Done when cancelled. In the merged model next(State) is changed so that state Selected always enters that assignment, leaving the original transition to only Served unreachable. A 64 3.2. Modeling in Feature-oriented Design FEATURE Cancel REQUIRE MODULE Main VAR State : {Ready, Paid, Selected, Served, Done}; INTRODUCE CTLSPEC EF !(State = Served) CHANGE MODULE Main IF State = Selected THEN IMPOSE next(State) := {Done,Served}; Figure 25: Feature Cancel of the vending machine in fSMV. new specification only relevant for products where Cancel is selected – checking if there are paths where the drink is never served – is also added in the INTRODUCE section. As another example, feature MultiSelection in fSMV is depicted in Fig. 26. This feature introduces a new variable cnt – counting the number of selected items – as well as assignments for its initial state and transitions. In this case, the increment of cnt occurs in a transition from Selected to itself when the user requests an additional item, is reset when leaving state Served , and is left unchanged otherwise. The transition of State when in Selected is also updated accordingly, allowing the non-deterministic transition either to Served or back to Selected. The main advantage of fSMV – as other composition-based approaches – is that features are developed independently, promoting the separation of concerns, modularity and maintainability. Unfortunately, such approaches also have some drawbacks. Some are related to the granularity and nature of the refinement operations usually provided by such approaches. In fSMV, for instance, existing expressions in assignments cannot be updated (e.g., by adding a new possible state as in our example), meaning that the user must always fully specify the update for the intended guard. Another limitation is that the provided operations are mostly incremental, so that existing sections (such as variable declarations) cannot be removed. Another issue is related to the feature interaction problem, which arises when features interfere with each other in ways that are not easy to predict. In particular, transitions affected by several features are hard to model in fSMV’s composition-based design. In fact, this is patent in our example: both Cancel and MultiSelection changes introduce a new assignment when State is in Selected , so in products with both features selected, depending on the order of composition, it will either end with the non-deterministic choice between Served and Selected or Served and Done , although the expected behaviour would be the choice between those 3 states. In composition-based approaches with the level of granularity of fSMV, 65 3.2. Modeling in Feature-oriented Design FEATURE MultiSelection REQUIRE MODULE Main VAR State : {Ready, Paid, Selected, Served, Done}; INTRODUCE VAR cnt : [0..5] ASSIGN init(cnt) := 1; next(cnt) := case State = Selected & next(State) = Selected & cnt<5 : cnt+1; State = Served : 1; true : cnt; esac; CHANGE MODULE Main IF State = Selected THEN IMPOSE next(State) := {Selected,Served}; Figure 26: Feature MultiSelection of the vending machine in fSMV. this problem must be addressed through the creation of a new derivative feature that must be additionally merged when both other features are selected. This is depicted in Fig. 27, fixing the State transition. This approach will undermine the reusability characteristic of composition-based approaches and as the number of feature interactions grows, it may become unmanageable. FeatureAlloy FeatureAlloy is a feature extension of the lightweight modelling language Alloy proposed by Apel et al. (2010). Like fSMV, FeatureAlloy is a composition-based approach that takes advantage of the distinguishing characteristics of feature-oriented software development and establishes a clear mapping between features and their design. It separates the features of a complex system, making them explicit in the design phase. The elements that are to be introduced or changed by a feature (signatures, predicates, functions, or assertions) are encapsulated and modeled separately from the base system. These features combine with the base model or other features by means of a tool, called FeatureHouse, in order to produce a final model in plain Alloy. Assertions can then be checked using the standard Alloy Analyzer. The composition is achieved by recursively superimposing and merging the features selected by a user. FMs are not explicitly considered during superimposition, and the authors argue that such assertions capture depedences that would not have been present in FM regardless. 66 3.2. Modeling in Feature-oriented Design FEATURE CancelMultiSelection REQUIRE MODULE Main VAR State : {Ready, Paid, Selected, Served, Done}; cnt : [0..5]; CHANGE MODULE Main IF State = Selected THEN IMPOSE next(State) := {Served,Done,Selected}; Figure 27: Derivative feature for Cancel and MultiSelection of the vending machine in fSMV. module ecommerce sig Product { catalog : some Catalog, images : set Image } sig Image {} sig Catalog {} Figure 28: Base model of the e-commerce catalog in FeatureAlloy. FeatureAlloy combines new features by means of refinement. Elements in the refining module are added to the base module or overwrite the existing elements. Specifically, signatures are refined by adding new fields (or overriding existing ones) while paragraphs (except assertions) are refined by overriding. All matches are determined by the elements’ names. Assertions are not allowed to be replaced by subsequent features since the authors advocate their use to detect semantic dependences and feature interactions. We will explain in detail FeatureAlloy by encoding some features of the e-commerce catalog running example. The base model, shown in Fig. 28, organizes the system in catalogs, images, and products assigned to some catalogs and with possibly images associated. Figure 29 depicts a module that refines the base model by introducing feature Thumbnails. Signature Catalog has a new field thumbnails which will be added to the Catalog signature from the base model. Fact Thumbnails did not exist in the base model, and is simply added as a new fact in the superimposed model. Figure 30 shows instead the module for feature Categories, where catalogs are now comprised by categories rather than individual products. A new signature Category is introduced, as well as a new field category associating each product with some category. However, in this feature products are 67 3.2. Modeling in Feature-oriented Design refines module ecommerce sig Catalog { thumbnails : set Image } fact Thumbnails { all c:Catalog | c thumbnails in (catalog c) images } Figure 29: Feature Thumbnails of the e-commerce catalog in FeatureAlloy. refines module ecommerce sig Product { catalog : set Catalog, category : some Category } fact NoCatalogs { no catalog } sig Category { inside : one Catalog } Figure 30: Feature Categories of the e-commerce catalog in FeatureAlloy. no longer associated directly to catalogs, which would ideally result in the removal of field catalog of Product . This is however impossible in FeatureAlloy, where refinements do not allow the removal of fields. A workaround is to override the existing field with another with a looser multiplicity set , and then add an extra fact NoCatalogs saying that there is no catalog in the model. Note however, that this does not actually remove the field from the model but only forces it to be empty. In fact, although this is not the case in our example, the user would have to override every element of the base model where field catalog was called, as they would still be considered with a permanently empty catalog. As already pointed out when presenting fSMV, feature interaction in composition-based approaches often requires additional derivative features to solve conflicts. The two features we just presented in fact interfere with each other: fact Thumbnails retrieves thumbnails from all products associated with a catalog, which is no longer valid when categories are considered, since images must be indirectly retrieved through categories. Figure 31 denotes such a derivative feature, that should be considered when both Thumbnails and Categories are selected, overriding the original Thumbnails fact with one considering categories. 68 3.2. Modeling in Feature-oriented Design refines module ecommerce fact Thumbnails { all c:Catalog | c thumbnails in (category inside c) images } Figure 31: Derivative feature for Categories and Thumbnails of the e-commerce catalog in FeatureAlloy. Likewise fSMV, the cons and pros of FeatureAlloy are those typically shared by composition-based approaches. Features can be developed in a modular and step-wise fashion. However, the final model is obtained by recursively applying refinement for the models selected by a user, so if features interact the result depends on the order of feature selection. As shown, refinements are incremental and code deletion is not supported. The workaround we implemented pollutes the code and is not manageable in more complex features. Moreover, solving feature interactions usually requires developing additional features to be merged after the interacting ones. Δ -modelling The Unified Modelling Language (UML) is a large and popular modeling language in software development for specifying, constructing, visualizing, and documenting products. However, the standard UML does not support the modelling of variability in system families because it was proposed to model a single system. Although we can use mechanisms such as specification and redefinition to model variability, it is not sufficient for the systems with large variability. Therefore, researchers have drawn their attention to feature-oriented extensions to UML both using compositional and annotative techniques. Here we present one such composition-based approach proposed for model-driven development, which can be applied to UML models. Δ -modelling (Schaefer,2010) is an approach proposed for step-wise refinement of models with variability. At each level of abstraction there is a core model and a set of Δ -models. Each Δ -model specifies a set of changes to the core model (additions, modifications, and removals of elements and relations) and is associated with a logic constraint to determine for which feature configurations this fragment is to be applied. In order to obtain a specific product configuration, the changes specified by the Δ -models are applied to the core model. Feature interactions may cause conflicts, for instance if the same element is removed and modified by different Δ -models occurring in the same feature configuration. Although we are not addressing this scenario, the authors show that when considering multiple abstraction layers, refining 69 3.2. Modeling in Feature-oriented Design Figure 32: Core class diagram for e-commerce. Figure 33: Class diagram Δ-Model for Categories. Figure 34: Class diagram Δ-Model for Multiple. the core model and Δ -models and then configuring a product, commutes with first configuring a product and then refining it. As an example, we present a possible specification of the class diagram of the e-commerce catalog example, along with a few features. This amounts essentially to the signature and field declarations of the Alloy model, since the approach does not consider additional constraints, e.g. in OCL. Figure 32 shows the core class diagram of the base system, declaring products, catalogs and images, as well as their associations. Two Δ -models are then presented in the graphical style proposed in (Schaefer,2010), one for feature Categories in Fig. 33 and another for feature Multiple in Fig. 34. The logic conditions on the top-right corner of the diagram determine the application condition of the Δ -model. The Δ -model for Category adds the Category class (denoted by the + annotation) and modifies Product and Catalog ( ∗ annotation) by removing the catalog association ( − annotation) and adding the category one. The Δ -model for Multiple modifies the association between products and categories, allowing many-to-many relationships. The level of granularity of approaches for conceptual models is often finer than those for models with additional constraints, such as fSMV or FeatureAlloy. For instance, recall that we were not able to remove the field catalog in FeatureAlloy, while Δ -models may remove arbitrary elements. Another difference from those approaches is the relaxation of the one-to-one mapping between models and features, which in Δ -modelling is determined by feature presence conditions, which enables, for instance, the solving of feature interactions without explicitly creating a derivative feature. 70 3.2. Modeling in Feature-oriented Design 3.2.3 Annotation-based Languages Annotative approaches directly mark parts of the code with constraints over the features, for example, feature expressions. This is more practical than the composition-based approach for coding. For instance, #ifdef and #endif statements of C/C++ style preprocessors are traditionally used to encode variability in an ad hoc manner. These directives are used to control the inclusion of the code that belongs to the selected features or the exclusion of the code from the deselected ones. However, such annotation style obfuscates the code and makes it hard to understand and maintain. Likewise composition-based approaches, many annotation-based approaches extend existing languages, in this case with feature annotations. fPromela (Cordy et al.,2013) extends Promela by introducing a feature variable over which transitions can be guarded; FMs, provided in TVL, are also integrated in subsequent analysis. Cordy et al. (2012) proposed feature timed automata – timed automata annotated with feature constraints – accompanied by an input language that extends HyTEC; FMs are also provided in TVL. Besides the composition-based extension already mentioned, Sabouri and Khosravi (2013) also proposed an annotative extension for the actor-based Rebeca language, where entities are annotated with application conditions. CL4SPL (Gnesi and Petrocchi,2012) and FLan (ter Beek et al.,2013) are annotation-based approaches proposed in the context of process algebras and implemented in Maude. There is considerable work on supporting variability modelling in conceptual modelling, namely focusing on UML-like models (see, for instance, (Jézéquel,2012;Reinhartz-Berger and Sturm,2014)). Approaches mostly propose lightweight extensions to UML using profiles – sets of stereotypes, tags and constraints – rather than actually extending the UML meta-model. A stereotype extends the vocabulary of a profile, defining how existing UML metaclasses can be extended. Tags are the specific properties defined for each stereotype, which are assigned values for stereotyped elements. An advantage of the use of standard extension mechanisms is the usage of the UML meta-model and its corresponding tools without any adaptation. Several of these approaches, however, do not view features as first-class artefacts, rather just annotating certain elements as variable and enforcing restrictions on their selection. For instance, Gomaa (2000) proposed a method to use predefined UML stereotypes to model variability in class diagrams. The «Kernel» and «Optional» stereotypes are used to represent commonality and variability in system families. Features are interpreted as optional elements that always appear together. Nonetheless, there are still several approaches that explicitly consider FMs in the process. FeatuRSEB (Griss et al.,1998) includes a method to implement FD notation. Each feature node is implemented as a class with a stereotype «feature» and a feature name. An optional attribute is used to 71 3.2. Modeling in Feature-oriented Design indicate the kind of features, rationale, and notes. Use case diagrams are then merged into a single model with variation points denoting alternatives and «trace» abstractions used to map back to the FM. Clauß (2001) proposed to use the «variationPoint» and «variant» stereotypes in classes, components, packages, collaborations, and association elements. The «variationPoint» is used to describe the UML elements containing the variability and the «variant» specifies the alternatives to bind those variation points. The dependencies between variants are described by the «mutex» or «require» stereotypes. The FM follows the approach from (Griss et al.,1998), and variation points are connected to features using the «trace» abstraction. In (Robak et al.,2002) variable features in component and activity diagrams are specified by a new stereotype «variable» and with a tagged value named feature that maps back to a feature in the FM. In addition, variables can be annotated with further information to support choosing variants. Czarnecki and Antkiewicz (2005) propose fmp2rsm, connecting FMs specified in FeaturePlugin (Antkiewicz and Czarnecki,2004) with UML models. Here, elements from class diagrams and activity diagrams can be annotated stereotypes representing presence conditions (propositional formulas over features) or meta-expressions (to compute feature-dependant values). In SMarty (Junior et al.,2010), besides «variationPoint» and «variant» stereotypes (the latter specialized into variants with additional restrictions imposed), a «variability» stereotype for comments is also introduced, which contains information regarding a feature. Use case, class and component diagrams are annotated with variability annotations, and the traceability between variation points and features registered. In COVAMOF (Sun et al.,2010) class, activity, sequence, and deployment diagrams are also annotated with «variationPoint» and «variant» stereotypes, and a Variation point Interaction Diagram (an extended UML class diagram) relates variation elements with features, here provided in an FM encoded in XVL. Devroey et al. (2012) propose SDVA, UML-like state diagrams annotated with feature constraints. In the remainder of this section we present in more detail two annotation-based approaches that we feel are most relevant to the work developed in this thesis, namely fPromela for dynamic modelling and fmp2rsm for conceptual modelling. fPromela The fPromela language (Cordy et al.,2013) is a feature-oriented extension of Promela (Holzmann,2003), a well-known formal modeling language used by the model checker SPIN. The syntax of fPromela is almost the same as Promela specification language. The key elements in fPromela are processes that describe behaviours of single units in the design. Such processes are specified with the proctype keyword. A 72 3.2. Modeling in Feature-oriented Design process is either declared active from the start or activated by another process. If several processes are active, their executions are interleaved, and communication performed through shared variables or explicit channels. Like Promela, fPromela supports five basic data types declared with keywords int , short , bit , byte , and bool . A collection of variables can also be declared using an array. The keyword mtype allows the introduction of symbolic values, that is, enumerated types. Control flow can be introduced, for instance, by do loops (which are only interrupted by break statements) or if statements. Their bodies contain several options , declared by a double colon ( :: ). During execution, an option is non-deterministically chosen from those evaluating to true. fPromela extends Promela by allowing the user explicitly declare features and then introduce guards over them to control the behaviour of processes. All features must be declared with a new special type features , which generally contains a Boolean field for each possible feature (although multi-features and numeric features are also supported). A feature variable is then declared with this type, which can be called in feature expressions. These expressions are used to guard statements using gd blocks. Feature expressions may only use feature variables or the else keyword, and this is the only place where features may occur. A product can execute a statement if and only if it satisfies the expression that guards it. FMs in TVL are provided to the analysis tool, SNIP, restricting which values can be assigned to the feature variables. Analysis itself is performed by FTS model checking (see Section 3.3) or by projecting and model checking each product individually. Assertions to be checked are written in feature LTL (see Section 3.3). As an example, consider the specification of the vending machine example in fPromela in Fig. 35. Three features are declared in the features type, Cancel, Free and MultiSelection. A feature variable f is declared with this type. The valid states of the state machine are declared as an mtype . The behaviour of the state machine is then encoded in the process vending , which starts by initializing the variables and then entering a do loop. Each option of the loop tests the current State and assigns it a succeeding value. When these transitions depend on the selected features, guarded conditions are introduced in gd blocks depending on the value of feature variable f . Recall that if more than one of the options is true, e.g., when state is Selected , the choice will be non-deterministic. Since only transitions may be annotated with feature expressions, other elements, such as variable cnt for MultiSelection, must exist in every configuration. Assertions are not integrated in the model but rather passed as parameters of the model checking tool. For our example, we could check whether every time the machine is in the selected state it will eventually reach the ready state as follows. $ ./snip -check -fm fm.tvl -filter 'Cancel' \ -ltl '[] (State == Selected -> <> State == Ready)' -vending.pml 73 3.3. Analysis in Feature-oriented Design As mentioned above, a simple and commonly used approach to SPL model checking is the enumerative method that verifies each variant individually. In this case, all products are projected to obtain normal transition systems and enable the application of standard model checking algorithms. This method does not take advantage of the commonality between different variants and is in principle highly inefficient due to the potential exponential number of variants. Consider, for example, the fLTL property [¬𝑓] G ( Paid → F Served ) . To apply the enumerative approach to model check this formula one would first project the FTS to all products that satisfy feature expression ¬𝑓 , and then apply a standard LTL model checking algorithm to verify if formula G ( Paid → F Served ) is true in all the obtained transition systems. In this case we have two variants that satisfy the feature expression, namely the products without or with the possibility of cancelling a selection. The respective projected transition systems are presented in Figs. 39a and 39b, respectively. In this case the formula does not hold in the second transition system, being the violating product {𝑐} with a counter-example path that cycles indefinitely through states Ready , Paid , Selected , and Done. (a) (b) Figure 39: Projected transition systems for the vending machine. In (Classen et al.,2010,2012) a semi-symbolic model checking algorithm was introduced to perform amalgamated analysis of FTSs (for both the simple model checking problem and the extended one that returns counter-examples for all violating products). The algorithm relied on a generalization of the explicitstate Depth-First Search used in model-checking normal transition systems, but where visited states are marked with feature expressions instead of Boolean flags. This algorithm was implemented in the model checking tool SNIP to verify fPromela models. This algorithm was shown to speed up considerably the model checking of properties when compared with the enumerative approach. For example, for an FTS with 9 features and 64 products it achieved average speedups of 3.5 Classen et al. (2010). Unfortunately, like all explicit-state model checking algorithms, this technique is prone to the state explosion problem. To mitigate this problem, an amalgamated symbolic model checking algorithm was later proposed for fCTL (Classen et al.,2011b,2014), and used to verify fSMV specifications. Essentially, this algorithm reduces SPL model checking to classic model checking and enables the usage of the standard symbolic model checker NuSMV. The idea is to enrich the state definition with Boolean variables to encode 80 3.4. Supporting Clone-and-own all the possible features, a technique denoted as feature lifting . The value of these feature variables is kept constant in all transitions, and the feature expressions associated with transitions in the FTS become guards defined over them. If a counter-example is obtained, the initial state of the feature variables is inspected to obtain a violating product. For our example, the verification of fCTL property [𝑐]EG ¬ Served could be done by model checking the amalgamated SMV model of Fig. 40. This symbolic SPL model checking technique can achieve order-of-magnitude speedups over the enumerative approach: in an fSMV model of an elevator system with 9 independent features (that is, 29 variants) the verification of some properties has only marginally faster then the enumerative approach, but for other properties it achieved speedups greater than 250 and up to 1000 (Classen et al.,2011b). As expected, the higher speedups occurred in true properties, for which all the variants had to be checked. However, the enumerative approach was competitive in some false properties, most likely in cases where most products yield a counter-example. MODULE main VAR f : boolean; c : boolean; State : Ready, Paid, Selected, Served, Done; ASSIGN init(State) := false; next(State) := case State = Ready & !f: Paid; State = Ready & f : Selected; State = Paid : Selected; State = Selected & c & f : {Ready,Served}; State = Selected & c & !f : {Done,Served}; State = Selected & !c : Served; State = Served & !f : Done; State = Served & f : Ready; State = Done : Ready; esac; CTLSPEC c -> EF !(State = Served) Figure 40: SMV model for the amalgamated verification of the vending machine example. 3.4 Supporting Clone-and-own A code clone is a piece of code fragment that occurs in multiple locations with the same or similar form. Usually, a clone appears when a developer copies a piece of code from one location to another and afterwards customizes the copy to address new requirements. This phenomenon, which is called clone- and-own occurs commonly in the software development process. Clones can be classified into 4 types according to their similarity, namely Type-1 to Type-4 clones (Bellon et al.,2007). The Type-1 clones are 81 3.4. Supporting Clone-and-own exact copies of each other. Everything is exactly the same in the two clones. The Type-2 clones subsume all Type-1 clones, but also allow slight modification, such as variable renaming. The Type-3 clones subsume all Type-2 clones but include bigger changes, such as adding or removing statements, to implement some product-specific requirements. The Type-4 clones, also called functional clones, implement similar functionality but have few or no code similarity. The clone-and-own technique is well-supported by versioncontrol systems, such as Git, via operations like forking, merging, and pull requests. Since clone-and-own offers a simple, intuitive, and time and cost-saving technique to develop new software variants, it is well accepted by industry as a way to develop SPLs (Dubinsky et al.,2013). However, clone-and-own leads to ad hoc product portfolios with multiple, yet similar, variants, with no explicit connections, which brings significant increase in the cost and effort of maintenance. In particular, changes such as bug fixes must be carefully synchronized in all variants. Unfortunately, reuse tracking in clone-and-own is typically embodied in the personal knowledge of the developer (Dubinsky et al.,2013), which further difficults change propagation between clones. In feature-oriented software design, the clone-and-own approach is also a simple way to create a new variant of a model in an SPL, and to explore the impact of different features while exploring the design of a software system. The basic idea is again to derive a new variant of a design by copying from an existing one and then adapting to accommodate the new requirements. Likewise to code, anecdotal evidence seems to indicate that clone-and-own is also common when developing software models (Störrle,2013). In particular, in Alloy this is a common approach, for example, in several of the case-studies that come pre-packaged in the Analyzer there are multiple variants that share a great percentage of code. Some of these case-studies will be used in the Chapter 6 to evaluate the proposed clone migration technique. 3.4.1 Migrating Clones into an SPL Maintenance of SPLs developed with clone-and-own is a big challenge. As the number of clones grows and differences between their implementations increases, it becomes harder to perform many of the tasks needed in SPL engineering, for example, keeping track of changes made to each variant and of which features are shared between specific clones, reconcile changes, or derive new variants. A good way to solve this maintainability problem is to migrate (by merging) all variants into a single SPL model, where the common parts of the variants are factored out and implemented only once. This is also known as an extractive approach to SPL engineering. With this single model, changes of the systems only need to be 82 3.4. Supporting Clone-and-own implemented once, which provides significant benefits for management and synchronization, with minimal workload in the subsequent maintenance and evolution of the design. Many techniques have been proposed to migrate product variants into managed SPLs, as detailed in the survey conducted by Assunção et al. (2017). Most of these techniques work at the code level, and only a few have been proposed specifically for design models (although many techniques developed for object-oriented programs could in principle be adapted for models such as UML class diagrams). In this section we review a couple of techniques that have been specifically developed or applied to design models. Rubin et al. (2015) proposed a high-level approach based on seven conceptual operators that can be composed to implement several complex development activities related to SPL engineering, namely migrating clones into an SPL, in this work denoted as merge-refactoring . These operators can be applied to all possible artifacts such as requirements documents, design models, source code, and so on, and the authors illustrate the technique by applying it to transition systems, merge-refactored to a single model akin to an FTS. The seven proposed operators are: findFeatures that identifies a set of features in a given variant; findFeatureImplementation that locates the implementation artifacts of a given feature in a variant, thus establishing a trace between features and their artifacts; dependsOn?that checks if one feature requires another in a given variant; same? that determines whether the functionality described by one feature in one variant is consistent with the functionality described by another feature in a possibly different variant; interact? that checks whether the combining functionalities described by a set of features would alter the behavior of one or more of those functionalities; merge that combines several input variants into a single system; this operator has two parameters: matches , that specifies which artifacts are considered similar and should be combined in the resulting system, and resolution that indicates how to resolve disagreements and interactions between the input features (for example, keep both implementations as separate functionalities or override one feature implementation by the other); reorganize that improves the structure of a system (either a single variant or a combined SPL after merge) by refactoring, without modifying its behaviour. 83 3.4. Supporting Clone-and-own sig Product { catalog : some Catalog, images : set Image } sig Image {} sig Catalog { thumbnails : set Image } fact Thumbnails { all c:Catalog | c thumbnails in (catalog c) image } pred Scenario { some Product images } run Scenario for 2 Figure 41: Clone Alloy model of an e-commerce platform with thumbnails. These operators can be implemented and composed in many ways to achieve different SPL engineering tasks. The implementation of the operators is left open and is highly dependent on the kind of targeted artifacts and systems. Next we will illustrate this technique using an Alloy implementation of the e-commerce example, possibly obtained by clone-and-own, with the goal of merging it into a single ad hoc SPL Alloy model. One of the clones will be the base model of e-commerce presented in Fig. 28. Suppose this model was cloned and adapted to implement a variant that also supports thumbnails, originating the clone presented in Fig. 41. As proposed in (Rubin et al.,2015), to migrate these clones into a single model, we can start by identifying the features and the respective implementation in each variant with findFeatures and findFeatureImplementation . In our case we could, for example, assume that each signature corresponds to a possible feature, with the respective declaration as implementation artifact. Then, for each pair of features in a variant, dependsOn? should be used to identify require relationships. In our example, we could assume that one feature requires another if the fields declared in the former signature mention the latter. Then for each pair of features in different variants operator same? should be used to identify if two features are similar, for example, we could consider they are similar only if the respective signature declaration is literally identical. Then, possible interactions are detected with interact? . To implement this operator we could consider the existence of any additional facts, such as Thumbnails , to possibly cause interactions between the implementation of two variants. The witnesses collected by these two operators are then fed to the merge operator, namely the features identified by same? will be passed on to the matches parameter, leaving only one implementation of the respective signature in the merged model, and for those that disagree or interact the respective implementation could be kept separate, for example 84 3.4. Supporting Clone-and-own abstract sig Feature {} lone sig ProductImages, CatalogEcommerce, CatalogThumbnails extends Feature {} fact dependsOn { some CatalogEcommerce implies some ProductImages some CatalogThumbnails implies some ProductImages } sig Product { catalog : some CatalogA+CatalogB, images : set Image } sig Image {} sig CatalogA {} sig CatalogB { thumbnails : set Image } fact Disagreements { some CatalogEcommerce iff no CatalogThumbnails no CatalogEcommerce implies no CatalogA no CatalogThumbnails implies no CatalogB } fact Thumbnails { some CatalogThumbnails implies all c:CatalogB | c thumbnails in (catalog c) image } pred Scenario { some Product images } run Scenario for 2 Figure 42: Possible result of merging clones with the approach proposed by (Rubin et al.,2015). declaring additional signatures to distinguish the implementations in different variants, and making their existence conditional to the presence of atoms identifying the respective features. Finally, the reorganize operator could run an algorithm to detect atomic sets of features, to simplify the encoding of the FM. A possible resulting Alloy model is presented in Fig. 42. Rubin and Chechik (2012) proposed a step-wise merge-refactoring operation, denoted merge-in , that can be used for migrating cloned models to an annotative SPL model. In this work, models are trees of typed elements, each with an id and a role that defines the relationship with its parent. For example, in an UML statechart, possible types for model elements are state, transition, or a reference to a state. As for roles, for example, elements of the latter type can either be the source or target of the parent transition. Each model element can further be annotated with the features where it is present. Central to this technique is the operation of model merging , which is divided into three steps: compare, match and compose. The compare operation is used to determine the similarity degree between pairs of model elements. The similarity degree is a number between 0 and 1, with 1 representing identical 85 3.4. Supporting Clone-and-own elements and 0 meaning the two elements have no similarity. The match operation detects pair of elements that should be later considered similar in the merge step. The merge function puts the information in two models together, keeping a single copy for for matched elements. The compare operation between two model elements should take into consideration their types and roles in the model, as well as a weighted sum of the similarity of their sub-elements. Elements with different types or roles should always have similarity 0, and different weights can be chosen by the user for the different roles. The implementation of the match operation is based on thresholds: for each type a different threshold can be defined and pairs of elements whose comparison yields a value equal or higher than that threshold are considered similar. The merge function returns a model that contains all elements of the input models, with matched elements unified and appearing in the resulting model only once. The merge-in operation merges a product model with an annotative SPL model. The idea is to iterate this operation once per clone product, starting with an empty SPL model, and adding clones one by one until the final merged SPL model is obtained. As for the features of the SPL, different products are considered as distinct features. Hence, the merge-in operation will just add a new alternative feature to all existing features already in its FM. Then, the input product model is merged with the existing SPL model, and its elements are annotated with the respective feature. The authors proved that this technique is a behavior-preserving product line migration strategy and that only the original model clones can be projected from the merged SPL. However, by varying the compare and match parameters, as well as the order in which input models are combined, the resulting SPL model can be quite different. Although all possible results are correct and semantically equivalent, not all may be equally desirable. As such, Rubin and Chechik (2013) extended this technique to allow the user to specify a desired quality metric for the outcome, which is then used as an objective function to automatically explore different alternatives (until a specific desired quality is reached or a maximum number of alternatives is explored, after which the best alternative is return). Possible quality metrics are, for example, model size or the percentage of common elements in the resulting model. The ModelVars2SPL technique (Assunção et al.,2020) was proposed for automatically extracting an FM and an annotative SPL model, denoted Product Line Architecture (PLA), from existing UML class diagram variants. The input of ModelVars2SPL is a set of variants, each of which consists of a UML class diagram describing the structure of the variant and a feature set represent the configuration of features provided by the variant. The extraction proceeds in four steps: 1. Identify feature traceability, i.e. which elements implement each feature. This is done by analyzing the overlaps between the model elements and feature sets of different variants. This step outputs 86 3.4. Supporting Clone-and-own the traceability links between model elements and features and a dependency graph that represents the relationship between features. 2. Apply reverse engineering, using a multi-objective search-based technique, to obtain an FM that best represents the feature sets and that respects the dependency graph obtained in the previous step. 3. Apply a search-based technique for model merging the various UML diagrams into a single model that contains all possible model elements present in the variants. 4. Graft variability annotations in the merged class diagram obtained in the previous step in order to produce a PLA. Variability annotation is done by adding a UML comment to each model element. All these techniques focus only on structural elements of the design, for example classes or relationships, and none addresses additional constraints, where variability can occur with finer granularity. When illustrating the technique proposed by Rubin et al. (2015) with our running Alloy example, we considered fact Thumbnails as a whole unit: it is not clear how to apply that technique (or the others) to merge, for example, the two distinct versions of that fact that would exist in the clones implementing variants with and without feature Categories (merging in a way that highlights the commonalities between them). 87 4 COLORFUL ALLOY In this chapter we propose an extension of the popular Alloy specification language and its Analyzer to support feature-oriented software design. As we have seen in the previous chapter, most techniques for feature-oriented software development fall into one of two categories: compositional approaches, that implement features as distinct modules and use some sort of module composition technique to generate a specific software variant; and annotative approaches, that implement features with explicit (or sometimes implicit) annotations in the source code, that dictate which code fragments will be present in a specific variant. The former are well suited to support coarse-grained extensions, for example adding a complete new class to implement a particular feature, but not to support fine-grained extensions, for example adding a sentence to a method or change the expression in a conditional, to affect the way a code fragment works with different features (Kästner et al.,2008). Annotative approaches are much better suited for such fine-grained variability points. Unfortunately, as we have also seen, explicit support for feature-oriented design in formal methods, providing a uniform formalism for feature, architectural, and behavioral modeling as advocated for SPL engineering (Schaefer and Hähnle,2011), is still scarce. Support for features in model checking has been proposed, namely fSMV (Plath and Ryan,2001) and fPromela (Classen et al.,2012). For structural design, a compositional approach has been proposed to explicit support features in Alloy (Apel et al.,2010). Typically, modeling and specifying in Alloy is done at high levels of abstraction, and adding a feature can require only minimal and very precise changes (e.g., adding one new relation to the model or changing part of the specification of a desired property). Compositional approaches such as the one proposed by Apel et al. (2010) are not well suited for these fine-grained extensions. Our Alloy extension addresses precisely this problem, proposing an annotative approach to add explicit support for features to Alloy and its Analyzer. A classic annotative approach for source code is the use of #ifdef and #endif C/C++ compiler preprocessor directives to delimit code fragments that implement a specific feature. Unfortunately, such annotation style obfuscates the code and makes it hard to understand and maintain, leading to the well- 88 4.1. The Background Color Approach known #ifdef hell (Feigenspan et al.,2013). To alleviate this problem, while retaining the advantages of annotative approaches, Kästner et al. (2008) proposed to annotate code fragments associated with different features with different background colors, which was later shown to clearly improve SPL code comprehension and be favored by developers (Feigenspan et al.,2013). Given these results, we propose to use such annotative technique to support features in Alloy. Our Colorful Alloy extension allows users to annotate model and specification fragments with different background colors denoting different features 1 , and run analysis commands to verify either a particular variant of the design, or several variants at once, simplifying the detection of feature combinations that may fail to satisfy the desired specification. To the best of our knowledge, this is the first annotative approach for feature support in a formal method geared towards structural design. The next section gives a detailed description of the color background approach, first proposed by Kästner et al. (2008), and which inspired the development of Colorful Alloy. Section 4.2 formally presents the syntax of the new language extension, and Section 4.3 presents an example of proactively designing an SPL with Colorful Alloy. Section 4.4 presents its typing rules, and Section 4.5 its semantics. Finally, Section 4.6 presents a technique to perform multi-variant analysis, inspired by the feature lifting technique used proposed by Classen et al. (2011b,2014) to model check fCTL. 4.1 The Background Color Approach The background color approach was proposed by Kästner et al. (2008), as a mechanism to improve SPL code comprehension. The idea is to annotate the code fragments belonging to different features with different background colors. In case a code fragment is associated with multiple features (for example code within nested preprocessor #ifdef statements), the background colors associated with the respective features are mixed. The code snippet presented in Fig. 43 illustrates how background colors can be used to highlight feature code. This is an example where #ifdef preprocessor directives are used to annotate the code of different features. The code associated with feature HAVE_QUEUE (l. 5–16) is annotated with the yellow background color, while the code associated with feature DIAGNOSTIC (l. 12–14) is annotated with orange. The latter code is nested inside feature HAVE_QUEUE, so orange is the result of mixing the color yellow from feature HAVE_QUEUE with the red color that would be used to annotate code belonging only to feature DIAGNOSTIC. Notice also, that the same color is used to annotate code in the #ifndef and #else branches of feature HAVE_QUEUE, because both pieces of code are relevant for that feature: 1 Unlike the technique proposed by Czarnecki and Antkiewicz (2005), where different colors represent different presence conditions. 89 4.3. An Example of Proactive SPL Design Figure 47: Feature diagram of the colorful e-commerce specification. categories and multiple categories require the existence of categories. The FD of this reduced e-commerce SPL is depicted in Fig. 47, already depicting the feature numbers and the respective background colors. The Colorful Alloy specification of this example is shown in Fig. 48. To avoid deviating a lot from the standard Alloy syntax, Colorful Alloy does not explicitly support FMs, but the user can still restrict valid variants using normal facts. In Fig. 48 fact FeatureModel (l. 1–6) encodes the FD of Fig. 47, forcing feature 1to be selected in a variant whenever either 2or 3are. This is achieved by introducing an inconsistency in the model if either feature 2or 3is selected together with 1. Alloy does not have a keyword to denote False , but there are several expressions that can be used instead, for example some none . In line 3, this formula is annotated both with 2 and 1 , meaning that whenever feature Hierarchical is selected without feature Categories, that expression would be introduced in the model, thus creating an inconsistency. A similar technique is used in line 5 for forcing feature Categories to be selected when feature Multiple is as well. When proactively specifying a design with Colorful Alloy, we usually start by defining the base model, and incrementally add or remove elements (with the respective annotations) to support optional features. In this case, the base model declares signatures Product (l. 8–13), Image (l. 14), and Catalog (l. 15–17). It also declares fields images (l. 9), to relate products with their images, catalog (l. 10), to relate products with their catalog, and thumbnails (l. 16), to relate catalogs with the images that will illustrate them. This base model also includes a fact to force the thumbnails of a catalog to be images of one of its products (l. 19), and a command to search for a scenario where there are some products with images (l. 33–36). After specifying this base model, we proceed by specifying the changes introduced by feature 1 , allowing products to be classified in categories, instead of being directly placed in a catalog. This introduces two main changes: field catalog should be replaced by category , to relate products with one category, and a new signature Category should be declared. To remove catalog when feature 1 is selected it suffices to annotate it with 1 . On the other hand, the new field category should be annotated with 96 4.3. An Example of Proactive SPL Design 1fact FeatureModel { 2-- 2Hierarchical requires 1Categories 321some none 12 4-- 3Multiple requires 1Categories 531some none 13 6} 7 8sig Product { 9images: set Image, 10 1catalog: one Catalog 1, 11 13category: one Category 31, 12 13category: some Category 31 13 } 14 sig Image {} 15 sig Catalog { 16 thumbnails: set Image 17 } 18 fact Thumbnails { 19 1all c:Catalog | c.thumbnails in (catalog.c).images 1 20 1all c:Catalog | c.thumbnails in (category.( 2inside 2+2^inside 2).c).images 1 21 } 22 23 12sig Category { 24 inside: one Catalog 25 }21 26 12sig Category { 27 inside: one Catalog+Category 28 }21 29 12fact Acyclic { 30 all c:Category | c not in c.^inside 31 }21 32 33 pred Scenario { 34 some Product.images and 1all c:Category | lone category.c 1 35 } 36 run Scenario for 10 37 38 assert AllCataloged { 39 2all p:Product | some (p.category.^inside & Catalog) 2 40 } 41 check AllCataloged with 1,2for 10 Figure 48: E-commerce specification in Colorful Alloy. 1 to force its inclusion with this feature. Similarly, the new signature Category declaration should be annotated with 1 . Inside this signature we should also declare the new field inside , that relates it to the respective catalog. After this changes, the declaration of these signatures would look as follows. sig Product { images: set Image, 1catalog: one Catalog 1, 1category: one Category 1 } 97 4.3. An Example of Proactive SPL Design 1sig Category { inside: one Catalog }1 Fact Thumbnails also needs to be adapted with the introduction of this feature, so that products are retrieved indirectly from the categories of the catalog. To fetch the products inside a category c , instead of expression catalog c we should use category inside c . As such, we could adapt this fact by annotating the initial constraint with 1 and adding the new variant annotated with 1 , as follows. fact Thumbnails { 1all c:Catalog | c.thumbnails in (catalog.c).images 1 1all c:Catalog | c.thumbnails in (category.inside.c).images 1 } Notice that we could alternatively have used finer grained annotations, to pinpoint more precisely where the changes need to be made. For operators with a clear neutral element, their branches can also be annotated by features in Colorful Alloy, so we could have specified the above fact as follows. fact Thumbnails { all c:Catalog | c.thumbnails in (1catalog.c 1+1category.inside.c 1).images } As for our example scenario, we might want to add a extra restriction to variants where categories are present, for example forcing all products to have different categories, by annotating the respective expression with 1 (Fig. 48, l. 34). Having specified the changes introduced by feature 1 , we can specify the adaptions needed for the other features. Colorful Alloy allows two signatures or fields with the same identifier to be declared, as long as they have disjoint feature annotations. For example, the multiplicity of field category should change when feature 3 is selected, to allow a product to belong to multiple categories. To do so, in Fig. 48, two alternative declarations of this field are present which, depending on whether 3 is selected, assign exactly one (l. 11) or multiple (l. 12) categories to a product. Also, depending on whether 2 is selected or not, the signature Category should declare a different field inside : without hierarchical categories, each category is inside exactly one catalog (l. 24), while with hierarchical categories each category is inside one catalog or another category, determined by the union Catalog+Category (l. 27). Of course, we could also have opted to have a single declaration for Category with the two alternative field declarations inside, as we did for Product and field category , but opted for this formulation to illustrate the possibility 98 4.4. Type Checking Rules of declaring multiple versions of the same signature. Hierarchical categories require an additional fact Acyclic (l. 29–31) that forbids cyclic inside fields by calculating its transitive closure. Also, fact Thumbnails must be adapted when hierarchical categories are introduced (l. 20), so that all categories directly or indirectly contained in a catalog are considered: this can be done with a very precise annotation that replaces inside by ^inside when feature 2 is selected. Notice that the run command on Fig. 48 has no feature scope imposed, meaning that the scenario can be run for any of the 5 valid variants (although with a slightly different behavior for variants with feature 1selected). To verify the correctness of the design for hierarchical categories, an assertion AllCatalogued can be specified (l. 38–40) to check whether every product is contained inside at least one catalog. The formula inside this assertion only makes sense when feature 2 is selected. Note that due to the restrictions on the FeatureModel fact, feature 1 will also be present, so also annotating this formula with 1will not change its presence condition. The feature scope of the respective check command (l. 41) is restricted to consider only the two relevant variants with 1 and 2 selected (namely, with or without feature 3 , corresponding to multiple categories). 4.4 Type Checking Rules The grammar of the language restricts which elements can be annotated, but additional type checking rules must be employed to guarantee consistent and analyzable colorful models. The Alloy type inference rules presented in Section 2.2.3 aim at discovering irrelevant expressions. These typically represent specification errors, but actually do not affect the semantics or prevent a model from being analyzed. In fact, the Analyzer allows the user to opt to consider these type errors as mere warnings, and proceed with the analysis even when they occur. There are however some type errors that cannot be treated as warnings and that are caught by a simpler type checking mechanism, not described in Section 2.2.3, namely arity errors, that can occur, for example, when a user tries to compute the union of two relational expressions of different arity. The type checking system we describe in this section aims at catching such kind of errors. In particular, for completeness, we also included arity type checking in the system. The Colorful Alloy type checking rules aim mainly at detecting three kinds of coloring issues. First, calls to identifiers (for example, signature or predicate names) must occur in a color context that guarantees its existence. For instance, signature Category of our running example, which is declared only when feature 1is selected, cannot be called in a context where 1is not guaranteed to be selected. For example, fact {some Category } should raise an error, since such paragraph would be included 99 4.4. Type Checking Rules decls(c,p1,…,p𝑖)=decls(c,p1)∪…∪decls(c,p𝑖) decls(c,𝑐p𝑐)=decls(c∪{𝑐},p) decls(c,module n[n1,…,n𝑘])=n1↦(∅,1)∪…∪n𝑘↦(∅,1) decls(c,open n[n1,…,n𝑘])=decls(c,p1,…,p𝑖),where p1,…,p𝑖are the paragraphs of n decls(c,[abstract] [m]sig n[extends n1]{ d1,…,d𝑖}[{e}])= n↦(c,1)∪decls(c,d1)∪…∪decls(c,d𝑖) decls(c,[m]sig nin n1+…+n𝑘{ d1,…,d𝑖}[{e}])= n↦(c,1)∪decls(c,d1)∪…∪decls(c,d𝑖) decls(c,𝑐d𝑐)=decls(c∪{𝑐},d) decls(c,n:e)=n↦(c,arity(e)) decls(c,fact {e})=∅ decls(c,pred n[d1,…,d𝑖]{e})=n↦(c,𝑖) decls(c,fun n[d1,…,d𝑖]:e1{ e2})=n↦(c,𝑖+arity(e1)) decls(c,run {e}[with [exactly]c0] [for s])=∅ decls(c,check {e}[with [exactly]c0] [for s])=∅ Figure 49: Collecting a typing context from declarations. in all possible variants and Category is not declared in all of them. This applies to calls in expressions, the class hierarchy (the parent signature must exist in every variant that the children do), and calls to predicates/asserts in run/check commands. Second, when multiple declarations of the same identifier exist, they must be guaranteed to have disjoint color contexts, so that only one such declaration exists in a particular variant. Thus, both declarations of Category are valid since contexts 12and 1 2 refer to distinct variants, but it would not be the case if, for instance, one of them was just annotated with 1 . Third, the nesting of negative and positive annotations of the same feature should be forbidden, since this conjunction of conditions is necessarily inconsistent (i.e., under 11 e 11 , e will never exist). This also applies to feature scopes of commands, where the presence and absence of a feature would allow no variant. The context of the type rules will be a mapping Γ from identifiers to the color annotation (a set of positive and negative feature marks) and arity of their declaration, and a color annotation c under which it is being evaluated. Since the same entity can be declared multiple times, as long as their color annotations are disjoint, Γ is actually a relation that associates declared identifiers with a set of pairs with color annotations and arities. We denote a singleton mapping as n↦(c,𝑘) , for an identifier n , color annotation c , and arity 𝑘 . The union of mappings can be done with ∪ , while denotes overriding. This context can be collected from a Colorful model using function decls defined in Fig. 49. For simplicity, this definition considers 100 4.4. Type Checking Rules only a kernel of paragraphs, namely commands that call predicates or assertions are not considered. Also, function arity used here is an oversimplification, since calculating the arity of an expression requires prior knowledge of the arity of other declared signatures and fields. In this definition (and in the typing rules presented later), p denotes a paragraph (or an open statement), d a declaration, n an identifier, m a multiplicity keyword, e an arbitrary expression (either a formula or a relational expression), c a color annotation (a set of feature marks), and 𝑖,𝑗,𝑘arities. A context Γ collected by decls is valid iff the color annotations of all declarations with the same identifiers are disjoint and agree on arity, that is ∀n0↦(c0,𝑖),n1↦(c1,𝑗)⋅𝑛0=𝑛1→⌈c0⌉∩⌈c1⌉=∅∧𝑖=𝑗 where ⌈c⌉ is a function that computes the set of all concrete variants that are valid according to c , taking into consideration only the features that used in the specification. For example, in the e-commerce example ⌈{ 1 , 2 }⌉={{ 1 , 2 , 3 },{ 1 , 2 , 3 }} , and the context collected from the model declarations would be {Product ↦({},1),images ↦({},2),catalog ↦({ 1 },2), category ↦({ 1 , 3 },2),category ↦({ 1 , 3 },2),…} The typing rules for paragraphs are presented in Fig. 50. The fact that a paragraph p is well typed in context Γ with color annotation c is denoted by Γ,c⊢p . The fact that a colorful model comprised by paragraphs p1…p𝑖 is well-typed is denoted by ⊢p1…p𝑖 . Imported modules must also be well-typed according to the same rules. The typing rules for paragraphs are mainly responsible for aggregating color annotations as we traverse the model, to be later used when type checking expressions, as well as detecting the third kind of issue described above, color annotations with the same feature occurring positively and negatively. For an arbitrary feature mark 𝑐 , ¬𝑐 converts between the positive and negative version. In Colorful Alloy commands are not annotated, their color context being instead defined by the feature scope. This scope is used to type check the expression inside the command. When the feature scope is exact, the respective color annotation must be expanded with the negation of all marks not present in it, which is done by function ⌊c⌋. For example, in the e-commerce example ⌊{ 1 , 2 }⌋={ 1 , 2 , 3 }. The typing rules for expressions is presented in Fig. 51 for a kernel of operators. The fact that an expression e of arity 𝑘 is well-typed is denoted by Γ,c⊢𝑘e (arity 0 denotes formulas). Again most rules just aggregate feature marks as the expression is traversed, detecting contradictory marks and checking 101 4.4. Type Checking Rules Γ=decls(∅,p1,…,p𝑖) Γ,∅⊢p1… Γ,∅⊢p𝑖 ⊢p1…p𝑖 Γ,c∪{𝑐}⊢p⊢𝑐,c Γ,c⊢𝑐p𝑐⊢c¬𝑐∉c ⊢𝑐,c Γ,∅⊢module n[n1,…,n𝑖]Γ,c⊢1n1… Γ,c⊢1n𝑖 Γ,c⊢open n[n1,…,n𝑖] Γ,c⊢𝑘1d1… Γ,c⊢𝑘𝑖d𝑖Γ,c⊢0eΓ,c⊢1n2𝑘1…𝑘𝑖>0 Γ,c⊢[abstract][m]sig n1[extends n2]{ d1,…,d𝑖}[{e}] Γ,c⊢𝑘1d1… Γ,c⊢𝑘𝑖d𝑖Γ,c⊢0eΓ,c⊢1n1… Γ,c⊢1n𝑗𝑘1…𝑘𝑖>0 Γ,c⊢[m]sig nin n1+...+n𝑗{ d1,…,d𝑖}[{e}] Γ,c∪{𝑐}⊢𝑘d⊢𝑐,c Γ,c⊢𝑘𝑐d𝑐Γ,c⊢𝑘e𝑘>0 Γ,c⊢𝑘n:e Γ,c⊢0e Γ,c⊢fact {e} Γ,c⊢1d1… Γ,c⊢1d𝑖Γ,c⊢0e Γ,c⊢pred n[d1,…,d𝑖]{e} Γ,c⊢1d1… Γ,c⊢1d𝑖Γ,c⊢𝑘e1Γ,c⊢𝑘e2𝑘>0 Γ,c⊢fun n[d1,…,d𝑖]:e1{ e2} Γ,c⊢0e⊢c Γ,∅⊢run {e}[with c][for s]Γ,⌊c⌋⊢0e⊢c Γ,∅⊢run {e}[with exactly c][for s] Γ,c⊢0e⊢c Γ,∅⊢check {e}[with c][for s]Γ,⌊c⌋⊢0e⊢c Γ,∅⊢check {e}[with exactly c][for s] Figure 50: Type rules for kernel paragraphs. 102 4.4. Type Checking Rules Γ,c⊢1none Γ,c⊢1univ Γ,c⊢2iden ∀c0∈⌈c⌉⋅∃n↦(c1,𝑘)∈Γ⋅c1⊆c0 Γ,c⊢𝑘n Γ,c⊢2e Γ,c⊢2^e Γ,c⊢2e Γ,c⊢2∼eΓ,c⊢0e Γ,c⊢0not eΓ,c⊢0e1Γ,c⊢0e2 Γ,c⊢0e1and e2 Γ,c⊢𝑘e1Γ,c⊢𝑘e2𝑘>0 Γ,c⊢0e1in e2 Γ,c⊢𝑘e1Γ,c⊢𝑘e2𝑘>0 ∈{&,+,−} Γ,c⊢𝑘e1e2 Γ,c⊢𝑖e1Γ,c⊢𝑗e2𝑘=𝑖+𝑗−2 𝑖,𝑗,𝑘>0 Γ,c⊢𝑘e1e2 Γ,c⊢𝑖e1Γ,c⊢𝑗e2𝑘=𝑖+𝑗 𝑖,𝑗>0 Γ,c⊢𝑘e1→e2 Γ,c⊢1e1Γn↦(∅,1),c⊢0e2 Γ,c⊢0all n:e1| e2 Γ,c∪{𝑐}⊢𝑘e⊢𝑐,c Γ,c⊢𝑘𝑐e𝑐 Figure 51: Type rules for kernel expressions. the arity. The most interesting rule is the one for identifiers, in the upper right corner. A reference to an identifier n is well typed in a context Γ and color annotation c if in all possible variants c0∈⌈c⌉ that identifier is declared. For example, in the e-commerce example, expression 1 some Category 1 is well-typed because either 1 2 Category 2 1 or 12 Category 21 is declared in all variants where 1 is selected. Unfortunately, this rule is too restrictive when the FM actually restricts the possible set of variants. For example, expression 2 some Category 2 would not be considered well-typed because in some variants where 2 is selected Category is not declared, for example, in variant { 1 , 2 , 3 } . However, this variant is not allowed by the FM of this example, since fact FeatureModel requires 1 to be selected when 2 is also selected. Thus, the rule implemented in the Colorful Alloy typing system is a bit more general, so that less spurious errors are returned. In particular, the model is first scanned to detect FM constraints with the shape csome none c , where c denotes a feature combination that will be considered forbidden. From these, the set 𝐹 containing all possible valid variants in the model is computed (five, in the case of our running example), and the typing rule for identifiers is adapted as follows. ∀c0∈⌈c⌉∩𝐹⋅∃n↦(c1,𝑘)∈Γ⋅c1⊆c0 Γ,c⊢𝑘n 103 4.5. Semantics ⟨p1…p𝑖⟩c≡⟨p1⟩c… ⟨p𝑖⟩c ⟨𝑐p𝑐⟩c≡{⟨p⟩cif 𝑐∈⌊c⌋ 𝜖otherwise ⟨module n[n1,…,n𝑖]⟩c≡module n[n1,…,n𝑖] ⟨open n[n1,…,n𝑖]⟩c≡open n[n1,…,n𝑖] ⟨[abstract][m]sig n1[extends n2]{ d1,…,d𝑖}[{e}]⟩c≡ [abstract][m]sig n1[extends n2]{⟨d1⟩c,…,⟨d𝑖⟩c}[{⟨𝑒⟩c}] ⟨[m]sig nin n1+...+n𝑗{ d1,…,d𝑖}[{e}]⟩c≡ [m]sig nin n1+...+n𝑗{⟨d1⟩c,…,⟨d𝑖⟩c}[{⟨𝑒⟩c}] ⟨𝑐d𝑐⟩c≡{⟨d⟩cif 𝑐∈⌊c⌋ 𝜖otherwise ⟨n:e⟩c≡n : ⟨e⟩c ⟨fact {e}⟩c≡fact {⟨e⟩c} ⟨pred n[d1,…,d𝑖]{e}⟩c≡pred n [ ⟨d1⟩c,…,⟨d𝑖⟩c] {⟨e⟩c} ⟨fun n[d1,…,d𝑖]:e1{ e2}⟩c≡fun n [ ⟨d1⟩c,…,⟨d𝑖⟩c] : ⟨e1⟩c{⟨e2⟩c} ⟨run {e}[for s]⟩c≡run {⟨e⟩c}[for s] ⟨run {e}with c0[for s]⟩c≡{ run {⟨e⟩c}[for s]if c0⊆⌊c⌋ 𝜖otherwise ⟨run {e}with exactly c0[for s]⟩c≡{run {⟨e⟩c}[for s]if ⌊c0⌋=⌊c⌋ 𝜖otherwise ⟨check {e}[for s]⟩c≡check {⟨e⟩c}[for s] ⟨check {e}with c0[for s]⟩c≡{check {⟨e⟩c}[for s]if c0⊆⌊c⌋ 𝜖otherwise ⟨check {e}with exactly c0[for s]⟩c≡{ check {⟨e⟩c}[for s]if ⌊c0⌋=⌊c⌋ 𝜖otherwise Figure 52: Paragraph projection. 4.5 Semantics The semantics of Colorful Alloy can be defined in terms of a projection operator, that extracts from a colorful model a plain Alloy model representing a concrete variant. Assuming that a colorful model is well-typed according to the rules presented in the previous section, and that all unique feature marks cthat are used in it have been collected in a color annotation c during that process (i.e., the features relevant for the specified family of models), an instance 𝑀 is valid in a colorful model 𝑚 iff there exists a variant c0⊆c such that 𝑀 is valid in ⟨𝑚⟩c0 , the projection of 𝑚 for variant c0 , according to the plain Alloy semantics defined in Section 2.2.2. 104 4.5. Semantics ⟨none⟩c≡none ⟨univ⟩c≡univ ⟨iden⟩c≡iden ⟨n⟩c≡n ⟨e⟩c≡⟨e⟩c ⟨e1e2⟩c≡⟨e1⟩c⟨e2⟩cif ∉{+,&,or,and} ⟨c1e1c1c2e2c2⟩c≡⎧ { { ⎨ { { ⎩ ⟨e1⟩c⟨e2⟩cif c1⊆⌊c⌋and c2⊆⌊c⌋ ⟨e1⟩cif c1⊆⌊c⌋and c2⊈⌊c⌋ ⟨e2⟩cif c1⊈⌊c⌋and c2⊆⌊c⌋ neutral(,arity(e1)) otherwise if ∈{+,&,or,and} ⟨all n:e1| e2⟩c≡all n : ⟨e1⟩c|⟨e2⟩c Figure 53: Expression projection. The projection of a model to a concrete variant c is defined in Fig. 52 and is rather straight-forward: basically it projects away paragraphs and declarations not relevant in that variant, namely those enclosed in an annotation 𝑐 that is not selected in c . The projection of expressions is also straight-forward and is defined in Fig. 53. Recall that only direct sub-expressions of binary operators with a neutral element can be annotated in Colorful Alloy. In this case, if both sub-expressions are to be projected out, the parent expression will be replaced by the respective neutral element, defined as follows. neutral(+,𝑎)=none →…→none ⏟⏟⏟⏟⏟⏟⏟⏟⏟ 𝑎 neutral(&,𝑎)=univ →…→univ ⏟⏟⏟⏟⏟⏟⏟⏟⏟ 𝑎 neutral(or,𝑎)=some none neutral(and,𝑎)=no none An example of this process can be seen in the projected Alloy model of the e-commerce colorful specification for the variant where only 1 and 2 are selected (the variant with hierarchical categories), that is presented in Fig. 54. In the colorful specification the FeatureModel fact consists of a conjunction of two annotated formulas, that encode the restrictions of the respective FM. None of these formulas should be included in the projected model, because their annotations are not part of the variant. As such, the (implicit) conjunction inside FeatureModel is replaced by no none , the respective neutral element, and will thus have no effect on the analysis. If instead we asked for the projection to the variant where only 105 4.6. Analysis pred Scenario { some Product images (F1 in Variant) implies (all c:Category_0+Category_1 | lone (category_0+category_1) c) else no none } run { Scenario } for 10 pred AllCataloged { (F2 in Variant) implies all p:Product | some (p (category_0+category_1) ^inside & Catalog) } check { (F1 in Variant and F2 in Variant) implies AllCataloged } for 10 Figure 58: Amalgamated translation of the e-commerce model from Fig. 48 (commands). 112 5 MERGING CLONED ALLOY MODELS WITH COLORFUL REFACTORINGS In this chapter we propose a refactoring approach for migrating a collection of plain Alloy models, possibly developed with the clone-and-own approach, into a single Colorful Alloy model. As mentioned in Chapter 3, modern software systems are often highly-configurable, effectively encoding a family of software products, and feature-oriented software development is the most successful approach proposed to support the development of such systems. In such a family-based development, maintenance is an important challenge, and refactoring is one of the key activities used to improve the internal quality during software evolution. A refactoring is a kind of transformation that changes the structure of the source code while preserving its external behavior. Variability annotations introduce an additional complexity layer in the development process, making refactoring crucial to keep software maintainable and understandable. However, classical refactoring is not well-suited for feature-oriented development, since it does not take into account the behavior of a SPL as a whole. SPL refactoring must consider all variants, in particular, the set of possible variants and the behavior of each variant must be preserved (Schulze et al.,2012). Furthermore, typical code refactoring laws do not suffice for formal software design, since most refactoring laws are typically too coarse-grained, focusing on constructs such as entire functions or classes. Given the high level of abstraction on which design is performed, to improve the quality of a specification one might need also fine-grained refactoring laws, for example, affecting just part of an assertion. As discussed in Section 3.4, one of the standard ways to implement multiple variants in a SPL is through the clone-and-own approach. However, as the cost to maintain the clones and synchronize changes in replicas increases, developers may benefit from migrating (by merging) such variants into a single feature-oriented artifact. In fact, even when feature-oriented development has been fully adopted, it is useful in practice to switch between the two perspectives (Rubin et al.,2015). Fully-automated approaches for clone merging (e.g., the technique proposed by Rubin and Chechik (2012), discussed in Section 3.4) assume a quantifiable measure of quality to guide the process, but such measure is not easy to define 113 5.1. Migrating Code Clones into an SPL with Refactoring when the goal is to merge code, and even less so when the goal is to merge formal abstract specifications. Alternative techniques where the user still somehow controls the merging process have been proposed. In particular, Fenske et al. (2017) have proposed a migration strategy where variant preserving refactorings were defined to support the user in performing step-wise, semi-automated transformations, a technique that inspired our own proposal for migrating plain Alloy clones into a single Colorful Alloy model. In this chapter we start by reviewing the proposal of (Fenske et al.,2017) in Section 5.1. Then, in Section 5.2 we propose a catalog of variability-aware refactoring laws for Colorful Alloy, covering all model constructs – from structural declarations to axioms and assertions – and granularity levels – from whole paragraphs to formulas and expressions. Then, in Section 5.3 we show how these refactorings can be used to migrate a set of legacy Alloy clones into a colorful SPL using an approach similar to the one of (Fenske et al.,2017). Fine-grained refactoring is particularly relevant in this context: design in Alloy is done at high levels of abstraction and variants often introduce precise changes – refactoring only at the paragraph level, likewise the refactorings proposed by Gheyi (2007) (and presented in Section 2.3), would lead to unnecessary code replication and a difficulty to identify variability points. Finally, in Section 5.4 we also introduce an automatic merging strategy that composes together several refactorings, and that can be used to simplify the task of the user when migrating clones to a managed SPL design. 5.1 Migrating Code Clones into an SPL with Refactoring Fenske et al. (2017) propose a technique for migrating cloned product variants into an SPL that relies on variant-preserving refactorings. This technique was applied to Java code clones, with the resulting SPL encoded using Feature-Oriented Programming (FOP) (Prehofer,1997), a composition-based technique where all code artifacts that implement each feature are modularized in different units, called feature modules . The composition technique used to derive a specific variant implementation allows feature modules being composed later to refine definitions introduced previously, namely by adding fields or methods, by adapting the behaviour of methods by calling the original implementation, or by completely overriding the previous definition. The process of the variant-preserving migration is shown in Fig. 59. Suppose we have 𝑛 product variants 𝑝1,𝑝2,⋯,𝑝𝑛 , possibly sharing a large amount of code, to be migrated into a single FOP SPL. In the first step, the process creates a trivial initial SPL whose FM contains 𝑛 features 𝑝1,𝑝2,⋯,𝑝𝑛 grouped in a single alternative relation, each of which representing a product. Furthermore, the source code of each variant becomes a separate feature module associated with the respective feature. This FOP 114 5.1. Migrating Code Clones into an SPL with Refactoring Figure 59: Clone migration process of (Fenske et al.,2017) implementation together with the FM entails 𝑛 different configurations 𝐶1,𝐶2,…,𝐶𝑛 each with exactly one of the features, and we can easily recover the original variant 𝑝𝑖 through configuration 𝐶𝑖 . This first step does not yield any improvement in reuse, but rather provides the basis for the subsequent iterative variant-preserving refactoring process. Then a step-wise refinement process is applied and repeated as often as needed in order to improve the quality of the SPL implementation. This process uses a combination of extractive and preparatory variant-preserving refactorings: the goal of the former is to move identical code fragments (including different elements, such as fields or methods) introduced by a set of features into a common one and higher up in the feature hierarchy, while the latter focus on aligning implementations with Type-2 clones (for example, identical methods with different names) so that extractive refactorings can be applied. Variantpreserving refactorings (Schulze et al.,2012) extend the notion of behavior-preservation to SPLs, ensuring that all potential products within an SPL remain compilable and keep their previous behavior, and that all configurations that were valid before the refactoring must remain valid afterwards. This behaviorpreservation notion allows the introduction of new variants as long as they do not affect the behavior of the existing ones. The key extractive variant-preserving refactoring used in this work is Pull Up to Common Feature, an extension to FOP of the Pull Up refactoring first introduced by Fowler (2018) for object-oriented code. The goal of the Pull Up refactoring is to move equal definitions of class members (for example, methods or fields) to a common super-class, thus reducing code clones. The goal of the Pull Up to Common Feature is similar, but the idea is to move equal definitions of class members up in the feature hierarchy (instead of up in the class hierarchy) from a set 𝐹𝑠 of source features {𝑓𝑠1,…,𝑓𝑠𝑛} to a single target feature 𝑓𝑡 . There are several versions of this refactoring, but we will detail here the version applied to methods, the Pull Up Method to Common Feature. Notice that this refactoring should be applied only to Type-1 clones, after the 115 5.1. Migrating Code Clones into an SPL with Refactoring common code has been consolidated in the initial SPL. Given a method 𝑚 and a class 𝑐 the goal is to create 𝑐 in 𝑓𝑡 (if it does not exist already) and define 𝑚 in that class, deleting all definitions of 𝑚 in the source features 𝑓𝑠∈𝐹𝑠. To be variant-preserving, this refactoring has several preconditions: 1. Each source feature 𝑓𝑠∈𝐹𝑠contains the class 𝑐with method 𝑚. 2. All fields and methods referred by 𝑚 must be defined in the target feature 𝑓𝑡 or in one of the features implied by it. 3. 𝑓𝑡 must be a concrete feature , that is, one containing code (instead of an abstract feature that is just used in the FM to organize other features, for example the parent feature of an alternative relation between concrete features). 4. If 𝑐already exists in 𝑓𝑡it must not declare 𝑚. 5. Any valid configuration that contains an 𝑓𝑠∈𝐹𝑠 must contain 𝑓𝑡 and vice-versa (the latter prevents 𝑚 from shadowing other definitions in features composed before 𝑓𝑡 in undesired configurations containing 𝑓𝑡but not one of the source features). 6. No valid configuration containing an 𝑓𝑠∈𝐹𝑠 may contain a 𝑓𝑑∈𝐹−𝐹𝑠 that contains a class 𝑐 with 𝑚 and that is composed after 𝑓𝑡 and before 𝑓𝑠 (to prevent 𝑚 from being overwritten or refined before 𝑓𝑠being composed). The most important issue with this refactoring is identifying the appropriate target feature 𝑓𝑡 , namely one that obeys the above preconditions. If all source features have a common parent, then that parent feature might be used as the target feature (if it satisfies all the preconditions), otherwise a new target feature can be created. In the latter case, first an appropriate parent feature 𝑓𝑝 is selected (required to satisfy only some of the pre-conditions but not all of them, for example it might not be concrete or not imply one of the source features) and then 𝑓𝑡 is created as a concrete optional child of 𝑓𝑝 . To fulfill precondition 5 a cross-tree constraint is created stating that 𝑓𝑡 is selected if and only if one of the source features is selected. For example, in Fig. 59 feature 𝑓1 could be the target feature created by the Pull Up Method to Common Feature to refactor a cloned method in features 𝑝1 and 𝑝3 , hence the new cross tree constraint 𝑓1↔ (𝑝1∨𝑝3) . The corresponding set of configurations also changes according to the new added features during the refactoring. For instance, configuration 𝐶1 is now changed to include both feature 𝑓1 and feature 𝑝1. As mentioned above, the Pull Up to Common Feature refactoring only applies to identical codes fragments from source code (Type-1 clones). For dealing with Type-2 clones, for example methods with the same 116 5.2. Refactoring Rules for Colorful Alloy implementation but distinct names, the preparatory Rename refactoring should used first, to enable the later application of Pull Up to Common Feature. One important thing in this refactoring step is to update all the references to the new name. Otherwise, compilation errors would shown up in variants that contain the feature of the element that was renamed. This clone migration process was implemented in Eclipse on top of other tools, namely FeatureIDE (Thüm et al.,2014), the Eclipse refactoring framework, and copy and paste detectors. The latter were used to implement Type-1 and Type-2 clone detection, to suggest potential applications of the Pull Up to Common Feature and Rename refactorings. The authors also implemented an automated migration strategy that just applies repeatedly the former refactoring to all detected Type-1 clones. They evaluated the migration process by applying it to five variants of Android games developed with Java with a high-percentage of cloned code (in total around 69% of the LOCs were identified as inter-feature code clones), by measuring the reduction in the total LOCs. Since the technique only considers Type-1 and Type-2 clones (meaning that methods with even very small differences in the implementation could not be refactored), the automatic migration strategy only achieved a reduction of 4.2% of the total LOCs, with an additional 15.8% reduction after applying preparatory Rename refactorings. In the final FM, 15 additional target features were created to group common code. 5.2 Refactoring Rules for Colorful Alloy This section proposes a catalog of variant-preserving refactorings for Colorful Alloy, complementing the non-variability-aware ones previously proposed for standard Alloy (Gheyi,2007), which were presented in Section 2.3. Although the main use of this catalogue will be in our clone migration technique, which is inspired by the technique described in the previous section, they can also be used to promote the quality and maintenance of Colorful Alloy models, while preserving the set of variants and their individual behavior. Although the general idea of our technique for clone migration is similar to the work of (Fenske et al.,2017), in the sense that we first migrate all clones into an initial trivially correct SPL which is then improved by variant-preserving refactorings, there are some key differences that justify our particular choice of refactorings, apart from the obvious ones that our technique applies to formal design instead of code, and targets an annotative approach, instead of a compositional one: • We will not consider alignment issues at all, assuming that names of entities that model the same concept in different variants have been previously made equal. The name alignment problem is mostly orthogonal to the migration problem: some automation can be provided to help with that, 117 5.2. Refactoring Rules for Colorful Alloy for example using clone detection tools, but mostly it is up to the user to decide when two entities are to be considered the same. For example, in the process proposed by Fenske et al. (2017), the automatic migration strategy did not include the Rename refactoring, which was left to the user to be applied. • However, we intend to address not only Type-1 code clones, but also Type-3 ones, namely to enable the merging of two entities (predicates, facts, etc) whose specification might differ. To that end we propose several refactorings that work on the formula and expression level, a feature that distinguishes our approach from other works, allowing finer variability annotations, as is common in feature-oriented design, particularly in the clone-and-own context where changes may be small. This also distinguishes our approach from that of (Gheyi,2007), where the proposed Alloy refactorings are coarse-grained. • Unlike the technique of (Fenske et al.,2017), our refactorings do not create new features nor change the FM (as was the case with the Pull Up to Common Feature refactoring). We believe domain analysis, where the variability is modelled (with FMs), should be an orthogonal (and prior) task to clone migration, and that the developer should be ultimately responsible for deciding which features exist and how are they related. As such, we will assume that prior to migration the final FM has been defined and each clone has already been labeled with the configuration (set of features) it implements. The refactoring laws for Colorful Alloy are presented in the form of an equation between two templates (with square brackets marking optional elements), following the style from (Gheyi,2007), under the context of a particular FM 𝐹 extracted from the model under analysis (as described in the previous chapter). Unlike in the refactoring laws of (Gheyi,2007), our templates can be matched to part of a model (and not the all model), meaning that the refactoring is just to be applied locally to that part. As long as the preconditions are met and the left or right templates matched, the refactoring can be applied in either direction. Also, our notion of equivalence is different: we do not consider only a subset of relevant signatures and fields, but all that are declared in the model. Throughout the section, 𝑐 and 𝑐 will denote a positive or negative annotation for feature 𝑐 , while 𝑐 will denote either a positive or negative annotation for 𝑐 ; moreover, 𝑐 will denote a (possibly empty) sequence of positive or negative annotations 1 . Models are assumed to be type checked when the rules 1 Essentially 𝑐 is just a different notation for c , as used in the previous chapter, the only difference being that the annotations in the former have a particular order while the latter is an unordered set. We believe that this alternative notation improves the readability of the refactoring laws presented in this section. 118 5.2. Refactoring Rules for Colorful Alloy are applied, so without loss of generality, in an expression 𝑐e𝑐 we assume that the features 𝑐 in the closing annotations appear in the reverse order as those in the opening annotations, that there are no contradictory annotations, and that only supported elements of the AST are annotated. We use ann to refer to any model element amenable of being annotated (possibly itself already annotated), exp and frm for expressions and formulas, respectively, n for identifiers, ds for (possibly-annotated) relation declarations, and scp for scopes. We assume that using the extracted FM 𝐹 (a set of configurations) we can answer simple questions about the FM, namely whether a particular set of features 𝑎 entails a particular feature set 𝑏, denoted by 𝐹⊧ 𝑎→𝑏, which is defined as follows. 𝐹⊧ 𝑎→𝑏iff ∀𝑐∈𝐹⋅ 𝑎⊆𝑐→𝑏⊆𝑐 A n n o t a t i o n L a w s The first set of rules we address manage the feature annotations which, as will be shown, are often useful to align annotations on elements to enable more advanced refactorings. They act essentially as the preparatory refactorings in (Fenske et al.,2017). Law 11 (Annotation reordering). 𝑎 𝑏 ann 𝑏 𝑎 =𝐹𝑏 𝑎 ann 𝑎 𝑏 This basic rule arises from the commutativity property of conjunctions, and allows users to reorganize feature annotations. Therefore, users can rearrange the order of marked features on elements as needed. For example, the field category declaration inside signature Product (Fig. 48, l. 11), marked with features 13 , could alternatively be declared as follows. 31category : one Category 13 Law 12 (Redundant annotations). 𝑎 𝑏 ann 𝑏 𝑎 =𝐹𝑎ann 𝑎 provided (↔)𝐹⊧ 𝑎→𝑏and ann ≠some none. This rule relies on the FM to identify redundant annotations that can be removed or introduced. In order to not affect the implicitly specified FM (from which 𝐹 is extracted) its application is forbidden for some none formulas. For instance, if the FM imposes 2 → 1 (as in our example), then whenever a 2 annotation is present 1 is spurious, and whenever 1 is present 2 is spurious. In an extreme case it 119 5.2. Refactoring Rules for Colorful Alloy can also be used to remove duplicated annotations, since trivially 𝑐→𝑐 . Similar rules are defined to manage the annotations in the feature scope of commands. In the e-commerce example, using this refactoring, the declaration of signature Category for variant 1 2 (l. 26–28) could be simplified as follows. 2sig Category { inside: one Catalog+Category }2 S i g n a t u r e L a w s The next set of refactoring rules manage signatures with shared presence conditions, including their merging. In particular, most refactorings from (Gheyi,2007), and others, to remove syntactic sugar constructs from signatures, must be adapted to the colorful context. Here we present a few as examples. Law 13 (Remove signature multiplicity qualifier). 𝑎[abstract]mlt sig n[ext]{⋯}𝑎== F 𝑎[abstract]sig n[ext]{⋯}𝑎 𝑎fact { mlt n } 𝑎 where mlt ∈{lone,one,some}. This law removes multiplicity of signatures with an additional fact constraint. This rule is similar to that of normal Alloy, with the only difference being that the same feature expression as the original signature needs to be marked on the additional fact which indicates that the fact only applies when the original signature is selected. This rule is very useful as a preparatory refactoring in merging cloned variants, since signatures with the same identifier but different multiplicity often occur in systems developed with clone-and-own approaches. Using this law we can then remove these multiplicity constraints to enable further merging. Law 14 (Remove abstract qualifier). 𝑎abstract sig n[ext]{⋯}𝑎 𝑎 𝑏 sig n0extends n {⋯}𝑏 𝑎 ⋯ 𝑎 𝑐 sig n𝑙extends n {⋯}𝑐 𝑎 =𝐹 𝑎sig n[ext]{⋯}𝑎 𝑎 𝑏 sig n0extends n {⋯}𝑏 𝑎 ⋯ 𝑎 𝑐 sig n𝑙extends n {⋯}𝑐 𝑎 𝑎fact { n= 𝑏n0𝑏+⋯+𝑐n𝑙𝑐}𝑎 provided (↔)𝑙≥0. 120 5.2. Refactoring Rules for Colorful Alloy This law removes the abstract qualifier from signature declarations. The last line on the right-hand side of the law adds an additional fact that constrains the relationship between a parent signature and all its sub signatures. Law 13 and Law 14 remove syntactic sugar annotations from signatures, and are often used as a preparatory step to support the following merge signature refactorings. Note however, that while Law 13 is a direct adaptation of the rules for normal Alloy by considering an annotation context 𝑎 , that is not the case for Law 14, where the possible distinct annotations of the children signatures must be taken into consideration. Law 15 (Merge signature). 𝑎 𝑏 sig n[extends n0]{ ds0,…,ds𝑘}𝑏 𝑎 𝑎𝑏sig n[extends n0]{ ds′ 0,…,ds′ 𝑙}𝑏𝑎 =𝐹 𝑎sig n[extends n0]{ 𝑏ds0𝑏,…,𝑏ds𝑘𝑏, 𝑏ds′ 0𝑏,…,𝑏ds′ 𝑙𝑏}𝑎 Signatures cannot be freely merged independently of their annotations, since in Colorful Alloy they are not sufficiently expressive to represent the disjunction of presence conditions. Signatures with the same identifier can be merged if they partition a certain annotation context 𝑎 on 𝑏 , in which case the latter can be dropped (but pushed down to the respective field declarations). Due to the opposite 𝑏 annotations the two signatures never coexist in a variant, and the merged signature will exist in exactly the same variants, those determined by 𝑎 . Notice that these laws act on signatures without qualifiers. If qualifiers are compatible between the two signatures, they can be reintroduced after merging by applying the syntactic sugar laws in the opposite direction. Similar laws are defined for merging inclusion signatures (declared with in instead of extends). Returning to the e-commerce example of Fig. 48, it could be argued that the declaration of two distinct Category signatures under 1 depending on whether 2 is also selected or not, is not ideal (l. 23–28). Since neither signature has other qualifiers, Law 15 can be applied directly from left to right to merge the two signature declarations, resulting in the following single declaration. 1sig Category { 2inside: one Catalog 2, 2inside: one Catalog+Category 2 }1 Notice that fields are left unmerged by this refactoring. These will be the target of a separate set of refactorings to be presented below. 121 5.2. Refactoring Rules for Colorful Alloy Law 34 (Merge multiplicity test). 𝑎mlt exp1𝑎op1 𝑎mlt exp2𝑎== F mlt ( 𝑎exp1𝑎op2𝑎exp2𝑎) where mlt ∈{no,lone,one,some},op1∈{and,or},op2∈{+,&}. Likewise for quantifiers. Law 35 (Merge quantification). 𝑎qnt n:exp1| frm1𝑎and 𝑎qnt n:exp2| frm2𝑎== F qnt n: 𝑎exp1𝑎+𝑎exp2𝑎| 𝑎frm1𝑎and 𝑎frm2𝑎 where qnt ∈{all,some,lone,one,no}. Finally, we present two laws for merging expressions involving the essential Alloy join operator. Since join does not distribute over intersection, merging the intersection of two join expressions (when one of the operands is the same) is only possible when the respective annotations form a partition. Law 36 (Left distribute join over intersection). 𝑎exp1exp2𝑎&𝑎exp1exp3𝑎== F exp1(𝑎exp2𝑎&𝑎exp3𝑎) Since the join operation distributes over union, merging the union of two join expressions can be done independently of the annotation context. Law 37 (Left distribute join over union). 𝑎exp1exp2𝑎+ 𝑏exp1exp3𝑏== F exp1(𝑎exp2𝑎+𝑏exp3𝑏) Similar laws are defined for right distributivity. Back to the fact resulting from the merging of the field inside , after applying Laws 19, 35, 34, 29, it can be refactored into fact{1all x:Category | one x.inside 1} This allows the application of Laws 20 and 16 to push the multiplicity back into the field and remove the fact. 128 5.3. Migrating Clones into a Colorful Alloy Model 1sig Category { inside: one 2Catalog 2+2Catalog+Category 2 }1 Finally, with an application of Law 29, we can have the following declaration, meaning that a category is always inside exactly one element, which is either a Catalog or another Category if hierarchical categories are supported. 1sig Category { inside: one Catalog+ 2Category 2 }1 As another example, consider fact Thumbnails from our running example (Fig. 48,l. 18–21). With Laws 35, 31 and 36 it can be refactored into fact Thumbnails { all c:Catalog | c.thumbnails in (1catalog.c 1&1category.( 2inside 2+2^inside 2).c 1).images } The resulting fact is more compact, but whether it improves model comprehension is in the eyes of the designer. 5.3 Migrating Clones into a Colorful Alloy Model As we have seen, approaches to SPL engineering can either be proactive – where an a priori domain analysis establishes the variability points that guide the development of the product family, reactive – where an existing product family is extended as new products and functionalities are developed, or extractive – where the family is extracted from existing software products with commonalities (Krueger,2001). Colorful Alloy was initially conceived with the proactive approach in mind, with annotations being used precisely to extend a base model with the variability points addressing each desired feature. The model in Fig. 48 could be the result of a such a proactive approach to the design of the e-commerce platform. With plain Alloy, to develop this design we would most likely resort to the clone-and-own approach. First, a base model, such as the one in Fig. 60 would be developed. This model would then be cloned and adapted to specify a new variant adding support for categories, as depicted in Fig. 61. This model would in turn be further cloned and adapted twice to support hierarchical or multiple categories. A final clone would then be developed to combine these two features. These last three clones are not depicted, but 129 5.3. Migrating Clones into a Colorful Alloy Model sig Product { images: set Image, catalog: one Catalog } sig Image {} sig Catalog { thumbnails: set Image } fact Thumbnails { all c:Catalog | c.thumbnails in (catalog.c).images } pred Scenario { some Product.images } run Scenario for 10 Figure 60: E-commerce base model (variant 123). sig Product { images: set Image, category: one Category } sig Image {} sig Catalog { thumbnails: set Image } fact Thumbnails { all c:Catalog | c.thumbnails in (category.inside.c).images } sig Category { inside: one Catalog } pred Scenario { some Product.images and all c:Category | lone category.c } run Scenario for 10 Figure 61: Clone introducing categories (variant 12 3 ). they would very likely correspond to something like the projections of the colorful model in Fig. 48 over the respective feature combinations. This section first presents an extractive approach that could be used to migrate all such plain Alloy clone variants into a single Colorful Alloy model. Later we will also show how this technique can be adapted for a reactive scenario, where each new clone variant is migrated into a Colorful Alloy model already combining previous clones. Our technique follows the idea proposed by Fenske et al. (2017) for migrating Java code clones into an SPL: first combine all the clones in a trivially correct, but verbose, initial SPL, and then improve it with a step-wise process using a catalog of variant-preserving refactorings. However, as we mentioned in the beginning of the previous section there are some key differences in our approach: we don’t deal with alignment issues (although we also require some preparatory refactorings, changing the name of entities is 130 5.3. Migrating Clones into a Colorful Alloy Model 1fact FeatureModel { 221some none 12and 331some none 13 4} 5 61 2 3 sig Product { 7images: set Image, 8catalog: one Catalog 9}321 10 ... 11 run Scenario with 1,2,3for 10 12 13 12 3 sig Product { 14 images: set Image, 15 category: one Category 16 }321 17 ... 18 run Scenario with 1,2,3for 10 19 20 123sig Product { 21 images: set Image, 22 category: one Category 23 }321 24 ... 25 run Scenario with 1,2,3for 10 26 check AllCataloged with 1,2,3for 10 27 28 123sig Product { 29 images: set Image, 30 category: some Category 31 }321 32 ... 33 run Scenario with 1,2,3for 10 34 35 123sig Product { 36 images: set Image, 37 category: some Category 38 }321 39 ... 40 run Scenario with 1,2,3for 10 41 check AllCataloged with 1,2,3for 10 Figure 62: Part of the initial migrated e-commerce colorful model. not one of them); we also address Type-3 clones (namely, our refactoring catalogue includes fine-grained laws for expressions or formulas); our technique will not create features along the process. Regarding the latter, we assume that prior to clone migration the user identified the implemented features and the respective FM during domain engineering, and identified which variant (feature combination) corresponds to each clone. As such, to obtain the initial (trivially correct) Colorful Alloy model it suffices to migrate every clone to a single model, annotating all paragraphs and commands of each clone with the feature expression that 131 5.3. Migrating Clones into a Colorful Alloy Model exactly describes the respective variant. For example, for the e-commerce example, the base model of Fig. 60 would be annotated with the feature expression 123 , since this clone does not specify any of the three features, the clone of Fig. 61 would be annotated with the feature expression 12 3 , since it specifies the variant implementing only simple categories, and so on. If some feature combinations are invalid according to the FM (that is, there are only clones for some of the combinations), a fact that prevents the forbidden combinations should also be added, similar to the FeatureModel fact of Fig. 48. For the e-commerce example, part of the initial colorful model with all five variants is depicted in Fig. 62. Notice that, since all of the elements of the different clones are included and annotated with disjoint feature expressions, this Colorful Alloy model trivially and faithfully captures all the variants, although being quite verbose. After obtaining this initial model, the refactorings presented in the previous section can be repeatedly used in a step-wise fashion to merge common elements, reducing the verbosity (and improving the readability) of the model. For the structural elements the key refactorings are merging signatures (Law 15) and fields (Law 17), but, as already explained, some additional preparatory refactorings might be needed to enable those, for example reordering (or removing redundant) feature annotations or removing multiplicity qualifiers. For example, in the initial model of Fig. 62 we can start by merging signature Product (and the respective fields) from clones 123 and 12 3 and obtain 2 3 sig Product { images: set Image, 1catalog: one Catalog 1, 1category: one Category 1 }3 2 and then merge this with the definition from clone 123(by first removing the redundant feature annotation 1 to enable the application of Law 15 – notice that from the FM we can infer that 2 implies 1 ) in order to obtain 3sig Product { images: set Image, 1 2 catalog: one Catalog 2 1 , 1category: one Category 1 }3 The same result would be obtained if we first merged the declarations of Product from clones 12 3 and 123, and then the one from clone 123(in this case, to apply Law 15 we would first need 132 5.4. Automatic Merging Strategy to remove the redundant annotation 2, since from the FM we can also infer that 1implies 2). By repeatedly merging the variants of Product we can eventually get to the ideal (in the sense of having the least duplicate declarations) definition for this signature. sig Product { images: set Image, 1catalog: one Catalog 1, 1category: set Category 1 } 1fact { all p:Product | 3one p.category 3and 3some p.category 3 }1 If we repeat this process with all other model elements, we eventually get a (slightly optimized, in terms of number of declarations) version of the Colorful Alloy model in Fig. 48. A similar technique can be used to migrate a new clone into an existing colorful model, thus enabling a reactive approach to SPL engineering. Let us suppose we already have the ideal colorful model for e-commerce, but we decide to introduce a new variant to support multiple catalogs when categories are disabled (a new feature 4 ). The definition of Product for this clone would be sig Product { images: set Image, catalog: some Catalog } To migrate this clone to the existing colorful SPL we would annotate the elements of the new variant with the feature expression that characterizes it, 1234, annotate all elements of the existing SPL with 4 (since neither of its variants support this new feature), refine the FM to forbid invalid variants (adding some none annotated with 1 4 to forbid the new feature in the presence of categories), and then restart the refactoring process to improve the obtained model. 5.4 Automatic Merging Strategy In order to simplify the application of the step-wise refactoring technique described in the previous section, we also propose an automatic merging strategy that implements a sequence of refactoring laws in one composed step. This strategy supports the developers in automating the tedious and error-prone merge tasks and considerably reduces the number of steps (and overall time) to perform clone migration. 133 5.4. Automatic Merging Strategy To merge the declarations of a particular signature, the strategy repeatedly tries to find pairs of declarations of that signature that can be merged using Law 15, that is, where the respective annotations form a partition of the variants (ignoring feature annotation order, by implicit application of Law 11). The two declarations are first aligned using preparatory refactorings: if different, the multiplicity and abstract qualifiers from each declaration are moved into facts with Laws 13 and 14. When no more pairs of declarations can be merged by direct application of Law 15, the strategy tries to find a pair of declarations that could be merged if (at most) one redundant feature is removed from one of the annotations. We limit the search to one redundant feature for efficiency reasons. If such a pair of declarations is found, the redundant feature is removed using Law 12 and the process resumes. Whenever a pair of signature declarations is merged, a similar strategy is used to merge the field declarations inside. Similarly to signatures, if necessary, the multiplicity annotations of fields are first removed with Law 16, and when no pair of field declarations can be merged directly with Law 17, the strategy tries to find a pair where removing one redundant feature would enable merging. Similar laws are used for fields with different arities. To merge the respective bounding expressions the strategy for merging expressions detailed below can be applied. In most cases it suffices to apply Law 29 to merge common expressions. To illustrate this merging strategy, consider its application to signature Product in our example. The strategy will first merge declarations whose annotations partition the variants, for example the two declarations from clones 123and 12 3 , and the two declarations from clones 123and 123 . This choice would lead to the following result, where no more pairs of declarations can be directly merged with Law 15. 2 3 sig Product { images: set Image , 1catalog: some Catalog 1, 1category: one Category 1 }3 2 12sig Product { images: set Image, category: set Category }21 123sig Product { images: set Image, category: some Category }321 123fact {all p: Product | some p.category } 321 123fact {all p: Product | one p.category } 321 134 5.4. Automatic Merging Strategy Note the two facts that were created to align the declarations of field category . At this point, the strategy tries to find a pair of declarations that could be merged if one redundant feature is removed. For example, if redundant feature 1 is removed from the third declaration then it could be merged with the first one. As such, this redundant feature is removed, the automatic signature merging process resumed and those two declarations merged. Afterwards, we would end up with two declarations for Product that could not be directly merged using Law 15, namely with annotations 2 and 1 2 . Again, removing redundant feature 1from the latter would enable the merging. After finishing the automatic signature and field merging phase we would end up with the following single declaration for Product. sig Product { images: set Image, 123catalog: some Catalog 321, 1category: set Category 1 } 123fact {all p: Product | some p.category } 321 123fact {all p: Product | one p.category } 321 123fact {all p: Product | some p.category } 321 12 3 fact {all p: Product | one p.category } 3 2 1 Notice that field catalog is still annotated with two redundant features ( 2 and 3 ) that the developer may later opt to remove. The automatic strategy only removes redundant features if they enable the merging of two declarations. Import statements, facts, predicates, functions, assertions, and non-block commands with formulas can then be merged with Laws 18, 19, 21, 22, 23, 25, and 26, respectively. Block commands are merged with similar laws. Import statements, predicates, functions, assertions, and commands are merged using a similar strategy to signatures. Pairs of paragraphs that can be directly merged with the respective laws are first repeatedly processed, and once no more such pairs remain, the strategy tries to find a pair where removing a redundant feature enables merging. Since facts can be merged irrespective of the annotations they have, all facts with the same identifier will be merged in one step. Although in the above example the facts created to align field declarations are not named, in the actual implementation they have an internal identifier to ensure that the generated facts from each signature are merged separately. The annotated formulas and expressions obtained after this iterative process are then merged by repeatedly applying laws for formulas and expressions from left to right (with the exception of Law 28 that does not reduce the size of the expression). In Laws 33 and 34, where there is a choice of operator to introduce in the result, the strategy is currently opting for + . The automated strategy is also implicitly using commutative laws, for 135 5.4. Automatic Merging Strategy example, also merging common expressions in the right-hand side with Law 29, and also applying the law variants described above, namely the ones that result from combining Law 29 with Law 27. Using this strategy, the five clones of our example could be merged in single step, obtaining the model in Fig. 632. This model has some small differences when compared to the one in Fig. 48: • Field catalog still has some redundant features in the respective annotation. • There is a single declaration for field category , but an additional fact with the respective multiplicity constraints in different variants. • There is a single declaration for signature Category and the respective inside field. • There is a single expression inside fact Thumbnails , and a & operator is obtained instead of + in the sub-expression that chooses ^inside or inside depending on the presence of feature 2 . • The annotations on fact Acyclic were pushed inside into the corresponding formula. • There is one redundant feature 1in the annotation of assertion AllCataloged , and this annotation marks the all assertion instead of just the inner formula. Although the resulting model is smaller, one may argue that some of the merged declarations can actually reduce the comprehension, namely the single declaration for field category . If the user so wishes it would be possible, after the automatic strategy, to apply some manual refactoring steps and obtain a model identical to Fig. 48. For example, to obtain the same AllCataloged assert, we could start by removing the redundant annotation with Law 12 and introduce a trivial assertion with the same name annotated with the opposite feature using Law 24. 2assert AllCataloged { all p:Product | some (p.category.^inside & Catalog) }2 2assert AllCataloged { no none }2 These assertions can now be merged with Law 23, resulting in the following declaration. assert AllCataloged { 2all p:Product | some (p.category.^inside & Catalog) 2and 2no none 2 } 2 Currently our implementation pretty-prints the resulting models with spurious parenthesis, but here we opted to remove the unnecessary ones to ease the understanding of the result. In the near future we intend to solve this issue, using a more sophisticated pretty-printer. 136 5.4. Automatic Merging Strategy 1fact FeatureModel { 2-- 2Hierarchical requires 1Categories 321some none 12 4-- 3Multiple requires 1Categories 531some none 13 6} 7 8sig Product { 9images: set Image, 10 1 2 3 catalog: some Catalog 3 2 1 , 11 1category: set Category 1 12 } 13 fact { 14 1all p: Product | 3one p.category 3and 3some p.category 31 15 } 16 17 sig Image {} 18 sig Catalog { 19 thumbnails: set Image 20 } 21 22 fact Thumbnails { 23 all c:Catalog | c.thumbnails in 24 (1catalog 1&1category.( 2inside 2&2^inside 2)1.c).images 25 } 26 27 1sig Category { 28 inside: one Catalog+ 2Category 2 29 }1 30 31 fact Acyclic { 32 12all c:Category | c not in c.^inside 21 33 } 34 35 pred Scenario { 36 some Product.images and 1all c:Category | lone category.c 1 37 } 38 run Scenario for 10 39 40 12assert AllCataloged { 41 all p:Product | some (p.category.^inside & Catalog) 42 }21 43 check AllCataloged with 1,2for 10 Figure 63: E-commerce specification obtained with the automatic merging strategy. Finally the formula can be simplified by removing the annotated neutral element using Law 27, resulting in the exact same declaration of Fig. 48. 137