In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model...

151
Research Collection Master Thesis Reusable mathematical models Author(s): Widmer, Tobias K. Publication Date: 2004 Permanent Link: https://doi.org/10.3929/ethz-a-005115737 Rights / License: In Copyright - Non-Commercial Use Permitted This page was generated automatically upon download from the ETH Zurich Research Collection . For more information please consult the Terms of use . ETH Library

Transcript of In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model...

Page 1: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Research Collection

Master Thesis

Reusable mathematical models

Author(s): Widmer, Tobias K.

Publication Date: 2004

Permanent Link: https://doi.org/10.3929/ethz-a-005115737

Rights / License: In Copyright - Non-Commercial Use Permitted

This page was generated automatically upon download from the ETH Zurich Research Collection. For moreinformation please consult the Terms of use.

ETH Library

Page 2: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Master Thesis

Reusable Mathematical Models

Tobias K. [email protected]

Supervisors:

Prof. Dr. B. MeyerB. Schoeller

Chair of Software EngineeringDepartment of Computer Science, ETH Zurich

July 13, 2004

Page 3: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model
Page 4: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Abstract

In this thesis we develop a framework of reusable mathematical models intended to be used in EIFFEL

contracts. As first steps towards this goal we identify the necessary mathematical concepts and com-pare already existing approaches to formal software development to the current specification-relatedfacilities provided by the EIFFEL language.

Equipped with this theoretical background, we derive a new contract language named Interme-diate Functional Language (IFL), which is specifically designed to support high-level mathematicalconstructs from set theory and relation algebra. To give the proof of concept, we extend some existingclasses of the EIFFELBASE library with mathematical model contracts.

The principal contribution of this thesis consists of a set of library classes bundled in the Math-ematical Model Library (MML), providing the necessary support to write powerful and expressivemodel contracts in IFL. A language processing tool is presented that helps in automating the pro-cess of extracting the model contracts of an IFL annotated class and generating the associated proofobligations.

Page 5: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model
Page 6: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Contents

1 Introduction 7

2 Background 92.1 The B Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.2 The JML Specification Language . . . . . . . . . . . . . . . . . . . . . . . . . . . .102.3 The Eiffel Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10

3 Introducing Mathematical Models 133.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .133.2 Mathematical Model Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . .133.3 Specification with Mathematical Models . . . . . . . . . . . . . . . . . . . . . . . .153.4 Implications of Mathematical Models . . . . . . . . . . . . . . . . . . . . . . . . .183.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20

4 Mathematical Concepts 214.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .214.2 Syntax and Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .224.3 Fundamental Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22

4.3.1 Quantifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .234.4 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23

4.4.1 Set Equality/Set Membership . . . . . . . . . . . . . . . . . . . . . . . . .234.4.2 Set Containment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .244.4.3 Set Union/Set Intersection . . . . . . . . . . . . . . . . . . . . . . . . . . .244.4.4 Set Difference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .25

4.5 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .254.5.1 Ordered Pairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .254.5.2 Tuple Projection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26

4.6 Relations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .264.6.1 Definition by Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . .264.6.2 Definition by Comprehension . . . . . . . . . . . . . . . . . . . . . . . . .264.6.3 Binary Relations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27

4.6.3.1 Identity Relation . . . . . . . . . . . . . . . . . . . . . . . . . . .274.6.3.2 Domain/Range Projection . . . . . . . . . . . . . . . . . . . . . .27

4.6.4 Relation Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . .284.6.5 Relation Restriction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .284.6.6 Relation Inversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29

3

Page 7: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

4 CONTENTS

4.6.7 Relation Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .304.6.8 Relation Closure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .30

4.7 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .314.7.1 Finite Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .314.7.2 Function Intersection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .324.7.3 Function Union . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .324.7.4 Function Inversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33

4.8 Generalized Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .334.8.1 Sequences/Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33

4.8.1.1 Sequence Concatenation . . . . . . . . . . . . . . . . . . . . . . .344.8.1.2 Sequence Decomposition . . . . . . . . . . . . . . . . . . . . . .344.8.1.3 Sequence Reversal . . . . . . . . . . . . . . . . . . . . . . . . . .354.8.1.4 Sequence Filtering . . . . . . . . . . . . . . . . . . . . . . . . . .354.8.1.5 Sequence Disjointness/Sequence Partitioning . . . . . . . . . . . .364.8.1.6 Sequence Closure . . . . . . . . . . . . . . . . . . . . . . . . . .36

4.8.2 Multisets/Bags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .374.8.2.1 Multiset Membership . . . . . . . . . . . . . . . . . . . . . . . .384.8.2.2 Multiset Multiplicity . . . . . . . . . . . . . . . . . . . . . . . . . 38

4.9 Functionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .384.9.1 Function Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . .394.9.2 Function Currying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .394.9.3 Function Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .404.9.4 Generic Functionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40

4.9.4.1 map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .404.9.4.2 filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414.9.4.3 accumulate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .414.9.4.4 forall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414.9.4.5 exists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .42

5 The Intermediate Functional Language (IFL) 435.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .435.2 Devising A Language Specification . . . . . . . . . . . . . . . . . . . . . . . . . .43

5.2.1 Specification of Model Features . . . . . . . . . . . . . . . . . . . . . . . .445.2.2 Pure Features/Pure Expressions . . . . . . . . . . . . . . . . . . . . . . . .45

5.3 IFL Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .465.3.1 Types in IFL Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . .475.3.2 Specification with IFL Expressions . . . . . . . . . . . . . . . . . . . . . .475.3.3 Mathematical Notions of IFL . . . . . . . . . . . . . . . . . . . . . . . . . .485.3.4 Binary Operators in IFL . . . . . . . . . . . . . . . . . . . . . . . . . . . .48

5.4 IFL Validity Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495.4.1 Model Class Validity Errors . . . . . . . . . . . . . . . . . . . . . . . . . .505.4.2 Model Feature Validity Errors . . . . . . . . . . . . . . . . . . . . . . . . .505.4.3 Model Expression Validity Errors . . . . . . . . . . . . . . . . . . . . . . .515.4.4 Model Specification Validity Errors . . . . . . . . . . . . . . . . . . . . . .51

5.5 IFL Language Grammar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .525.5.1 Design of the Language Grammar . . . . . . . . . . . . . . . . . . . . . . .525.5.2 The Grammar Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54

Page 8: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

CONTENTS 5

6 The Mathematical Model Library (MML) 556.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .556.2 Design of the MML Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55

6.2.1 Facets vs. Abstract Data Types . . . . . . . . . . . . . . . . . . . . . . . . .566.2.2 Strict Interface/Implementation Separation . . . . . . . . . . . . . . . . . .596.2.3 Default Implementation of Interfaces . . . . . . . . . . . . . . . . . . . . .606.2.4 Feature Declaration/Feature Implementation Separation . . . . . . . . . . .616.2.5 Specification vs. Implementation . . . . . . . . . . . . . . . . . . . . . . .616.2.6 Type Safety vs. Generality . . . . . . . . . . . . . . . . . . . . . . . . . . .626.2.7 Object Equality/Mathematical Equality . . . . . . . . . . . . . . . . . . . .63

6.3 The Classes of the MML Library . . . . . . . . . . . . . . . . . . . . . . . . . . . .646.3.1 Mathematical Model Classes . . . . . . . . . . . . . . . . . . . . . . . . . .646.3.2 Facet Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .666.3.3 Auxiliary Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67

6.4 Usage of the Class Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .686.4.1 Compiling the Class Library . . . . . . . . . . . . . . . . . . . . . . . . . .686.4.2 Specification with the Class Library . . . . . . . . . . . . . . . . . . . . . .68

6.5 Limitations of the Class Library . . . . . . . . . . . . . . . . . . . . . . . . . . . .716.6 Implementation Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .726.7 Further Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .78

7 Specifications of Fundamental Data Structures 797.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .797.2 The Specification Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .797.3 The EiffelBase Class Specifications . . . . . . . . . . . . . . . . . . . . . . . . . .817.4 Specification Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .83

7.4.1 General Problems of EiffelBase . . . . . . . . . . . . . . . . . . . . . . . .837.4.2 Class-Specific Problems of EiffelBase . . . . . . . . . . . . . . . . . . . . .86

7.5 Benefits of Mathematical Models . . . . . . . . . . . . . . . . . . . . . . . . . . . .927.6 Usage of Model Specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . .947.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95

8 Proving Contract Correctness 998.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .998.2 The Contract Flattening Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . .998.3 Proof Obligations for Contracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1008.4 Specification Completeness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101

9 The Contract Flattener 1039.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1039.2 Functionality of the Contract Flattener . . . . . . . . . . . . . . . . . . . . . . . . .1039.3 Design of the Contract Flattener . . . . . . . . . . . . . . . . . . . . . . . . . . . .1049.4 Usage of the Contract Flattener . . . . . . . . . . . . . . . . . . . . . . . . . . . . .109

9.4.1 Compiling the Application . . . . . . . . . . . . . . . . . . . . . . . . . . .1099.4.2 Command Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . .109

9.5 Further Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .110

Page 9: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

6 CONTENTS

10 Summary of this Document 111

11 Conclusion 113

A IFL Grammar 115A.1 Syntax and Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .115A.2 The Grammar Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .115

B MML Library Features 119B.1 IFL Language Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119B.2 MML Library Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119

B.2.1 MML_ANY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120B.2.2 MML_PAIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120B.2.3 MML_SET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120B.2.4 MML_POWERSET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121B.2.5 MML_RELATION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121B.2.6 MML_FUNCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .122B.2.7 MML_BAG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .122B.2.8 MML_SEQUENCE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123B.2.9 MML_GRAPH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123

B.3 MML Generic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .124B.4 MML Conversion Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .124

C EiffelBase Class Specifications 125C.1 EiffelBase Model Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .125

C.1.1 LINEAR_SUBSET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .125C.1.2 BAG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .128C.1.3 DYNAMIC_LIST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .130C.1.4 STACK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .131C.1.5 QUEUE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .132

C.2 EiffelBase Class Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .133

D Mathematical Definitions 135D.1 Fundamental Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135D.2 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135D.3 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .136D.4 Relations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .136D.5 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .136D.6 Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .137D.7 Multisets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .137D.8 Functionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .137

Page 10: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Chapter 1

Introduction

Proving programs in a fully mathematical and rigorous way is hard and time-consuming. Althoughthere exist a number of formal approaches to software engineering like the Z specification languageor the B method, these methods strongly focus onrefinement-based programmingand do not di-rectly support trueobject-oriented programmingas the EIFFEL method does. On the other side, theJML specification language is an object-oriented extension to the JAVA programming language whichallows annotating existing JAVA programs with specification-related attributes and contracts. But nei-ther of these approaches really take full advantage the most beneficial concept in software engineering:Reuse of already available software elements. It should not only be possible to reuse units of imple-mented functionality, but also to rely on units of already proved software components. Unfortunately,the traditional formal methods as B only gradually support the reuse of proved components and theirassociated proof obligations.

Unlike in JML, contracts are first-class citizens of the EIFFEL programming language [Mey92,Mey97]. Designed as taking an integral part in the software specification process and providing semi-formal definitions of class interfaces, they turn out not to be powerful enough to express the com-plicated relationships in object structures of modern object-oriented environments. Contracts in theEIFFEL programming language are Boolean expressions written in EIFFEL itself, thus providing nosupport for higher-level expressions of first-order or higher-order predicate calculus. We are facedwith several shortcomings, meaning on the one hand the monolithic and inflexible proof process offormal methods like B, and on the other hand the restricted possibilities of formal specification usingDesign by ContractTM [Mey97] of the EIFFEL method. A combination of the reusability and ex-tendibility of object-oriented methods with the rigorous and powerful mathematical methods used informal development seems therefore reasonable. The idea of applying mathematical models to provecontract-equipped EIFFEL classes has been initiated by Meyer in [Mey03]. A nice overview is givenby Schoeller in [Sch03]. As part of the ongoing effort to prove contract-equipped EIFFEL classes,an open question is how the necessary mathematical models can be modeled as software componentsto assist client programmers in writing even more expressive and powerful contracts, using ordinaryBoolean expressions in EIFFEL assertions.

The ultimate goal of this thesis is therefore to create a collection of extendible and reusable soft-ware components that allow EIFFEL programmers to write powerful contracts using abstract mathe-matical models.

7

Page 11: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

8 CHAPTER 1. INTRODUCTION

Page 12: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Chapter 2

Background

In this chapter we give a short overview of existing approaches to formal or semi-formal software de-velopment that are of direct interest for the design of the Intermediate Functional Language (IFL) andthe Mathematical Model Library (MML). The overview is designed to support the decision what par-ticular mathematical concepts are crucial for the further discussions of this report and how they can beintegrated into a set of powerful model classes. We choose three unique and hopefully representativeapproaches to software construction.

Section2.1 presents B, a fully mathematical method of software development. Section2.2 pro-vides an overview of the JML Specification Language. Finally, in section2.3 we discuss a semi-formal approach, the EIFFEL method, which the following presentation is based on.

2.1 The B Method

The B Method [Abr96] is a formal mathematical approach tosoftware specificationanddevelopmentbased on the Z specification language from the same author. It has been successfully applied inindustry, and has robust, commercially available tool support for the entire development life-cycle,from specificationthroughrefinementdown tocode generation.

Each stage in the development process has a verification step. Specifications in B aremathemati-cal modelsof the required behavior of a system. These specifications are then transformed through asequence of formally definedrefinement stepstowards a concrete mathematically proved implemen-tation, for which source code can be generated. During this process, the developer has to discharge anumber of proof obligations.

B uses the Abstract Machine Notation [B-C] for the specification ofabstract machines, the unit ofproof in the B Method.Abstract machinescontainstate(a set of variables constrained by aninvariant)andapplicable operations(operations that may change the state, while maintaining theinvariant, andmay return a sequence of results). The foundations of B machines are the concepts ofsubstitutionanda large set ofbasic mathematical constructsfrom set theoryandrelation algebra.

In the following discussions of this report, we are not taking the rigorous mathematical road ofsoftware engineering as the B Method does, but would like to use the broad foundation ofset theoryandrelation algebraused in the B Method for ourmathematical models. Further, we would like todesign the MML class library in order to supportmechanical proofson mathematical models as the BMethod allows it onabstract machines.

9

Page 13: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

10 CHAPTER 2. BACKGROUND

2.2 The JML Specification Language

The JML language [LPC+, LBR] is a behavioral interface specification language(BISL) tailored toJAVA , taking the main characteristics of the EIFFEL [Mey92] and the LARCH [Lea96, CL94] approach,blending them to specification purposes. The language uses the JAVA DOC commenting facilities ofthe JAVA programming language to annotate existing JAVA classes with JML specifications.

JML is designed to be used by working software engineers and requires only basic mathematicaleducation. To achieve this, the JML language follows the EIFFEL-style assertion syntax combinedwith amodel-based approachto specification as pioneered by VDM and LARCH. However, JML notonly supports Boolean expressions, but also featuresquantifiers, specification-only variables, frameconditionsand other enhancements that make it more expressive for specification than EIFFEL. Thelanguage also allows assertions to be intermixed with JAVA code as an aid to verification and debug-ging.

Leavens and Cheon [LC] show how Design by ContractTM [Mey97] can be simulated in JML,and Breunesse and Poll [BP03] present how JML specifications can be verified usingmodel fields.Labeth, Meyer, Müller and Poetzsch-Heffter [LMMPH00] do a formal verification of adoubly linkedlist specified with JML using the JIVE system.

The JML language and itsmodel-based approachto specification provides the basis for the devel-opment of a library ofreusable mathematical models(MML) and the associatedcontract languageIFL.

2.3 The Eiffel Method

The following text has been adapted and shortened from [Wik].EIFFEL [MEY92] is a pureobject-oriented programming languagewhich emphasizes the pro-

duction ofrobust software. It is strongly statically typed and furnished withautomatic memory man-agement(typically implemented bygarbage collection).

Created in 1985, EIFFEL has become a mature programming language with development toolsavailable from multiple suppliers. Characteristics of EIFFEL include Design by ContractTM [Mey97],the sometimes too liberal use ofimplementation inheritanceincluding multiple inheritance, andgenericity. Design by ContractTM is a method to annotate classes withassertions, preconditions, post-conditions, loop variantsandinvariants.

Assertions in the EIFFEL language are simpleBoolean expressionsof first-order predicate logicwritten in the language itself.Existentialanduniversal quantifiersare partially provided by libraryclasses. However, no higher-order functions and related constructs are supported. EIFFEL has aunifiedtype system: All types in EIFFEL are classes, making it possible to createdescendantsof basic classessuch asCHARACTER. Additionally, the EIFFEL language allowsoperator overloading, including theability to define new operators, but does not havemethod overloading.

The EIFFEL language aims to promote clear and elegant coding. It emphasizesdeclarative state-mentsover procedural codeand intentionally limits stylistic expression, leaving much freedom foroptimizations to the compiler. The simplicity of the language not only makes the code more readable,but also allows a programmer to concentrate on the important aspects of a program without gettingdistracted by implementation details. EIFFEL’s simplicity is intended to promote simple, readable,usable, reusable and reliable solutions to business problems.

The EIFFEL language will certainly influence the design of the IFL language (see chapter5).We adopt the idea of using EIFFEL, or a subset of it, as thecontract languagefor specification with

Page 14: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

2.3. THE EIFFEL METHOD 11

mathematical models. We also reuse the support forrun-time assertion checkingoffered by all EIFFEL

run-time systems. The class library presented in chapter6 is supposed to fill in the missing conceptsof EIFFEL assertions, complementing the IFL language with a set of reusable model classes.

Page 15: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

12 CHAPTER 2. BACKGROUND

Page 16: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Chapter 3

Introducing Mathematical Models

This chapter introducesmathematical modelsas a tool to rigorously specify EIFFEL classes withexpressive contracts.

3.1 Overview

The presentation of mathematical models is laid out as follows: Section3.2 introduces the basic no-tions and concepts of mathematical models. We distinguish between two types of contract assertions,regular assertionsandmodel assertions. Section3.3is dedicated to applyingmodel contractsto exist-ing software classes. We present the process of choosing the most suitable mathematical model, anddiscuss how existing EIFFEL classes can be extended with abstract mathematical models. Section3.4discusses the benefits of specifications with mathematical models, using illustrative examples whereappropriate.

Finally, section3.5summarizes the discussions of the previous sections and lists the most impor-tant consequences of applying mathematical models to EIFFEL classes.

3.2 Mathematical Model Terminology

Before discussing the benefits and implications of mathematical models (see section3.4), it seemsconvenient to introduce a few important concepts which are needed to fully describe the process ofannotating existing EIFFEL classes with mathematical models. We proceed in the order of definition,giving for each concept a rigorous description, complementing it with an illustrative example whereappropriate.

The basic concepts of mathematical models comprise the following definitions:

• Regular Assertion: Boolean EIFFEL expression used as assertion in EIFFEL contracts.Regularassertionsare the set of assertions appearing in contracts before any annotation with mathemat-ical models is made. They correspond to normal EIFFEL assertions as used by the EIFFEL

language to support the Design by ContractTM [Mey97] method. EIFFEL assertions have thefollowing characteristic properties:

13

Page 17: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

14 CHAPTER 3. INTRODUCING MATHEMATICAL MODELS

• The expressions must conform toBoolean types. Each expression therefore yields a resultconforming to typeBOOLEANwhen evaluated.

• The expressions should bepure. A pure expressionis an expression that does not changethe state of the current object (in EIFFEL denoted by the predefined entity ’Current’). Inthe current EIFFEL standard, purity of expressions is not enforced. Consequently,pureexpressionsare only allowed to useattributesor pure queries.

• The expressions can be verified at run-time. Their execution can be monitored, triggeringanexceptionif the expression is evaluated to ’False’ and resulting in the abortion of theprogram execution.

• Abstraction Function: General function of typef : X → Y , whereX is thebase typeof theEIFFEL classC being specified (or in the case whereC is ageneric class, the family of typesrepresented by classC) andY represents themathematical abstractioncomputed byf . Let usillustrate this concept with an example:

Example: Consider an instance of a classLINKED_LIST[G]. The instance contains a possiblyempty set of elements at certain indexes, depending on the state of computation. Suppose thelinked list contains the elementsa1, a2, ..., an at a certain point of time during the computa-tion. A possible implementation of anabstraction functionf : LINKED_LIST→SEQUENCEiterates through the list instance and constructs the mathematical equivalent of alinked list, amathematicalsequence[a1, a2, ..., an] (see section4.8.1).

• Abstraction Invariant : EIFFEL class invariantdescribing the relation between the currentobject state and themathematical abstractioncomputed by anabstraction function.

• Model Assertion: Regular assertionconforming to the restrictions necessary to express prop-erties about mathematical models. These restrictions are discussed in chapter5 where the In-termediate Functional Language (IFL) is presented. Additionally,model assertionshave tocontain only feature calls tomodel features(see definition3.2).

• Model Feature: EIFFEL feature designed to represent the current state of an object in an ab-stract mathematical view. Amodel featureis a pure querywhich extracts the full state of anobject at run-time and captures one or moremathematical facetsof the state of computation ata certain point of time. Amodel featuremust be designed according to the following rules:

• Everymodel featureis the EIFFEL implementation of anabstraction function.

• Everymodel featureimplementation in EIFFEL must bepure, thus not changing the cur-rent state of the computation on the current object.

• Everymodel featurecomputes themathematical abstractionof the current object’s statebefore the execution of themodel feature.

• Regular Contract: EIFFEL contracts consisting ofregular assertionsonly.

• Model Contract: EIFFEL contracts where only feature calls tomodel featuresare allowed.Model contractsare playing an important role in the proof process of contracts, which is de-scribed in detail in chapter8.

Page 18: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

3.3. SPECIFICATION WITH MATHEMATICAL MODELS 15

• Model Class: Regular EIFFEL classes containingmodel contracts.

• Gluing Invariant : EIFFEL class invariantdescribing the relation between two or moremodelfeaturesof a class. Agluing invariantstates properties and constraints involving severalmodelfeatures, describing global constraints of the mathematical models in an EIFFEL class. Considerthe following example:

Example: The EIFFEL classLINKED_LIST [G] representssequential listswith an internalcursor. Two basicmathematical abstractionscan easily be identified: A mathematicalse-quencerepresenting the ordered elements of thelinked list, and an index pointing to the elementwhere the cursor is currently located. Therefore we introduce twomodel featuressequence andcursor of typeLINKED_LIST→SEQUENCEandLINKED_LIST→ INTEGER, respectively.To relate the twomodel features, we can specify which cursor positions are valid. The mostobvious way to do this is to extend theclass invariantwith the following invariant clause:

cursor ≥ sequence.lower_bound and cursor ≤ sequence.upper_bound (3.1)

Expression3.1states that the cursor always stays on a existing element in thesequence model.

3.3 Specification with Mathematical Models

The acquired insights of section3.2 allow us now to give an exact procedure to annotate an existingEIFFEL class with mathematical models. This procedure is divided into the following steps:

1. Model Selection: Select the appropriate mathematical models for a class. We give two basiccriteria: Mathematical AbstractionandEquivalence Partitions.

(a) To determine mathematical models of a class by usingmathematical abstraction, we haveto extract the mathematical notion represented by the class implementation. In manycases, EIFFEL classes are implementations ofAbstract Data Types(ADT’s). In this case,the selection of the necessary mathematical models is straight-forward in most cases andjust requires a translation from the ADT syntax to pure mathematical notation. Let usconsider an example to illustrate this:

Example: Undirected Weighted Graph

Consider an EIFFEL classGRAPH [W] which represents undirected graphs with an as-sociated weighting of typeW defined on its edges. The class provides features to addand remove nodes from the graph, change the weight of an edge, and others. From amathematical point of view, a graphG can simply be defined by a vertex setV and a rela-tion E defined onV indicating the edges of the graph. Therefore relationE has signatureE : V ↔ V . In the case of a weighted graph, we have an additional weighting functionW : V × V → R which is defined on the subsetE of theCartesian productof the vertexset. Finally, a weighted graphG is completely defined by a 3-tuple of setsG , (V,E, W )with E : V ↔ V andW : V × V → R. Therefore we use three different mathematicalmodels to represent the node set, the edge relation and the weighting function. Note thatthe above-mentioned tuple could be represented as a single model as well. However, thiswould yield more complicated formulas formodel assertions,and gluing invariantsinparticular. Therefore we decide to use three separate models in favor of simplicity.

Page 19: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

16 CHAPTER 3. INTRODUCING MATHEMATICAL MODELS

(b) The other criterion,equivalence partitions, is based on theobject equality relationdefinedon every instance of an EIFFEL class. For every class annotated with mathematical models,consider its features in theflat form. For each of these features, list all the attributes of theclass that are changed during the execution of the corresponding feature, and similarly,the attributes that are not affected by its execution. This results in a partition ofclassattributeswith respect to a certain feature; a set of attributes that is changed by the featureand a set of unchanged attributes.This partition can be helpful as a hint whichclass attributesa particular model shouldcover, or in other words, what the domain (theCartesian productof a subset of allclassattributes) of the abstraction functionof that particular model is. Let us illustrate thisconcept with a simple example:

Example: Linked List with Internal CursorConsider the EIFFEL classLINKED_LIST[G] implementing a list using linked cells, andproviding aninternal cursorwhich can be used to iterate over the list elements. Addi-tionally, the cursor has two positionsbeforeandafter, denoting positions before the firstelement and after the last element, respectively.Usually,linked listsprovide features to append or insert new elements, features to removeelements and in this case features to move the cursor over the list elements. As an example,let us take a featureput_left(element: G) with the following semantics:

• If the cursor isbefore, this feature is not applicable• If the cursor isafter, the element is inserted at the end of thelinked list, and the cursor

staysafter.• In all other cases, the implementation inserts the element to the left of the current

cursor position and let the cursor point to the same element as before.

If we consider this feature now with respect toequivalence partitions, it is evident that inall the defined cases for the featureput_left the cursor stays on the same element (or inother words thecursor valuesof the pre-state and the post-state areequivalent), whereasthe linked list elementsare changed by the operation. Note however thatequivalenceofthecursor positiondoes not necessarily meanimmutabilityof thecursor valueitself, sinceall indexes of the elements to the right hand side of the old cursor position are increased.The arguments above naturally suggest to separatecursor indexand linked list elementsand to use separate mathematical models for each one of them.

2. Model Implementation: Implement the selected mathematical model (or themodel feature,respectively) as apureEIFFEL query. The implementation of amodel feature fmust satisfy thefollowing conditions:

(a) Featuref must not have aprecondition. Sincemodel features are evaluated in a globalcontext, they have to be applicable at all times during the execution of a system.

(b) The postconditionof featuref states theabstraction invariantof f. This is not manda-tory, since theabstraction invariantis expressed anyway in the invariant clause of thecorresponding class. For reasons of better readability and documentation we recommendstating it again in thepostcondition.

(c) The implementation off must not change the state of the current object, nor must it changeany feature arguments received by feature calls of features havingmodel assertionsinvolv-ing f. See section5.3for a definition ofpure expressions.

Page 20: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

3.3. SPECIFICATION WITH MATHEMATICAL MODELS 17

(d) The mathematical model constructed byf reflects the state of the current object at the timeof the feature call. More details on how to constructmathematical modelsfrom theobjectstatecan be found in chapter6 and in particular in section6.4.

3. Contract Specification: Specify contracts of a featuref in terms of the implemented mathe-matical models and itsmodel features. There are only a few general rules howmodel contractsare specified. In most cases, the specification is feature-dependent and can not be systematicallydetermined. However, we would like to give a few general rules of advice:

(a) If a modelm is changed byf, introduce amodel assertionin thepostconditionof f ensuringobject equalityof the modelm. In EIFFEL, there is a convenient way to use the pre-statevalue of an object in apostcondition, which we can use in this case. This special kind ofassertion is calledimmutable model assertion:

m.is_equal (old m) (3.2)

(b) Sometimes, we may also want to specify that a feature always causes changes in the modelm, which can be expressed using:

not m.is_equal (old m) (3.3)

(c) Similar to immutable model assertions, we introduce another kind of assertion to statethat anactual feature argumentis not changed by the feature itself. This assertion type iscalledimmutable argument assertion(see also section7.2) and is used to declare a featureasside-effect freewith respect to thefeature arguments.

(d) However, the most important advice to contract specification is to annotatepure fea-tureswith a specialpure feature assertion(see also section7.2). The EIFFEL program-ming method strongly recommends to follow theCommand/Query Separation Principle[Mey97], a design rule which states that a feature is either acommand(a procedure whichchanges the state of the current object) or aquery(a pure function). A more precise def-inition of pure featurescan be found in section5.2.2. We use apure feature assertiontoexpress that a feature is indeed apure querywhich does not change the state of the currentobject:

is_equal (old Current) (3.4)

This is obviously also valid formodel featureswhich justifies apure feature assertionforeverymodel feature.

Note: Due to a problem in the language specification of the EIFFEL programming lan-guage, the semantics ofpure feature assertionsare not the ones we desire. Unfortunately,entities ofreference typeare evaluated only as reference value in the pre-state. There-fore, pure feature assertionsalways evaluate to ’True’. Since these kinds of assertionsare tautologies, we use them for documentation purposes only. The desired semanticsfor the code snippet3.4 would require an adaptedobject equality relation. For furtherinformation see section6.6.

4. Equality Relation: Redefine the featureis_equal(other: like Current) in order to provide anew implementation involving the modelm. With the introduction of a new modelm, object

Page 21: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

18 CHAPTER 3. INTRODUCING MATHEMATICAL MODELS

equalityalso requires the two corresponding models of the compared objects to be equal, whichhas to be checked by any new implementation. Additionally, thepostconditionof is_equalhasto be updated accordingly to account formodel equality.

5. Gluing Invariants : For every new modelm introduced in a class, state a correspondinggluinginvariant relating the model directly or indirectly to all other models in theflat form of theclass. Let us again give an example using the previously introduced classLINKED_LIST[G] toillustrate the concept ofgluing invariants:

Example: Linked List with Sequence and Cursor Model

Consider the EIFFEL classLINKED_LIST [G] introduced in step (1), but extended with twoimmediatemodel featurescalledsequenceandcursor. A natural property of the cursor is tohave a valid position during the life-time of alinked list instance, e.g. a position that alwayscorresponds to a element in the list. We use this property now to express agluing invariantrelating thecursor modelto thesequence model:

cursor ≥ sequence.lower_bound and cursor ≤ sequence.upper_bound (3.5)

3.4 Implications of Mathematical Models

We have introducedmathematical modelsin the last few sections of chapter3. After this theoreticalbackground it is important to realize the consequences of mathematical models and what benefits andimprovements models can bring when using it within EIFFEL contracts. The following properties arenoteworthy:

• State Change Specification: Mathematical models give the developer the ability to rigorouslyexpress which parts of the state space of an object change. Let us illustrate this statement withour linked list example:

Example: Appending Element to Linked List

Consider again the EIFFEL classLINKED_LIST[G] of section3.3having two immediatemodelfeaturescalledsequenceandcursor. If we want to specify the state changes of a featureextend(element: G) which appends a new element to the linked list, we use the two models to expressthese state changes separately:

sequence.is_equal (old sequence.extended (element)) (3.6)

cursor ≤ sequence.upper_bound implies cursor.is_equal (old cursor) (3.7)

cursor > sequence.upper_bound implies cursor.is_equal (old cursor + 1) (3.8)

Assertions3.6, 3.7and3.8express the following properties: After the execution of the feature,thesequence modelis simply theold sequence modelextended with the new element. Regardingthe cursor model, we have to differentiate between two cases: If the cursor is not in theafterposition, it points to the same element as before (which implies that the cursor value does notchange). If the cursor is behind the last element in theafter position, the index of theafterposition itself is increased due to the insertion of the new element.

Page 22: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

3.4. IMPLICATIONS OF MATHEMATICAL MODELS 19

• Minimal Contract Specification: Mathematical models allow complicated relationships in theobject structure of a system to be expressed with very few assertions. Experience has shown (seesection7.3) that the definition of a feature stated in itspostconditionsin most cases comprisesonly one line:

Example: Sequence Concatenation

Consider classLINKED_LIST [G] from the previous example. The specification of an imag-inary featureconcatenate(other: like Current) that concatenates two sequences is a simplefeature call expression:

sequence.is_equal (old sequence.concatenated (other)) (3.9)

cursor.is_equal (old cursor) (3.10)

• High-Level Contract Specification: Mathematical models allow the programmer to writehigh-level specifications without loosing mathematical preciseness. With the support of a pow-erful class library providing EIFFEL classes for the most commonmathematical abstractions(see chapter6), even contracts for general graph problems of discrete mathematics can be ex-pressed:

Example: Graph Strong Connectivity Property

Consider an EIFFEL classDIRECTED_GRAPHrepresentingstrongly-connected directed graphswith the associated mathematical modelsnodesandedges. To express thestrong connectivityproperty we use amodel invariant(or in this case agluing invariant) which comprises only oneline:

edges.reflexive_transitive_closure.is_subset (nodes.cart_product (nodes) (3.11)

• Correctness Proofs of Contracts: Mathematical models not only make it possible to writemore expressive contracts, but also provide a basis forcorrectness proofsof EIFFEL contracts.The concept ofcontract flatteningcan be directly used to generateproof obligationsfor asser-tions. Correctness proofs of contracts will be described in more detail in chapter8.

It is evident that the above-mentioned statements are only conjectures and can only be confirmedby performing actual specification of EIFFEL classes. The experience gained in the specification ofEIFFELBASE data structures (see chapter7) has shown that these statements are indeed justified.

Page 23: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

20 CHAPTER 3. INTRODUCING MATHEMATICAL MODELS

3.5 Conclusion

In this chapter, we have introduced mathematical models as an expressive tool to write more formaland powerful contracts in EIFFEL classes. In section3.2 we have given definitions for the mostimportant concepts used later on in the discussion. Section3.3 is dedicated to a thorough discussionof mathematical models applied to EIFFEL classes. We have laid out the procedure of annotatingexisting classes have presented the following steps as a guideline to introduce mathematical modelsfor an EIFFEL class:

• Model Selection: How are mathematical models chosen?

• Model Implementation: How are the correspondingmodel featuresimplemented?

• Contract Specification: How are EIFFEL contracts specified using mathematical models?

• Equality Relation: How is theobject equalityrelation implemented?

• Gluing Invariants : How are the necessarygluing invariantsexpressed?

In section3.4, the benefits and consequences of mathematical models in general are presented. Fourkey benefits of class specification using mathematical models have been identified:

• State Change Specification: Partial state changes can be formally expressed

• Minimal Specification: Preciseness of mathematical models ensures minimal specification

• High-Level Specification: Encapsulation of complicated object relationships in class librariesmakes high-level specifications possible

• Correctness Proofs: Mathematical models help in theverification processof regular assertions

The discussions of chapter3 have shown that mathematical models are a powerful tool for speci-fication, provided a broad mathematical background exists, complemented with a flexible, reusableand extendible class library of mathematical models. The mathematical background is discussed inthe next chapter (chapter4), and in chapter6 we present a library of reusable mathematical modelclasses.

Page 24: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Chapter 4

Mathematical Concepts

After the introduction on mathematical models in the previous chapter, we present the associatedmathematical objects and concepts. Mathematically inclined readers may skip the following sectionsof chapter4 on the first reading and continue directly with the introduction to the Intermediate Func-tional Language (IFL) in chapter5.

4.1 Overview

The chapter is structured as follows: For each mathematical concept, a rigorous definition is givenassociated with an informal description of the concept and how it is related to our goal of creating apowerful class library of mathematical models. To top the presentation of selected concepts off, wegive some simple but hopefully instructive examples.

Section4.3 presents the most fundamental properties of first-order predicate logic to build thebasis for all following discussions. In section4.4, the concept of a mathematical set is introduced.Next, section4.6 gives the concept of a mathematical relation based on the notion of ordered pairs,having theirfirst andsecondelement in a specifieddomainandrangeset, respectively.

Building upon these two concepts, we study the generalized notion of a mathematical functionin section4.7. Following are the different notions ofgeneralized setsin section4.8, manifested bysequences(section4.8.1) andmultisets(section4.8.2), which heavily rely on the previous concepts.Higher-order functions (section4.9) build the powerful cornerstones for a modular and generic col-lection of mathematical facilities to manipulate not onlysets, but alsofunctionsitself. We study theconcepts offunction composition(section4.9.1), function currying(section4.9.2) andfunction itera-tion (section4.9.3) and present a set of usefulgeneric functionalsto manipulate collections in section4.9.4.

During the course of this chapter we strongly obey the rule ofdefinition before use, except for twocases: The relation symbol↔ and the function symbol→. Relations and functions are used in thedefinition parts of the concept descriptions. For the sake of completeness, the definitions of these twosymbols are given below:

X ↔ Y , P(X × Y ) (4.1)

X → Y , {f : X ↔ Y | ∀x : X • ∃1 y : Y • (x, y) ∈ f} (4.2)

21

Page 25: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

22 CHAPTER 4. MATHEMATICAL CONCEPTS

4.2 Syntax and Notation

Before starting with the definitions of the most fundamental mathematical concepts, let us review thetypography and notation used in the following discussions. The most import symbol is thedefinitionsymbol,. Contrary to mathematical conventions, where most of the time the same symbol= is usedto denote eitherdefinitionor equality, we would like to stress the defining nature of the followingstatements and therefore use the symbol, to make this difference evident.

Single elements are written in lower case lettersx and can denote bothsingle elementsor subsets.The exact meaning is defined by the surrounding context. Sets are usually denoted by capital lettersX . Thepowersetof a setX is written asPX. Further, we use some predefined sets that are listedbelow without further explanation:

• Z : Integers

• N ⊂ Z : Non-Negative Integers

• R : Reals

• B , {true, false} : Booleans

In our notation, thecardinality of a set is attached as an annotation to the set name. If we wantto express the set of all subsets ofX that havecardinality greater than one, we simply writeP1X.Relations(see section4.6) will also denoted byupper caselettersR, whereasfunctionsare namedwith lower caselettersf .

The following sections of chapter4 explain the necessary mathematical concepts using conven-tions introduced above.

4.3 Fundamental Logic

We begin with the most fundamental logic operations. Assuming two arbitrary elementsx andy ofsetB, the following properties hold:

Definitions:

• x ∧ y , true if x = true, y = true

• x ∨ y , false if x = false, y = false

• ¬x , false if x = true

• x ⇒ y , ¬x ∨ y

Description:

The∧ operator denoteslogical conjunction. x ∧ y is only true if both operands aretrue. Similarly,the∨ operator denoteslogical disjunction, yieldingtrue if one or both operands aretrue. Thelogicalnegation¬ inverts the value of its operand, turningtrue into false and vice-versa.

The last operator symbolizeslogical implication. x ⇒ y is true except ifx is true andy isfalse at the same time. Note in particular thatx ⇒ y is true wheneverx is false. This is intuitivelyjustified by the fact that anything can be concluded from wrong assumptions.

Page 26: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

4.4. SETS 23

4.3.1 Quantifiers

For most of the following definitions, it is convenient to be able to express properties of severalelements belonging to a certain class. To this end, we use theexistentialanduniversalquantifiers ofpredicate calculus.

Notation:

• ∃ : Existential Quantifier

• ∀ : Universal Quantifier

Definitions:

∃x : X • P (x) , true if there exists anx in X such thatP (x) is true

∀x : X • P (x) , false if there exists anx in X such thatP (x) is false

Description:

Theexistential quantifier∃ expresses the fact that an element of a ground setX contains at least oneelementx such that the predicateP (.) is satisfied. Similarly, theuniversal quantifier∀ expresses theproperty that all elementsx of a setX satisfy a predicateP (.).

As an important consequence, theuniversal quantifier∀ yields true for any empty setX, inde-pendently of the predicate. In this case, anyexistential quantificationyields false. Obviously, theopposite holds too: If an expression∃ is true for a predicateP (.) over a ground setX, theuniversalquantification∀x : X • ¬P (x) yields alwaysfalse.

4.4 Sets

The first mathematical structure we introduce is the elementary notion of amathematical set.

4.4.1 Set Equality/Set Membership

The most fundamental properties of sets areset membershipandset equality:

Notation:

• =, 6= : Set Equality, Set Inequality

• ∈, /∈ : Set Membership, Set Non-Membership

The properties6= and/∈ are the complements of theset equalityandset membershipproperties.

Definitions:

x 6= y , ¬(x = y)

x /∈ Y , ¬(x ∈ Y )

Description:

A setX is equal to a setY if and only if it has the samecardinalityandequalityholds for all membersof the sets. The type of theequalityproperties is thereforeX ↔ Y . The type of themembershipproperties is similarly deduced asX ↔ PX.

Page 27: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

24 CHAPTER 4. MATHEMATICAL CONCEPTS

4.4.2 Set Containment

Most of the remaining set relationships of the categoryset containmentcan be described using thesubsetproperty.

Notation:

• ∅ : Empty Set

• P1 : Non-Empty Subset

• ⊆,⊂ : Subset, Proper Subset

Definitions:

∅ X , {x ∈ X | false}

P1X , {S ∈ PX | S 6= ∅ X}

S ⊆ T , {x ∈ X | S ∈ PX, T ∈ PX, x ∈ S ⇒ x ∈ T}

S ⊂ T , {x ∈ X | S ∈ PX, T ∈ PX, S ⊆ T ∧ S 6= T}

Description:

The empty set∅ is a set which contains no elements. Therefore itscardinality is zero.Informally, a setS is a subsetof a setT if every member ofS is also a member ofT . More

strongly, aproper subsetS is asubsetwhich is not equal to the setT . Additionally, for any setX,P1X denotes the set of all subsets ofX that havecardinality greater than one (or in other words, arenot equal to the empty set∅).

4.4.3 Set Union/Set Intersection

Set unionandset intersectionare binary operations on sets. We directly use thegeneralized formofthese operations for the following definitions.

Notation:

• ∪ : (Generalized) Set Union

• ∩ : (Generalized) Set Intersection

Definitions:

∪S , {x ∈ X | S ∈ P (PX) ,∃T ∈ S • x ∈ T}

∩S , {x ∈ X | S ∈ P (PX) ,∀T ∈ S • x ∈ T}

Description:

Thegeneralized formof unionandintersectionoperates on sets of sets. AssumingS is a set of sets,then∪S is its generalized union, containing all elements which are members of some sets containedin S. Thegeneralized intersection∩S is defined in an analogous way: it contains precisely thosemembers contained in all sets belonging toS. Therefore the type of both operations isP (PX) → PX.

The definition ofunion and intersectionnaturally follows from the above descriptions allowingX to containone element setsonly.

Page 28: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

4.5. TUPLES 25

4.4.4 Set Difference

Like set unionandset intersection, set differenceis a binary set operation. For any two setsS andT ,it removes all elements fromS which are also elements ofT .

Notation:

• \ : Set Difference

Definition:

S \ T , {x ∈ S | x /∈ T, S ∈ PX, T ∈ PX}

Description:

The members ofX \ Y are exactly those elements that are members ofX, but not ofY . The type ofthe operation is thereforePX × PX → PX.

4.5 Tuples

For the discussions following in the next few sections we need the notion of a collection of elementswhose order is significant. For this purpose, the mathematical concept of ann-tuple is used. Thenumbern can be replaced by any positive integer and is constant. Therefore ann-tuple represents anordered collection ofn elements, each of them possibly being of different type and value. However,the elements do not have to be unique. Special instances ofn-tuples in mathematics arecomplexnumbers(or more general ordered pairs) which have ann of 2, or quaternionsas a generalization ofcomplex numberswith dimension4.

A generaln-tuple is:(a1, a2, . . . , an) = (b1, b2, . . . , bn) if and only if a1 = b1, a2 = b2,. . .,an =bn. Formally, ann-tuple can either be defined in terms of sets as

(a1, a2, . . . , an) = {a1, {a1, a2} , {a1, a2, a3} , . . . , {a1, a2, . . . , an}} (4.3)

or by induction:

• a1-tuple(a1) is defined asa1

• if t is ann-tuple, then(t, an+1) is an(n + 1)-tuple.

It is trivial to show that either of the above definitions implies the other, which proves their equiva-lence. For the following concepts,relationsandfunctions, we restrict ourselves to the special notionof ordered pairs, mathematical objects that correspond to2-tuples.

4.5.1 Ordered Pairs

An ordered pair(x, y) is a collection of two elements such thatx can be distinguished as thefirstelement andy as thesecondelement.

Page 29: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

26 CHAPTER 4. MATHEMATICAL CONCEPTS

4.5.2 Tuple Projection

The projection operations are needed to access the elements of anordered pair.

Notation:

• first, second : Pair Projection Operations

Definition:

first (x, y) , x

second (x, y) , y

Description:

The projection operationfirst is used to extract the first element of anordered pair. Similarly, the op-erationsecondextracts the second element of anordered pair. The type of this operations is thereforededuced asX × Y → X.

4.6 Relations

Based on the previously introduced notion oftuplesandordered pairs, we are able to formally definethe concept of arelation. Sinceternary relationsand evenhigher-dimensional relationsare not ofparticular interest when we are attempting to specify data structures (see chapter7), we only considerthe special case ofbinary relations. Since relations aresetsof ordered pairs, all operations applicableto sets, includingunion, intersectionanddifferenceare also defined forrelations.

4.6.1 Definition by Extension

One way to define a relation is to list for all possible elements in thedomain setthe related elementin therange set(see section4.6.3.2). This is similar to the way of defining a set just by stating all itsmembers. Therefore any relationR on a ground setX can easily be defined by enumeration all pairsthat are element of the relation, e.g.R =

{(xi , xj

), (xm, xn) , . . .

}. The order in which the pairs are

listed is not important, since a relation is asetof ordered pairs. Definition by extensionis particularlyconvenient forfinite relationsinvolving only sets of smallcardinality.

4.6.2 Definition by Comprehension

The other way to define arelation is not byextension, meaning by listing all the contained members,but bycomprehension, e.g. through acharacteristic propertyof its members. This is clearly applicableto sets too.Definition by comprehensionis particularly interesting for functions (see section4.7). Thefollowing example shows the relation that relates each element to plus or minus the other one:

double , {(x, y) ∈ N× Z | (y = 2 ∗ x) ∨ (y = −2 ∗ x)} (4.4)

This relation contains the elements(0, 0), (3,−6), (3, 6), and so on, and could be defined equiv-alently by extension:

double , {(0, 0) , (3,−6) , (3, 6) , . . .} (4.5)

If the domain setor range setof the relation involvescountablebut infinite sets, definition bycomprehensionproves to be more convenient, since noinfinite enumerationsare needed.

Page 30: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

4.6. RELATIONS 27

4.6.3 Binary Relations

A binary relation relates elements of adomain setto elements of arange set.

Notation:

• ↔ : Binary Relation

• 7→ : Maplet

Definition:

X ↔ Y , P (X × Y )

x 7→ y , (x, y)

Description:

If X andY are sets, then the set ofbinary relationsbetweenX andY is exactly thepowersetof theCartesian productbetweenX andY , writtenP (X × Y ). Note that this definition corresponds to theone already given in section4.1. Themapletis a simple alternative notation to express the graphicalnature ofordered pairs(x, y) and elements of binary relations.

4.6.3.1 Identity Relation

An important special case of a relation is theidentity relationid.

Notation:

• id: Identity Relation

Definition:

id X , {x ∈ X | x 7→ x}

Description:

The identity relation on a setX relates each member ofX to itself and is therefore of typeX → Y .

4.6.3.2 Domain/Range Projection

Two functions in particularly related tobinary relationsare the projection functionsdomainandrange.

Notation:

• dom, ran : Domain Projection/Range Projection

Definition:

dom R , {x ∈ X | y ∈ Y, R ∈ X ↔ Y, (x 7→ y) ∈ R}

ranR , {x ∈ X | y ∈ Y, R ∈ X ↔ Y, (x 7→ y) ∈ R}

Page 31: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

28 CHAPTER 4. MATHEMATICAL CONCEPTS

Description:

AssumingR being abinary relationfrom adomain setX to arange setY , thedomainof R consistsof the set of all members ofX which are related to at least one member ofY by R. Similarly, therangeof R is the set of all members ofY to whichR relates at least one member ofX.

Note that the above projection functions forbinary relationsare generalizations of the functionsfirst andsecondfor ordered pairs. Contrary to ordered pairs, relation projection functions are of type(X × Y ) → PX, indicating a set valued result, whereas the type offirst andsecondobviously isX × Y → X.

4.6.4 Relation Composition

Most of the power and usefulness of relations comes from the fact that a relation can be expressed asacompositionof more general relations. Therelation compositionserves this purpose.

Notation:

• ◦ : Relation Composition

Definition:

R ◦ S , {x 7→ z | x ∈ X, y ∈ Y, z ∈ Z, S ∈ X ↔ Y, R ∈ Y ↔ Z, (x 7→ y) ∈ R ∧ (y 7→ z) ∈ S}

Description:

The relation compositionR ◦ S of two relationsR ∈ Y ↔ Z andS ∈ X ↔ Y relates a memberx ∈ X to a memberz ∈ Z if and only if there is at least one elementy ∈ Y to whichx is related byS and which is itself related toz by R.

4.6.5 Relation Restriction

Similar to the projection functionsdomandran which project a relation in itsvertical dimension, wedefine two other operations on relations: thedomain restrictionand therange restriction. Contrary tothedomainandrangeprojection functions, the relation restriction projects a relation in thehorizontaldimension, meaning that the restriction functions yield asubsetof the original relation.

Notation:

• / : Domain Restriction

• . : Range Restriction

Definition:

S / R , {x 7→ y | x ∈ X, y ∈ Y, S ∈ PX, R ∈ X ↔ Y, x ∈ S ∧ (x 7→ y) ∈ R}

R . T , {x 7→ y | x ∈ X, y ∈ Y, R ∈ X ↔ Y, T ∈ PY, y ∈ T ∧ (x 7→ y) ∈ R}

Page 32: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

4.6. RELATIONS 29

Description:

The domain restrictionS / R of a relation R to a setS relates an elementx from the domain setdom R to elements of the range setranR if and only if x is a member ofS. The type of thedomainrestriction is PX × (X ↔ Y ) → (X ↔ Y ). Similarly, therange restrictionR . T of R relateselements from thedomain setto an elementy of the range setif and only if y is a member ofT . Itstype is(X ↔ Y )× PX → (X ↔ Y ).

Notation:

• E : Domain Anti-Restriction

• D : Range Anti-Restriction

Definition:

S E R , {x 7→ y | x ∈ X, y ∈ Y, S ∈ PX, R ∈ X ↔ Y, x /∈ S ∧ (x 7→ y) ∈ R}

R D T , {x 7→ y | x ∈ X, y ∈ Y, R ∈ X ↔ Y, T ∈ PY, y /∈ T ∧ (x 7→ y) ∈ R}

Description:

The anti-restriction operations are the complemented counterparts of the previous restriction oper-ations. An elementx from the domain setdom R is related to elements of the range setranRby S E R if and only if x is not a member ofS. The type of the the domain anti-restriction isPX × (X ↔ Y ) → (X ↔ Y ). The relationR D T of type (X ↔ Y ) × PX → (X ↔ Y ) relateselements from the domain setdom R to an elementy of the range set if and only ify is not a memberof T .

4.6.6 Relation Inversion

Considering arelation R as asetof maplets, we can define theinverse relationas thesetof inversedmapletsof R. The inverseof a mapletx 7→ y is themaplety 7→ x with its elements just reversed, ingraphical terms the back edge of a directed edge in a graph.

Notation:

• R-1: Inverse Relation

Definition:

R-1 , {y 7→ x | x ∈ X, y ∈ Y, R ∈ X ↔ Y, (x 7→ y) ∈ R}

Description:

An elementy of therange setof R is related to an elementx of thedomain setby theinverse relationR-1 of type(X ↔ Y ) → (Y ↔ X) if and only if R relatesx to y.

Page 33: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

30 CHAPTER 4. MATHEMATICAL CONCEPTS

4.6.7 Relation Image

Therelation imageis another projection operation applicable to relations. It is a combined operationof domain restrictionandrange projection.

Notation:

• R [S] : Relation Image

Definition:

R [S] , {y ∈ Y | x ∈ X, R ∈ X ↔ Y, S ∈ PX, (x 7→ y) ∈ R ∧ x ∈ S}

Description:

The relation imageR [S] of a setS through a relationR is the set of all elements of therangeset ranR to which R relates some member ofS. The type of this image operation is therefore(X ↔ Y )× PX → PY .

4.6.8 Relation Closure

Another important category of operations applicable to relations arerelation closures.

Notation:

• R+: Transitive Closure

• R* : Reflexive-Transitive Closure

Definition:

R+ , {Q ∈ X ↔ X • ∩ {R ∈ X ↔ X, R ⊆ Q ∧Q ◦Q ⊆ Q}}

R* , {Q ∈ X ↔ X • ∩ {R ∈ X ↔ X, id X ⊆ Q ∧R ⊆ Q ∧Q ◦Q ⊆ Q}}

Description:

Thetransitive closureR+ of a relationR with identicaldomainandrange setis the strongest or small-est relation containing the relationR which istransitive. Similarly, thereflexive-transitive closureR*

is the strongest relation containingR which is bothreflexiveandtransitive. Both relation closures areof type(X ↔ X) → (X ↔ X).

These closures can also be defined in terms ofrelation iteration: Two elementsx andy are relatedby the relation closureRk of R with k ≥ 0 if and only if there existk +1 elementsz0, z1, . . . , zk withx = z0 andzk = y, such that0 ≤ i < k. Theinverse relation closureR-k is defined as

(R-1

)k.

Page 34: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

4.7. FUNCTIONS 31

4.7 Functions

Given arelation R and an elementx of its domain set, there may be zero or more elementsy suchthatR contains the pairx 7→ y . In fact, there may be infinitely many such elements in therange setof R. A relationf that relates eachx of its domainto at least oney from its rangeis called afunctionor sometimes also amapping.

Notation:

• 9 : Partial Function

• → : Total Function

Definition:

X 9 Y , {f : X ↔ Y | x ∈ X, y1 ∈ Y, y2 ∈ Y, (x 7→ y1) ∈ f ∧ (x 7→ y2) ∈ f ⇒ y1 = y2}

X → Y , {f : X 9 Y | dom f = X}

Description:

Relations that relate at most one element of its range set to elements of its domain set are calledfunctional relationsor just functions. Functions are a particularly interesting kind of relations sincethey guarantee that for any element of its domain the associated range element is unique.

If a functionf : X → Y relates each elementx of thedomainX to an element in therangeY ,the function is called atotal function. Otherwise it is called apartial function. Note that the definitionof a function corresponds exactly to the one given in the introduction to this chapter.

We further distinguish between the following subtypes of functions: Apartial or total functionf that maps different elements of itsdomainto different elements of itsrange is called aninjectivefunction. Functions that have typef : X → Y with ran f = Y are calledsurjective functionsoronto-mappings. Finally, functions that are bothinjectiveandsurjectiveare calledbijective functionsor one-to-one mappings.

Since functions are special instances of relations, all operations applicable to relations are also ap-plicable to functions. The only exception to this arefunction intersection(section4.7.2) andfunctionunion(section4.7.3), which are presented in later sections. Special care must be taken when definingthe inverseof a function (section4.7.4).

4.7.1 Finite Functions

Finite functionsare particularly suitable for modeling how computers deal with information. Thenatural finiteness of computer resources guarantees in many cases, such as memory or disk resources,that thedomainof a function isfinite. Some authors also prefer the termfinite mapping.

Notation:

• � : Finite Function

Definition:

X � Y , {f : X 9 Y | dom f is finite}

Description:

The set offinite functionscontains all functions with adomain setX that isfinite.

Page 35: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

32 CHAPTER 4. MATHEMATICAL CONCEPTS

4.7.2 Function Intersection

Since functions are specialized relations and relations themselves specialized sets, theintersectionoperationis also applicable to functions. Theintersectionof two functions is thesetof ordered pairsfrom thedomain setto therange setthat belong to both functions. Since theintersection operationshould yield a function and not a relation, we have to adapt its definition accordingly.

Notation:

• ∩ : Function Intersection

Definition:

f ∩ g , {f : X 9 Y, g : X 9 Y, h : X 9 Y }

dom h = {x ∈ dom f ∩ dom g | f (x) = g (x)}

ranh = {x ∈ dom h | h (x) = f (x) = g (x)}

Description:

The intersectionof two functionsf andg yields a functionh that yields the value off andg wher-everf andg yield the same value. The type of theintersection operationis therefore(X 9 Y ) ×(X 9 Y ) → (X 9 Y ).

4.7.3 Function Union

Although theunion operationcan be applied to functions as well, the result of this operation does nothave to be necessarily a function as well. This is the case for elements of the function domains whereboth functions are defined, but yield another value. This results in a relation in general.

One possible way out of this problem would be to restrict this operation to pairs of functions thatyield the same value for all common elements in their domain set. Obviously, this operation does notmake much sense.

The other option is to define theunion operationfor any function pairs and making itnon-commutativeto always get a function as result. We choose the second option in the following dis-cussions:

Notation:

• t : Function Union

Definition:

f t g , {f : X 9 Y, g : X 9 Y, h : X 9 Y }

dom h = {x ∈ dom f ∪ dom g | f (x) = g (x)}

ranh = {x ∈ dom h | h (x) = f (x) ⇔ x ∈ dom f ∧ x /∈ dom g, h (x) = g (x) ⇔ x ∈ dom g}

Description:

Theunion operationon functions is defined as afunction unionwhich is notcommutativeanymore.Wherever the two functionsf andg yield different values, the value ofg takes precedence, resulting ina function and not a relation. An alternative definition forfunction unionis given by((dom g) E f)∪g. The type of this operation is therefore(X 9 Y )× (X 9 Y ) → (X 9 Y ).

Page 36: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

4.8. GENERALIZED SETS 33

4.7.4 Function Inversion

Inverting a function does not necessarily result in a function, but generally yields a relation (see section4.6.6). The only kind of functions that guarantee its inverse to be again a function is the specialcategory ofinjective functions. Sinceinjective functionsmap different elements from itsdomaintodifferent elements in itsrange, theinversefunction is a function as well. In all other cases, theinverseof a functionis usually arelation.

4.8 Generalized Sets

In the previous definitions we always usedunordered setswhich contain each element exactly once,in no particular order. To extend our collection of mathematical concepts, we introduce furthergen-eralizationsof sets, allowing on the one hand elements to occurmultiple times, and on the other handto define a particularorder on its elements.

4.8.1 Sequences/Lists

Sequences are sets that contain elements in a particular order.

Notation:

• seq: Finite Sequences

• seq1: Non-empty Finite Sequences

• rank: Finite Rankings/Finite Injective Sequences

Definition:

seq X , {f : N � X | dom f = 1 . . . ‖ f ‖}

seq1 X = {f ∈ seq X |‖ f ‖> 0}

rank X = seq X ∩ (f : N � X | ∀x ∈ X, ∀y ∈ X • x 6= y ⇒ f (x) 6= f (y))

Description:

The notationseq X designates the set offinite sequencesoverX. Sequences arefinite partial functionsfrom N to the setX whosedomainare exactly the indexes1 . . . n for any natural numbern. We use thenotation〈x1, x2, . . . , xn〉 to define the sequence that contains the elementsx1, x2, . . . , xn by extension.The setseq1 X is exactlyseq X without theempty sequence, which we denote by〈〉 in the followingdiscussions. The empty sequence symbol〈〉 is an alternative notation for the function∅ : N → X,the empty function.

Further,rank X is the set ofinjective sequencesover X. Injective sequencesare sequenceswhich whose elements are unique, what is already suggested by the nature of the sequence functionf .Injective sequencesare sometimes also calledrankings. There are a number of important operationsdefined for sequences which we are presenting in the following sections.

Page 37: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

34 CHAPTER 4. MATHEMATICAL CONCEPTS

4.8.1.1 Sequence Concatenation

Theconcatenation operationon sequences combines two sequences over the same ground setX. Weuse the./ operator to denotesequence concatenation. Like in the discussion ofset unionandsetintersection(section4.4.3), we also consider thegeneralized formof sequence concatenation. The./ operator is reused to denote both the simple (as binary operator) and thegeneralized form(asunary prefix operator) of concatenation. The exact semantics of this operator are evident from thesurrounding context.

Notation:

• ./ : (Generalized) Sequence Concatenation

Definition:

./ 〈〉 , 〈〉

./ 〈S〉 , {S | S ∈ seq X}

./ (S ./ T ) , {(./ S) ./ (./ T ) | S ∈ seq (seq X) , T ∈ seq (seq X)}

U ./ V , {U ∪ {n ∈ dom V • n+ ‖ V ‖7→ V (n)} | U ∈ seq X, V ∈ seq X}

Description:

If U is a sequence of sequences of elements inX, then./ U yields a single sequence containingall the elements of the sequences inU , in the order of the concatenated sequences. The type of thegeneralized concatenation isseq (seq X) → seq X. The simple concatenation of two sequences overthe elements of a ground setX consists of all elements of the first sequence followed by the elementsof the second sequence. The type of this operation is thereforeseq X × seq X → seq X.

4.8.1.2 Sequence Decomposition

Apart from thesequence concatenationoperation there are severaldecompositionoperations applica-ble to sequences of elements inX.

Notation:

• first: First Element

• last: Last Element

• tail: Sequence Tail

• front: Sequence Front

Page 38: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

4.8. GENERALIZED SETS 35

Definition:

first S , {S ∈ seq X | S (1)}

last S , {S ∈ seq X | S (‖ S ‖)}

tail S , {S ∈ seq X | λn : 1 . . . ‖ S ‖ −1 • S (n + 1)}

front S , {S ∈ seq X | (1 . . . ‖ S ‖ −1) / S}

Description:

The operationsfirst and last return thefirst and last element of any sequenceS, respectively. Theresulting values are exactly the results of evaluating the sequence functionS with the according ar-gument1 and‖ S ‖. The type of these operations isseq1 X → X, meaningfirst andlast are onlydefined onnon-empty sequences.

The sequencestail S andfront S contain all the elements of the sequenceS except for thefirstandlast one, respectively.tail andfront are only defined on sequences of more than one element aswell. Both operations are of typeseq1 X → seq X.

4.8.1.3 Sequence Reversal

The most importantpermutation operationfor sequences is thesequence reversaloperation.

Notation:

• S∼ : Reverse Sequence

Definition:

S∼ , {S ∈ seq X | λn : dom S • S (‖ S ‖ −n + 1)}

Description:

Thesequence reversaloperator∼ applied to a sequenceS returns a sequenceS∼ containing the sameelements, but in reverse order. Obviously, the type of thesequence reversal operationis seq X →seq X.

4.8.1.4 Sequence Filtering

In the special case ofunordered sets, afilter operation could simply be defined using theset differenceoperation. In the context of sequences, special care must be taken to preserve the order of the elements.

Notation:

• � : Sequence Filtering

Page 39: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

36 CHAPTER 4. MATHEMATICAL CONCEPTS

Definition:

〈〉 � U , {〈〉 | U ∈ PX}

〈x〉 � U , {x ∈ X, U ∈ PX | 〈x〉 ⇔ x ∈ U, 〈〉 ⇔ x /∈ U}

(S ./ T ) � U , {((S � U) ./ (T � U)) | S ∈ seq X, T ∈ seq X,U ∈ PX}

Description:

The formal definition given above is an inductive definition based on sequence concatenation. IfS isa sequence of elements inX andU is a subset ofX, thenS � U is a sequence which contains exactlythose elements ofS which are not members ofU , in the same order as inS. The type of the filteringoperation isseq X × PX → seq X.

4.8.1.5 Sequence Disjointness/Sequence Partitioning

The previously encountered concepts ofset intersectionandset containmentcan naturally begener-alizedandextendedto sequences. To this end, we use the concept of indexed families of sets. Anindexed family of sets is a set of typeP (I 9 PX), whereI ∈ N+is the set of positive indexes usedto identify the members of the set family. Each member of the set family has therefore a uniquelyassigned index.

Notation:

• G : Disjointness

• ] : Partitioning

Definition:

G S , {S ∈ I 9 PX, T ∈ PX | ∀i, j ∈ dom S, i 6= j • S (i) ∩ S (j) = ∅}

S ] T , {S ∈ I 9 PX, T ∈ PX |G S ∧ ∪{i ∈ dom S • S (i)} = T}

Description:

We say that afamily of setsS (in our case anindexed family of sets) is disjoint if and only if eachpair of non-equal sets in the family hasempty intersection. In addition to thedisjointness property,the disjoint familyS partitionsa setT if the union of allS (i) is exactlyT .

4.8.1.6 Sequence Closure

A third type of closures which is only defined on functions is thesequence closure. The sequenceclosuref∗∗ of a functionf : X 9 X is defined such that for anyx ∈ X, f∗∗ yields the sequencex, f(x), f(f(x)), ..., up to the first element that is not indom f anymore. We usef∗∗ to denote thesequence closureincludingx, andf++ to express that the sequence starts withf(x). Note thatf++

is equivalent to applyingf to thesequence closuref∗∗. An important remark on the finiteness of thesequence closureconstruct: It is obvious that onlyacyclic functionsf yield a finitesequence closure.

In the definition for thesequence closurewe use theiterate functional presented in section4.9.3.Let us denotef∗∗n andf++

n as thesequence closuresof f with lengthn. Then the recursive definitionfor thesequence closureis the following:

Page 40: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

4.8. GENERALIZED SETS 37

Notation:

• f∗∗, f++: Sequence Closure

Definition:

f∗∗n+1 x , f∗∗n x ./ iterate f xn

f∗∗0 x , iterate f x 0

f++n+1 x , f++

n x ./ iterate f x n

f++0 x , f(x)

Description:

The sequence closureis a special case of the more generaltransitive closuresdefined on relations.But in order to get asequenceas result, the underlying structure is required to have thefunctionalproperty. Thereforesequence closuresare only defined on functions with identicaldomainandrange.To ensure thefinitenessof the sequence, the functionf has to beacyclic.

4.8.2 Multisets/Bags

A direct generalization of sets aremultisets, sometimes also calledbags. Multisetsdo not have therestriction of containing unique elements only, but allow each element to occur more than once. Likesets,multisetshaveno defined orderon their elements.

Notation:

• bag: Finite Multisets

• bag1: Non-Empty Finite Multisets

Definition:

bag X , f : X � N1

bag1 X , {f ∈ bag X | ‖ f ‖> 0}

Description:

A multisetbag X over a setX is an unordered set whose elements can occur multiple times. Similarto section4.6, there are two basic ways of defining a bag:Definition by extensionanddefinition bycomprehension. In the following presentation we take the somehow simpler form ofdefinition byextension.

We use the notation[[x1, x2, . . . , xn]] to denote a bag that contains the elementsx1, x2, . . . , xn. Amore complete definition which also takes the multiplicity of the elements into account uses the pre-viously introduced maplet notation{x1 7→ k1, x2 7→ k2, . . . , xn, 7→ kn}, where for eachi the elementxi occurs exactlyki times. Theempty bagis denoted by[[]], similar to theempty sequence.

Page 41: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

38 CHAPTER 4. MATHEMATICAL CONCEPTS

4.8.2.1 Multiset Membership

Themembershipproperty formultisetscan be defined similar to the definition forset membership.

Notation:

• ∈, /∈ : Multiset Membership, Multiset Non-Membership

The property/∈ is the complement of themultiset membershipproperty.

Definition:

x ∈ Y , {x ∈ dom Y | x ∈ X, Y ∈ bag X}

x /∈ Y , ¬(x ∈ Y )

Description:

An elementx is a member of a multisetY if and only if the functionY evaluates to a non-negativex.

4.8.2.2 Multiset Multiplicity

Since elements can occurmultiple timesin amultiset, the properties of a set have to be extended witha notion ofmultiplicity.

Notation:

• mult: Multiset Multiplicity

Definition:

mult Y x , {x ∈ X, Y ∈ bag X | ran ((λx : X • 0) ∪ ({x} / Y ))}

Description:

Themultiplicity of an elementx in a multisetY denoted bymult Y x is simply defined as therangeof the functionY . To prevent the case where an elementx does not occur at all in the multiset, we usethefunction union.

4.9 Functionals

So far, functions only take arguments of simple set and tuple types. In order to provide more flexibilityand to increase the power and expressiveness of function application, we use the concept ofhigher-order functions, sometimes also calledfunctionals. Higher-order functions are generalizations ofconventional functions allowing not only set and tuple types as argument types and result types, buthigher-order functionsitself. By allowing functions as arguments, we can construct functions thatoperate on other functions or even return higher-order functions as the result of a computation overfunctional arguments.

Page 42: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

4.9. FUNCTIONALS 39

4.9.1 Function Composition

The most basic application of higher-order functions is thecomposition operationof functions. Theconcept offunction compositionis similar torelation composition(see section4.6.4). However, forfunctions we would like not to give up thefunctional property of the composition, meaning thatfunction compositionshould always yield a function, and not a relation.

Notation:

• ◦ : Function Composition

Definition:

g ◦ f , {f : X 9 Y, g : Y 9 Z, h : X 9 Z}

dom h = {x ∈ dom f, f (x) ∈ dom g | x}

ranh = {x ∈ dom f | g (f (x))}

Description:

The function compositiong◦f is a functionh which has the same domain asf . The range ofh consistsof all elementsz ∈ Z which are the result of applyingf to x first, and then applyingg to that result.The composition operator obviously is a higher-order function taking two functions as arguments andresulting in a function yielding the same values as the nested application off andg to an argumentx.The type of the functional composition is therefore(Y 9 Z)× (X 9 Y ) 9 (X 9 Z).

4.9.2 Function Currying

The other important functional which we will use in the following discussions is the higher-orderfunction curry. This functional is termed after the mathematician H.B. Curry. It transforms anytwo-argument function into a one-argument function. For a number of considerations it proves to beconvenient to allow only one-argument functions.

Given a functionf with a two arguments,function curryingconsidersf as a one-argument func-tion whose result is itself a function taking one argument. Naturally, this concept can be extended tofunctions with more than two arguments. For simplicity, we definecurry for total functionsonly.

Notation:

• curry: Function Currying

Definition:

curry f , {x ∈ X, y ∈ Y, f : X × Y 9 Z, g : X 9 (Y 9 Z) | g (x) (y) = f (x, y)}

Description:

What seems not so clear at first sight is thatcurry f in fact represents the same function asg. Assum-ing z to be the result of applyingf to the argumentsx andy, applyingcurry f to the first argumentxyields a total function fromY to Z, which exactly yieldsz for any second argumenty.

The purpose of thecurry higher-order function is to achievepartial evaluationof a function. It isitself atotal functionof type((X × Y ) → Z) → (X → (Y → Z)).

Page 43: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

40 CHAPTER 4. MATHEMATICAL CONCEPTS

4.9.3 Function Iteration

A functional that is particularly useful for the definition of thesequence closurein section4.8.1.6is the iterate functional. This functional is closely related tofunction compositionand in fact is ageneralization of this concept.iterateapplies a function a certain number of times to a argument. Inother words,iterate can be expressed asf ◦ f ◦ ... ◦ f ◦ f , with f appliedn times. Therefore, thetype of the function argument has to bf : X → X. It follows that the type of theiteratefunctional is(X → X) × N → (X → X). As for thecurry functional, we defineiterate for total functionsonly.For convenience reasons, we use arecursive curried form of definition:

Notation:

• iterate: Function Iteration

Definition:

iterate f x (n + 1) , f iterate f xn

iterate f x 0 , x

Description:

It is obvious from the style of definition thatfunction iterationis a recursive concept.iterateappliedto an argument of0 yields exactly theidentity function. Then-th iterate off is then defined as thefunction application off to the(n− 1)-th iterate off .

4.9.4 Generic Functionals

Apart from the powerful concepts offunction compositionandfunction currying, we introduce somegeneric higher-order functionsthat seem very useful as basic building blocks of functionality forsetsandsequences.

4.9.4.1 map

map, as the name already suggests, is a generic function which applies a functional to all elements ofasetor sequence. The functionmapincorporates the concept of a transformation from adomain settoa range set. Its type is therefore deduced to be((X → Y )×PX) → PY , or (X → Y ) → PX → PYin the more natural curried form. This function has numerous practical examples thanks to its genericfunctional argument.

Example:

cardinality : X → N+0 , ‖X‖

map (cardinality, [[3, 4, 5] , [6,−1]]) = [3, 2]

Page 44: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

4.9. FUNCTIONALS 41

4.9.4.2 filter

Another common application of higher-order functions isfiltering of setor sequence elements. Forthis purpose we define the following functionfilter, which uses aunary predicateasfilter criterion.Applying the predicate to adomain setX results in arange setof the same type. Therefore the typeof filter is PX × (X → B) → PX.

Examples:

even : Z → B , {z ∈ Z | ∃k ∈ Z • z = 2 ∗ k}

filter ({−1, 3, 4, 6, 9, 13} , even) = {4, 6}

4.9.4.3 accumulate

The higher-order functionaccumulateis also known under the namereduce. It is used to calculatea result incrementally over aset (sequence). The main idea ofaccumulate, hence the name, is tostore intermediate values from the computation over asubset(subsequence) in anaccumulator, andcompute successive values from the current element and the previously stored result. Therefore thisfunction needs three arguments: Theaccumulation functiona, adomain setX over which to computethe result and aninitial value for the accumulator, calledc. From the above description it is evidentthat the type ofaccumulateis ((X × Y ) → Y ) → Y → PX → Y , expressed in the more naturalcurried form. Theaccumulatefunction can be applied in several contexts.

Examples:

sum : PZ → Z , accumulate (operator +) 0

sum ({1, 2, 3, 4}) = 10

4.9.4.4 forall

A function which can be defined in an elegant way using the previously encounteredaccumulatefunction is the Boolean functionforall. This function tests whether a certain propertyp holds forall elements in asetor sequence. It is the functional counter part of theuniversal quantifier. Theextensive usage of this function in the EIFFELBASE library justifies a separate definition. Again, theproperty is specified using aunary predicate, which yieldstrue if and only if the required propertyis satisfied. The deduced type therefore is(X → B) → PX → B. An elegant way to defineforalluses the Boolean operator∧ together with theaccumulatefunction and the initial valuetrue for itsaccumulator:forall , accumulate p ◦ operator ∧ true.

Examples:

positive : Z → B , {z ∈ Z | x > 0}

forall (positive, {−1, 0, 5, 7}) = false

forall (positive, {1, 2, 3, 4}) = true

Page 45: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

42 CHAPTER 4. MATHEMATICAL CONCEPTS

4.9.4.5 exists

Since we have defined theuniversal quantifieras a functionalforall, it is natural to also specify theexistential quantifieras a corresponding functionalexists. Similar to theforall functional,existstestswhether a certain propertyp holds for at least one element in asetor sequence. As above, the propertyis specified using aunary predicate, which yieldstrue if and only if the required property is satisfied.The deduced type therefore isexists : (X → B) → PX → B. Note that these two functionals areequivalent, meaning that each one can be expressed by the other, by negating thefunctionaland thepredicate.

Examples:

positive : Z → B , {z ∈ Z | x > 0}

exists (positive, {−1, 0, 5, 7}) = true

exists (positive, {−1,−2,−3,−4}) = false

Page 46: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Chapter 5

The Intermediate Functional Language(IFL)

This chapter introduces the IFL contract language used to specify EIFFEL contracts with mathematicalmodels.

5.1 Overview

In section5.2, we present our approach on how to design the IFL language. We explain the reasonsfor the additional restrictions that are introduced to adapt the language of EIFFEL Boolean expressionsto meet the strict requirements of mathematical modeling.

The important concept ofmodel featureswhich has been introduced in chapter3 is revisited insection5.2.1. A summary describes which necessary conditions have to be met by EIFFEL classeswith annotated mathematical models, and in particular we discussmodel featuresin the context ofthe previously defined concepts of chapter3, namelyabstraction functions, abstract contractsandmodel contracts. Additionally, we also provide definitions ofcleanandpure features, which help inthe following elaboration of a rigorous language definition for the IFL contract language.

In section5.3, we proceed with the definition of valid IFL language expressions. We discuss theconcrete restrictions which have been identified in section5.2, and finally give a list of semi-formaldescriptions of IFL validity errors, designed as reference for the implementation of IFL languageverifiers.

The last section of this chapter, section5.5, is dedicated to the description of the IFL languagegrammar, which is derived from the upcoming EIFFEL standard [Mey].

5.2 Devising A Language Specification

Devising a specification for a powerful functional language requires a careful examination of the ex-isting language constructs, in particular where the existing EIFFEL language grammar can be changedand adapted to favor a more restricted IFL language grammar, modeling the restrictions of the IFLlanguage as accurate as possible, while leaving as few as possible semantic checks to the semanticanalysis phase of the translation process. We are first presenting the necessary restrictions that haveto be met bymodel featuresin order to comply with the IFL language and then discuss the importantconcept ofpure expressions.

43

Page 47: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

44 CHAPTER 5. THE INTERMEDIATE FUNCTIONAL LANGUAGE (IFL)

5.2.1 Specification of Model Features

Since any implementation ofmodel featureshas to provide a result computed by theabstraction func-tion of the corresponding model, it has to conform to the properties of mathematical concepts andstructures. We list the necessary language rules formodel features, and for every rule, we give a jus-tification why it is necessary in our view.

The language rules formodel featuresf introduced in amodel classC are the following:

• Pure Query Rule: Model featuresmust be implemented aspure queriesonly. Sincemodel fea-turesrepresent theabstraction functionof the corresponding model inC, they are not allowedto change the state of the current object at all. In other words, amodel featuref can be calledas many times during the evaluation of amodel contract, each time yielding the exact samenon-void result. This property is essential for mathematical reasoning aboutmodel contracts.Note that deferredmodel featuresare perfectly valid and even sometimes needed (consider forexample a deferred class under specification, whose internal implementation details have notyet been fixed, thus leaving the construction of the mathematical models open for descendants).

Additionally, we forbid the following language constructs of the EIFFEL language:

1. External Query Rule: External featuresare normally used to interface EIFFEL code withexisting code written in another programming language. Most conventional programminglanguages provide no notion ofpure featuresin their type systems. Thereforefeaturepurity could not be guaranteed anymore when allowingexternal features.

2. Once Query Rule: A language construct which is unique in the EIFFEL programminglanguage is the notion ofonce features, a special kind of features that are only executedonce during the life-time of a software system. If theonce featureis a command, thenthe instructions of this feature are not executed anymore during subsequent calls to thisfeature. In the case of a query, subsequent function calls use the result computed duringthe first function call.

• Model Argument Rule: Model featurescannot depend on arguments other than the currentstate of computation. Everyabstraction functionof a mathematical model is of the formf :X → Y , whereX is thebase typeof the EIFFEL classC being annotated with models (or inthe case whereC is a generic class, the family of types represented by classC). Thereforeforbidding any arguments formodel featuresdoes not decrease the power of the IFL language,since the domain of theabstraction functionis thebase typeof the class itself, automaticallyproviding access to all necessary information on the current state of computation.

• Model Type Rule: Model featuresmay only return results of basicnumeric typeslike CHAR-ACTER, INTEGER, REAL, BOOLEANandreference typesof classes of a model class librarylike the Mathematical Model Library (MML) presented in chapter6. If using the MML classlibrary, thereference typeshave to conform toMML_ANY.

• Model Implementation Rule: Model featuresare only allowed to return a result which is not’Void’. This restriction should be stated both in the postcondition of the correspondingmodelfeatureand in the class invariant of themodel classwhich introduces themodel feature. Theimplementation of amodel featureis required to comply with theabstraction invariant.

Page 48: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

5.2. DEVISING A LANGUAGE SPECIFICATION 45

• Model Feature Declaration Rule: Model featureshave to be declared in a feature clause whichexports its features both to the root class of the EIFFEL type system, classANY, and to a specialmarker classwhich is designed to allow IFL language processing tools to easily extractmodelfeaturesfrom theflat formof an EIFFEL class. In the MML class library, this marker class iscalledMML_SPECIFICATION. The reason whymodel featureshave to be exported toANYlies in the export validity ruleVAPE of the EIFFEL language [Mey92], which states that everyfeature occurring in feature calls of apreconditionof a feature exported to classC in themodelclass Mmust be at least exported to classC.

• Model Class Inheritance Rule: Model classeswhich introducemodel featuresmust conformto the marker classmentioned in thePure Query Rule. Again, if model contractsare ex-pressed using the MML class library facilities, then themodel classhas to conform to classMML_SPECIFICATION. The reason for this rule is the need to access models of feature argu-ments. The following example presents such a case:

Example: Set Intersection

Consider the EIFFEL classSUBSET[G] representing the mathematical notion of a set. Thisclass introduces a featureintersect(other: SUBSET[G]) which removes all elements in thecurrent set which are not in the other set. The definition of the feature can be easily stated in itspostconditionusing mathematical models:

set.is_equal (old set.intersected (other.set)) (5.1)

Assertion5.1needs access to theset modelof the feature argument. In order to grant this access,theset modelmust be exported toANY. Since models do not have anypreconditionthat can failnor do they change the state of the current object (see section5.2.2), exposing the mathematicalmodels to the public does not raise any problems.

5.2.2 Pure Features/Pure Expressions

It has already been mentioned thatmodel featuresdo not change the state of the current object. Wewould like now to formalize this property and to give a precise definition offeature purity. The firstimportant definition for our further discussions is the definition ofpure feature:

• Definition: Pure Feature

An effected featuref of a classC is pure if and only if the following two conditions are met:

• f contains only assignments to local variables

• f contains only feature calls to features which are alsopure

This simple definition guarantees that objects instantiated from a class which offerspure featuresonlyareimmutable objects, what the following definition states:

• Definition: Immutable Object

An objecto instantiated by a classC is immutableif and only if classC providespure featuresonly.

Page 49: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

46 CHAPTER 5. THE INTERMEDIATE FUNCTIONAL LANGUAGE (IFL)

The two preceding definitions naturally lead to the important definition ofpure expressions:

• Definition: Pure Expression

An expressione is called pure if and only ife involvesimmutable objectsonly.

Note that from a mathematical point of view expressions arestatelessandpureanyway, however inthe IFL language, which is designed as a subset of the EIFFEL programming language, we have tomake sure thatmodel assertionsdo not change the state of the current object.

However, there is a small problem with the definitions mentioned above. The EIFFEL language,among many others, offers the concept ofdeferred features, a mechanism to postpone afeature im-plementationto descendant classes. Unfortunately, the definition forpure featuresis dependent onfeature implementations, which makes the concept ofpure featuresinapplicable fordeferred features.

We therefore introduce introduce a more general concept to capture alsodeferred features, whichis calledclean features:

• Definition: Clean Feature

A featuref appearing in a classC of a systemSis calledcleanif and only if one of the followingconditions is met:

• f is apure featurein classC

• f is an immediatedeferred featurein classC and all redefinitions inSarecleanas well

• f has been undefined in classC or anyancestor classin S.

An obvious observation following from the above definitions is that an expression which containsonly feature calls toclean featuresis a pure expression. This property is crucial with respect topolymorphismand will be used in the following discussion of IFL expressions.

5.3 IFL Expressions

This section is dedicated to the presentation of IFL expressions, the kind of expressions that is usedin the model assertionsof model contracts. Since the IFL contract language is based on a subsetof the EIFFEL language, our starting point for the following discussions are expressions ofBooleantypeas defined by the most recent EIFFEL standard [Mey]. Therefore, unless otherwise stated, IFLexpressions are described exactly by the same language grammar as EIFFEL expressions.

However, there are some necessary restrictions that have to be introduced in order to let IFL ex-pression reflect the mathematical world more closely. We identify three categories of additional rulesin IFL expressions: Type-related issues that have to be handled bytype rules, changes to the EIF-FEL language making IFL a language directly mappable to pure mathematics,specification-orientedrules for features annotated with mathematical models, and finally rules governing the use of binaryoperators in IFL expressions. We are going to describe each category in detail.

Page 50: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

5.3. IFL EXPRESSIONS 47

5.3.1 Types in IFL Expressions

We have already seen theModel Type Rule in section5.2.1which constrains the possible types ofmodel features. The restrictions are similar for IFL expressions. All features which are involved ina feature call of an IFL expression have to be ofbasic types CHARACTER, INTEGER, REALandBOOLEAN, or of reference typesfrom mathematical model class libraries. Obviously, the type of theexpression itself isBOOLEAN, since IFL expressions are used inmodel assertions.

All the type-related restrictionsserve only one purpose: To model mathematics as accurately aspossible. By restricting ourselves to basicnumeric typesfrom the EIFFELBASE class library, we al-low mathematical reasoning to be performed directly on the models. Depending on the reasoninglanguage, minor translation effort has to be done, which ispurely syntactical. Classes from math-ematical model libraries are specifically designed to only instantiate mathematical objects that areimmutableandstateless. In conjunction with thePure Query Rule, these twotype restrictionsthere-fore guaranteeimmutability of objectsand thereforepure expressionsas desired.

5.3.2 Specification with IFL Expressions

This category of restrictions on IFL expressions gives rules about their usage in normal EIFFEL fea-tures. These rules ensurespecification completenessof feature contracts in amodel class. We identifytwo basic criteria for a complete specification:

1. Each feature assertionmust contain assertion clauses involving all introduced or inheritedmodel features

2. Each function must specify the computation of the result with a specialdefinition assertion(seeassertion5.2).

The reasons for the first rule are very simple. If we assume that all the mathematical aspects of anEIFFEL class and its associated ADT are captured by its set of mathematical models, it is natural nowto claim that a specification iscompleteif and only if afeature assertioninvolves allmodel featuresofthatmodel class. This rule can easily checked by any language processing tool like the IFLContractFlattener (see chapter9). It has to be said that this rule is only necessary, but in no way sufficient.Enforcing eachmodel featureto occur at least once in afeature assertiondoes only help not to forgetthe specification with respect toinherited models.

The second rule is basically an accentuation of the first rule. We additionally require everypost-conditionof EIFFEL functions to contain anexact specificationof theresult they compute. This kindof assertion is called adefinition assertion(see also section7.2) and has the following form:

Result.is_equal (...) (5.2)

The right-hand side of assertion5.2 is exactly the expression of the feature implementation that isassigned to the predefined entity ’Result’. At least onedefinition assertionis required. It is alsopossible to state more than onedefinition assertionin more complicated function specifications.

Page 51: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

48 CHAPTER 5. THE INTERMEDIATE FUNCTIONAL LANGUAGE (IFL)

5.3.3 Mathematical Notions of IFL

The EIFFEL programming language has been designed as a pure, object-oriented general-purposeprogramming language. However, we have to carefully examine whether the language constructsinvolved in Boolean expressions are indeed compatible with mathematics. The following languageconstructs of the EIFFEL language have been proved incompatible with amathematical specificationlanguage:

• External Features: Features with an implementation written in another language

• Once Features: Features that are executed only once during the life-time of a system

• Impure Features: Features that change the current object state

These kinds of features are prohibited by thePure Query Ruleand its sub-rules.

External featuresare not allowed sincefeature puritycan not be guaranteed when interfacing pro-cedures and functions written in a programming language that does not support the declaration ofpure methods.

The reason whyonce featuresare not allowed in the IFL language is that they are notstateindependent. All executions of aonce featurehave the same effect as the first one. In case of aonceprocedure, the action is only executed the first time and in case of aonce function, all feature callsreturn the result computed during the first execution of the feature. This property is certainly notdesired in a mathematical environment and has therefore been prohibited in the IFL language.

The third kind of incompatible EIFFEL features areimpure features, that is to say features thatchange the state of the current object. To model the functional nature of mathematical specificationsand to completely preventabstractor concrete side-effectsof IFL expressions, only feature calls topure featuresare allowed in IFL expressions. Note that this applies tocreation proceduresas well;except that they are allowed to initialize class attributes of the target object.

To summarize, IFL expressions occurring in a classC of a systemSare allowed only to containfeature calls toclean featureswhich arecleanwith respect toS.

5.3.4 Binary Operators in IFL

Another incompatibility of the EIFFEL language (and of any non-functional programming language)with mathematical specifications is the concept ofreference equality. In mathematics, if two objectsare considered equal, then the two object have indeed the same identity. This is contrary to object-oriented programming, where objects with different identities can be considered equal. This mismatchhas an impact on thebinary operatorsthat are involved inreference equalitycomparisons.Unary op-erators of the EIFFEL language do not have to be checked for mathematical compatibility, since thereare nounary operatorsfor reference equalitycomparisons in the language specification.

We declare the following constructs of the EIFFEL language to be incompatible with the IFL lan-guage:

• Reference Equality Operator ’=’

• Reference Inequality Operator ’ /=’

Page 52: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

5.4. IFL VALIDITY ERRORS 49

However, for better usability and easier use we would like to make an exception and allow reference(in)equality operators in expressions with a right-hand operand equal to ’Void’. The reasons for thisexception are twofold:

• ’Void’ is a specialsingleton objectof the EIFFEL type system. In some implementations likethe EIFFELBASE library, ’Void’ is a frozen attribute of typeNONE, whereas others treat ’Void’as alanguage keywordor predefined entity. Reference equalityandobject equalitycomparisonstherefore always yield the exact same result. Consequently, it is justified to introduce thisconvenient syntactical shortcut.

• In EIFFEL, object equalitycomparison is supported by the three featuresis_equal(other: likeCurrent), equal(some: ANY; other: like some) and its counter part fordeep equalitycompari-son,deep_equal(some: ANY; other: like some) of classANY. Shallow equalitycomparison isprovided in two forms, a feature taking only the peer object as argument and a feature whichtakes both objects to be compared as arguments. The advantage of the second form is the pos-sibility to deal with ’Void’ arguments.

In order to provide a consistent approach tocomparisonin the IFL language, we only useobject equalitycomparison provided by the featureis_equal(other: like Current) and take thereference operators ’=’ and ’/=’ as a shortcut forequal(object,Void).

One concept that is less important in our case arenon-strict Boolean operatorslike ’and then’ or ’orelse’. As described in chapter7, these operators are seldom used in specifications involving mathe-matical models, which is the reason why we decide not to incorporate them into the IFL specification.The ’implies’ operator however proves to be crucial tocase differentiationin model postconditionsand is therefore supported by the IFL language.

5.4 IFL Validity Errors

In this section we formalize the observations of the previous sections of chapter5. We describe thelanguage restrictions of IFL by giving a set of definitions forvalidity errors. For the following dis-cussions, we assume that the reader is familiar with the validity errors of the current EIFFEL languagestandard [Mey92].

We present thevalidity errorsof the IFL language in four categories: The first category presentedin section5.4.1 lists thevalidity errors related to the EIFFEL class being annotated. Section5.4.2presents the second category containing allvalidity errorsrelated tomodel featuresin an EIFFEL class,and the third category specifies validity errors resulting fromincorrectIFL expressions(section5.4.3).Finally, the fourth category presented in section5.4.4definesvalidity errors related toincompletespecificationsof IFL contracts.

All validity errorshave an associatederror code, starting with the prefix ’IFL ’, a short summaryof the constructs involved in the validity statement, and a set ofnecessaryandsufficient conditionsforthe IFL language construct under definition.

Page 53: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

50 CHAPTER 5. THE INTERMEDIATE FUNCTIONAL LANGUAGE (IFL)

5.4.1 Model Class Validity Errors

The following conditions must be met by classes having a model featuref either declared in the classitself or contributed by a proper ancestor:

• IFLVMC : A model class Cintroducing amodel feature fis model-validif and only if the classsatisfies the following condition:

• ClassC must directly or indirectly inherit fromMML_SPECIFICATION

5.4.2 Model Feature Validity Errors

A valid model feature fdeclared in a model-annotated classC has to adhere to the following require-ments:

• IFLVMF : A model feature fdeclared in amodel class Cis model-validif and only if the featuref is either:

• aclass attribute

• apure query

• IFLVMF -x: A model feature fdeclared in amodel class Cis model-validif and only if thefeaturef is:

• IFLVMF -1: apure feature

• IFLVMF -2: not anexternal feature

• IFLVMF -3: not aonce feature

• IFLVMA : A model feature fdeclared in amodel class Cis model-validif and only if the featuref is either:

• a frozenclass attribute

• a possibly deferredfunctionwith an empty list of formal arguments.

• IFLVMT : A model feature fdeclared in amodel class Cis model-validif and only if the featuref conforms to at least one of the following types:

• MML_ANY

• INTEGER, CHARACTER, REAL

• BOOLEAN

• IFLVME : A model feature fdeclared in amodel class Cis model-validif and only if the featuref is explicitly exported to the following classes:

• MML_SPECIFICATION

• ANY

Page 54: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

5.4. IFL VALIDITY ERRORS 51

5.4.3 Model Expression Validity Errors

Valid IFL expressions occurring inmodel contractsare subject to the following additional rules:

• IFLVEF -x: A feature callf in a model expression Eis model-validif and only if the callf iseither:

• IFLVEF -1: a call to apure feature

• IFLVEF -2: not a call to anexternal feature

• IFLVEF -3: not a call to aonce feature

• IFLVEC : A creation call to acreation procedure con a objecto in a model expression Eismodel-valid if and only if the procedurec has noside-effectsexcept on the objecto undercreation.

• IFLVEE-x : A model expression Eis model-validif and only if it does not involve the followingreference operatorswith a right-hand side expression unequal to ’Void’:

• IFLVEE-1 : the reference equality operator ’=’

• IFLVEE-2 : the reference inequality operator ’/=’

• IFLVEB-x : A model expression Eis model-validif and only if it does not involve the followingnon-strict Boolean operators:

• IFLVEB-1 : the Boolean operator ’and then’

• IFLVEB-2 : the Boolean operator ’or else’

5.4.4 Model Specification Validity Errors

A specification of an Eiffel class using IFL and MML models iscompleteif and only if:

• IFLVSM : All features in theflat form Fof a classC have an associatedpostconditioncontainingan IFL expression for each of themodel featuresappearing inF.

• IFLVSD : All functions in theflat form F of a classC are required to contain at least onedefinition assertionin theirpostconditions.

For further discussions on specification completeness consult section8.4.

Page 55: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

52 CHAPTER 5. THE INTERMEDIATE FUNCTIONAL LANGUAGE (IFL)

5.5 IFL Language Grammar

The last section of chapter5 is dedicated to the IFL language grammar. Since the IFL language isa subset of the EIFFEL programming language, we start from the existing grammar describing theupcoming EIFFEL standard [Mey]. Consequently, the IFL language grammar could also be designedas a subset of the EIFFEL language grammar.

The reason why we do not follow this approach here are the variouslanguage restrictionsthat IFLintroduces for Boolean expressions. The overall idea behind the definition of any language grammarfor type-safe programming languages is to move as much error processing to the parsing phase of alanguage processing tool, in order to have a grammar which is as strict as possible and which simplifiesthe semantic analysis. In other words, as many errors in IFL expressions should be processed assyntaxerrors. We therefore carefully examine occasions to further restrict the EIFFEL grammar for the IFLlanguage. The following section describes the approach we have taken to design the IFL grammar.

5.5.1 Design of the Language Grammar

The basis of our IFL grammar is the EIFFEL grammar used in the GOBO EIFFEL TOOLS [Beza] en-riched with the language constructs of the upcoming EIFFEL standard [Mey]. Since IFL is apurefunctional languagecontainingpure expressionsas basic language concept, it suffices to restrict our-selves to the grammar rules for assertions in the EIFFEL language. We can expect a far less com-plicated language grammar leading to additional improvements with respect to a simpler semanticanalysis.

However, enforcing language rules by syntax sometimes can lead to an explosion of grammarrules. Since the IFL language is as acontract language, the suggestion to enforce the Boolean natureof its expressionsby syntaxis certainly justified. In conjunction withinline agents, expressions ofarbitrary type have to be handled as well, which results in extensive duplication of grammar rules. Forsimplicity and better readability, we decided to movetype checkingto thesemantic analysisphase.

Similarly, postconditionsin the EIFFEL language can contain special expressions referring to thepre-state of the feature (’old’ expressions). Obviously, ’old’ expressions are only valid inpostcondi-tions of features. If we would want to enforce this by syntax, all grammar rules describing EIFFEL

expressions would have to be duplicated as well, yielding a very complicated language grammar.The same is also valid for the ’Precursor’ keyword, a mechanism to refer to the version of a

feature before it has been redefined. To avoid infinite recursion, calls to ’Precursor’ are not allowedin assertions. Thisvalidity rule is also checked duringsemantic analysisto avoid an explosion ofgrammar rules.

The following steps lead to the definition of the language grammar:

• Definition of Start Symbol:

The start symbol of the grammar is ’CONTRACT’ because the IFL language is a purely func-tional language defined for assertions in EIFFEL contracts.

Page 56: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

5.5. IFL LANGUAGE GRAMMAR 53

• Introduction of Inline Agents :

Introduce inline agents as described in the upcoming EIFFEL standard [Mey]. This only re-quires an additional alternative in the rule ’Agent’, which handles the formal argument list ofthe agent and its associated routine body:

Agent ::=agent[ AgentTarget ] AgentUnqualified | [( Declarations) ] [ : Type ] Routine

The rules ’Declarations’, ’Type’ and ’Routine’ are the same ones that are used to describeformal argument lists, result types and routine bodies.

• More Strict Call Definition :

The definition of the ’Call’ rule is more strict in the IFL language grammar than in the upcom-ing EIFFEL standard [Mey]. The problem with the version from the standard is that the syntaxaccepts constructs which are not correct EIFFEL feature calls such asfoo.ResultandCurrent(foo). The IFL language specification given in appendixA has been designed not to acceptthese erroneous feature calls:

Call ::= [ CallTarget. ] CallChain

CallArguments ::= Expression | CallArguments, Expression| – empty

CallChain ::= CallUnqualified | CallChain. CallUnqualified

CallTarget ::=Current | Result| ( Expression)

CallUnqualified ::= Identifier [( CallArguments) ]

• Removal of Reference Equality:

Based on the discussions of section5.3 and section5.4, all occurrences ofreference equalityoperators have been removed. Additionally, a new rule ’Void’ has been introduced to handlethe case where the right-hand side of an expression is equal to ’Void’ (see section5.3.4):

Void ::= Expression (= | /=) Void

• Removal of Non-Strict Boolean Operators:

All non-strict Boolean operatorsexcept the’implies’ operator have been removed accordingto the IFL language specification in section5.3.4. The specifications of EIFFELBASE classespresented in chapter7 do not use these operators. Experience shows that the applications ofthese operators are quite limited and therefore it is not justified to incorporate them into the IFLlanguage grammar.

Page 57: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

54 CHAPTER 5. THE INTERMEDIATE FUNCTIONAL LANGUAGE (IFL)

5.5.2 The Grammar Rules

The last section is dedicated to the design process of the IFL grammar. In this section, we formallydescribe the language grammar based on the design process and the observations made earlier in thischapter. The grammar is specified in the widely accepted EBNF syntax, which basically usesregularexpressionsto describe the language constructs.

The start symbol of the IFL grammar is the rule ’CONTRACT’. A complete description of the grammarcan be found in appendixA.

Page 58: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Chapter 6

The Mathematical Model Library(MML)

This chapter presents the principal contribution of this thesis, the Mathematical Model Library (MML).

6.1 Overview

In chapter4 we have presented the mathematical notions we need to formally specify EIFFEL classes,and in chapter5 the Intermediate Functional Language (IFL) has been presented to express EIFFEL

contracts in a more rigorous mathematical way based on the concepts developed above. This chapterintroduces the library of mathematical models (MML), a set of classes designed to model mathematicsmore closely than already existing implementations oftuples, sets, lists and others, data structureswhich can be found in many class libraries.

Section6.2presents the principal design ideas behind the MML library. In section6.3we list theclasses provided by the library and explain their purpose. The usage of the MML library is describedin section6.4. The following sections mention the limitations of the current library version (section6.5) and the problems encountered during implementation (section6.6). Finally, in section6.7 weprovide an outlook on work that can be done to further improve the class library.

6.2 Design of the MML Library

Designing a library of mathematical notions in a pure object-oriented fashion is not easy. It seemsthat there is animpedance mismatchbetweenobject-oriented analysisanddesignand thestructureof mathematical conceptsused inset theoryandrelation algebra. We have identified the followingproblems:

• Inheritance Hierarchy Problem: The inheritance hierarchy of a class library modeling math-ematical concepts does not necessarily correspond to the natural taxonomy of mathematicalstructures. This mismatch is illustrated best by the following example:

Example: Inheritance Relation

Consider a deferred classMML_SET[G] modeling the concept of a mathematical set. Further,we have other deferred classesFUNCTION [G, H] representingdiscrete finite functionsandMML_PAIR [G, H] corresponding to2-tuples. From a mathematical point of view, it seems

55

Page 59: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

56 CHAPTER 6. THE MATHEMATICAL MODEL LIBRARY (MML)

natural to letMML_FUNCTION [G, H] inherit from MML_SET[MML_PAIR [G, H]] to em-phasize the fact thatdiscrete functionsare nothing else thanfunctional relationswhich arethemselves described as a set ofmapletsor pairs. From the object-oriented point of view takenby the EIFFEL method, aninheritance relationbetween the two classesMML_SET [G] andMML_FUNCTION [G, H] implies also asub-typing relation. Polymorphismandsub-typingtherefore suggest that everyfunctioncan be viewed as asetas well. However, there exist someoperations that perfectly valid on sets asunion, intersectionor element insertion, which poten-tially break thefunctional propertyof a function.

• Object-Orientation vs. Mathematics Problem: The core concept ofobject-oriented program-mingis the notion offeature callor message passing. In order to initiate a computation, we calla feature on a target object (sometimes denoted as ’this’, ’ self’ or in the EIFFEL language ’Cur-rent’). The target object which is an instance of a certain class in the system ”knows” how toreact to this message (by changing its own state, or by sending further messages to other arbi-trary objects). In a mathematical world however, there is no such concept ofmessage passingand moreover, objects areimmutableas already discussed in section5.2.2. Any implementationof a class library for mathematical models has to deal with these restrictions.

• Object Identity Problem : In mathematics there is no concept ofobject identityand, closelyrelated, no notion ofreferenceandreference equality. Contrary to object-oriented methods, iftwo objects are mathematically considered equal, then they have the same identity (they are thesame object in fact). We certainly have to account for this substantial difference.

• Type System Problem: The type system of the EIFFEL language was not designed to closelymodel mathematics, but to supportobject-oriented designandanalysis. It has to be investigatedto what extent the mathematical taxonomy of objects can be mapped onto a type system whereinheritance relations automatically imply sub-typing and polymorphism. The main priorityhowever is to model the mathematical concepts as closely as possible, if necessary also with aloss in type information.

Based on the main problems identified above, we present the principle design concepts behind theMathematical Model Library (MML) in the next sections.

6.2.1 Facets vs. Abstract Data Types

The recommended method ofsystem decompositionpromoted by the EIFFEL method is the search ofabstract data types(ADT’s) in the problem domain. It seems not that clear whether this approachwill lead to a satisfactory design of a class library modeling mathematical concepts. The reason ismainly theInheritance Hierarchy Problem mentioned above. We therefore use a slightly differentapproach tosystem decomposition: The search ofmathematical facetsin the problem domain. Thefollowing definition describes the concept of afacet:

• Definition: Facet

A facetis aset of featuresconsolidated in aclass interfacewhich models a certain aspect of anabstract data type(ADT).

Page 60: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

6.2. DESIGN OF THE MML LIBRARY 57

Based on the definition offacets, the process ofsystem decompositioncan be described as follows:

1. Identify Mathematical Objects

Step (1) of the design process we identify the basic mathematical notions that have to be mod-eled in the class library. The focus point for the selection of mathematical constructstuplesandsets. All other mathematical constructs ofrelation algebraandset theoryare derived fromthese concepts. We further introduce relations as sets of tuples describing a mapping betweena domainand arangeset. Functions, sequences, multisetsand other high-level mathematicalstructures can all be expressed in terms ofrelations. We select a functionf : N → X whichmaps the non-negative indexes to corresponding elements as representation forsequences. Sim-ilarly, we choose a functionf : X → N to associate themultiplicity of a multisetelement withthe element itself. Other mathematical structures that are of interest during specification arepowersets, Cartesian product, or even more complex concepts likegraphsandnetworks. It isnot clear however to what extent a library of reusable mathematical models should support suchhigh-level constructs. Whether the mathematical concept justifies introducing a separate classis decided based on the new functionality offered by the construct.

2. Enumerate Applicable Operations

Step (2) of the design process consists of finding the necessary operations applicable on themathematical structures. We use anincrementalapproach: If an operation is considered crucialfor the mathematical structure, it is accepted into the set ofapplicable operations. Otherwiseit is discarded. This approach guarantees aminimal and easy to use class interfaceof themathematical model. Later during the implementation phase, it is likely that some operationsare missing for the structure. If we can justify to introduce these operations, we include themas well.

3. Find Facets in Operations

Having identified the most important mathematical abstractions with their associated opera-tions, we are trying to findintersectionsof the sets ofapplicable operationson the mathemati-cal structures. Such a set is called afacetand usually yields a separate EIFFEL class, capturing acertain property of objects that exhibit thisfacet. For the set ofmathematical abstractionsfoundin step (1) (Mathematical Object Identification Step), the followingfacetscan be found:

• Convertible Facet: Mathematical objects that can beconvertedto other objects which donot necessarily have to bemathematically compatible. As an example, amultisetcan beconverted to arandom sequence.

• Extendible Facet: Container objects where elements can beinsertedor removed,usuallycollections of elements.

CAUTION : This facet provides features which are notpureand therefore can only be usedinternally.

• Filterable Facet: Container objects that can befiltered according to a certain criterion,usually given as aunary predicate(based on the functionalfilter).

• Mappable Facet: Mathematical objects that can bemappedto arbitrary elements using amapping function(based on the functionalmap).

Page 61: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

58 CHAPTER 6. THE MATHEMATICAL MODEL LIBRARY (MML)

• Processable Facet: Container objects which offeriteration facilities to traverse containerstructures.

• Quantifiable Facet: Mathematical objects over whichuniversalandexistential quanti-fiersare defined.

• Reduceable Facet: Container objects over which a value can be computed byaccumula-tion (based on the functionalreduce).

• Typeable Facet: Mathematical objects that providetype information.

Each of the facets listed above will result in a separate potentially deferred EIFFEL class. Classesneeding these facilities will therefore establish aninheritance relation.

4. Identify Mathematical Taxonomy

The last step in the design process is the development of a clean and simple to understand-ableinheritance hierarchywhich models the mathematical taxonomy ofset theoryandrelationalgebraas accurate as possible. To support facilities which are common to all mathematicalobjects (see section6.2.7), we introduce a commonancestor classwith the nameMML_ANY.The sole purpose of this class to introduce amathematical equality relation, a mathematicalcompatibility relationwhich states whether an object can be substituted by another one, andtype informationsuch as whether an object isset-valued, function-valued, sequence-valuedandso forth.

Further, based on the discussion in step (1) (Mathematical Object Identification Step), wecreate a classMML_PAIR [G, H] and a classMML_SET[G] for the notions ofordered pairsandunordered collectionsof elements. Relations are modeled by classMML_RELATION[G,H] which naturally inherits fromMML_SET[MML_PAIR[G, H]] to express the mathematicalnature of relations. Further, we use the functionality provided by therelation modelto im-plement a classMML_FUNCTION[G, H], which inherits fromMML_RELATION[G, H] andmodels the notion of adiscrete finite function. Thesub-typing relationinduced by theinheri-tance relationclosely models the mathematical relationship between the two concepts.

The notion of amultisetis captured by classMML_BAG[G], a descendant ofMML_FUNCTION[G, INTEGER]. Similarly, MML_SEQUENCE[G] represents the mathematical notion ofse-quences, ordered collections derived fromMML_FUNCTION[INTEGER, G]. Note the inher-ent similarity betweenbagsandsequencesin the MML library. We expect that both classes canbenefit from the rich facilities provided by the common ancestor classMML_FUNCTION[G,H] and its implementations. However, thepolymorphic relationbetweenmultisets/sequencesandfunctionsis not existent and should therefore be eliminated. Luckily, the upcoming EIFFEL

standard offers the concept ofexpanded inheritancewhich allowssub-typingwithoutpolymor-phic use.

The mathematical notions described in the paragraphs above are only basic constructs and inmany cases not powerful enough to model the complicated relationships of object structures inobject-oriented software systems. We therefore implement two other classesMML_POWERSET[G] andMML_GRAPH[G] which representpowersets(sets of sets) andgraphs, respectively.It can be argued whether the notion ofpowersetsjustifies the introduction of another class.Powersets provide specializedunionandintersectionoperations forgeneralized unionandin-tersection. The wide use of these operations makes a separate class very convenient. Moreover,

Page 62: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

6.2. DESIGN OF THE MML LIBRARY 59

the mathematical notion of agraph is a crucial concept and therefore integrated into the MMLlibrary, if not for its original operations, then for its convenience in contract specifications. An-other important concept ofset theoryis theCartesian product. Its relationship with relationsand powersets would make it an ideal candidate for inclusion into the class library. After someinvestigations on what kind of operations are applicable to theCartesian productwe decidednot to implement such a class.

Figure 6.1: The MML Model Class Hierarchy

6.2.2 Strict Interface/Implementation Separation

The relatively highimpedance mismatchbetween the pure mathematical objects and their proceduralimplementations suggests a stronginformation hidingpolicy. We are following this design rule andcreate two kind of classes:

• Model Interface Classes: Interfaces and facets of a mathematical model.

• Model Implementation Classes: An implementation of the associatedmodel interface class.

Each mathematical model consists of adeferred class MML_XXXrepresenting themodel interfaceof the mathematical model. Associated with this interface, the MML library provides at least oneimplementation of the correspondingmodel interface. The MML library in its current form providesa default implementation with the nameMML_DEFAULT_XXXfor eachmodel interface. The ad-vantage of this interface/implementation separation is the strong distinction betweenspecificationandverificationas described in section6.2.5.

Page 63: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

60 CHAPTER 6. THE MATHEMATICAL MODEL LIBRARY (MML)

6.2.3 Default Implementation of Interfaces

Strong interface/implementation separation facilitates the use of severalmodel interfaceimplementa-tions tailored to specific needs. This option is especially important with respect torun-time assertionchecking. Mathematical models make it possible to specify complex graph problems with very littleeffort. Most of the problems related tographsandnetworksrequire sophisticated algorithms to solvethem, if they are solvable inpolynomial timeat all. The MML library easily supports the extension ofthe library by specific algorithms for hard problems, just by implementing the desiredmodel interface.But most of the time, the default implementations are sufficient, since in this library the most efficientalgorithms applicable are used anyway, e.g. theFloyd-Warshall[CLRS01] algorithm to calculate thetransitive closuresof relations.

Figure 6.2: The MML Implementation Class Hierarchy

Additionally, the MML library also facilitates the creation of mathematical models with additionalfacets. The following example shows an implementation of theReduceable Facet:

Example: Consider the MML classMML_REDUCEABLE_SET[G -> NUMERIC, NUMERIC] rep-resenting the notion of a mathematical set containingnumeric elementsonly. The set class shouldprovide a generic operation which accepts abinary operatordefined onnumeric typesand anini-tial numeric value. The result of this operation is the numeric value computed incrementally on theset elements. Themodel interfaceof this class can therefore be composed fromMML_SET [G ->NUMERIC] andMML_REDUCEABLE[NUMERIC, NUMERIC]. We use the default implementationMML_DEFAULT_SET[NUMERIC] of the MML library, and are only required to implement thefeaturereduced:

Page 64: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

6.2. DESIGN OF THE MML LIBRARY 61

deferred classREDUCEABLE_SET[G−> NUMERIC, H]

inheritMML_DEFAULT_SET[H]

undefinecopy

end

MML_REDUCEABLE[G, H]undefine

copyend

end−− classREDUCEABLE_SET

6.2.4 Feature Declaration/Feature Implementation Separation

Another consequence from the interface/implementation separation is the principle of feature decla-ration/feature implementation separation.Model interfacesandmodel implementationshave differenttasks to fulfill:

• Model Interface: Specification ofClass Interfaces, Regulation ofFeature ExportandFeatureRenaming

• Model Implementation: Provider ofFeature ImplementationsandRedefinitions

The features declared in themodel interfacedetermine theclass interfaceof the mathematical model.The export status of the features and the renaming of feature names is controlled in the interface. Theimplementation of the class is provided by themodel implementation. Any redefinitions of existingfeature implementations are performed in themodel implementationas well.

6.2.5 Specification vs. Implementation

The last consequence following from the interface/implementation separation principle concerns thedifference betweenspecificationand implementation. The deferredmodel interfaceclasses can beused for the sole purpose ofspecificationanddocumentation, whereas the implementation classes aredesigned to supportrun-time assertion checkingas provided by any EIFFEL run-time system. Thisensures thatdeferred classeswhich are annotated with mathematical models for specification purposesonly do not have to referencemodel implementations.

Page 65: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

62 CHAPTER 6. THE MATHEMATICAL MODEL LIBRARY (MML)

6.2.6 Type Safety vs. Generality

During the implementation of the MML class library we have come across situations where the typesystem of the EIFFEL language is not expressive enough to express the correct types of mathematicalmodels. An important shortcoming of the EIFFEL type system areformal generic parameters. InEIFFEL, genericity is provided on aclass basis, and not on afeature basisas e.g. in C++. Thisproperty makes it impossible to introduceanonymous typesin features likecomposedof the classMML_RELATION[G, H]:

composed (other : MML_RELATION [H, I]) : MML_RELATION [G, I] (6.1)

The formal generic parameterI cannot be declared on aclass basis, since it is not known what type theargumentother has at compile-time. The signature of the featurecomposeddisplayed above wouldnot cause any problems if genericity is introduced on afeature basis. We therefore have to search foran alternative solution. There are at least two ways to solve this problem:

• Resort to Untyped Arguments: UseANYfor arguments whose type involvesanonymous types.The signature of thecomposedfeature would then look like:

composed (MML_RELATION [H, ANY ]) : MML_RELATION [G, ANY ] (6.2)

The disadvantage of this approach is that IFL expressions loosetype information. However,it is seldom necessary to accesstype informationof elements in mathematical models, whatmakesstrong typingless important on the level of elements in mathematical structures.

• Use Auxiliary Classes: Define auxiliary classes with additionalformal generic parameterscorresponding to theanonymous typesof feature arguments. Consider the following examplewhich introduces acompositor classfor relation composition:

deferred classCOMPOSITOR_EXAMPLE[G, H, I ]

feature−− Composition

composed(first: RELATION[G, H]; second: RELATION[H, I ]): RELATION[G, I ] is−− The relation composed of‘first’ and‘second’.

deferredend

end−− classCOMPOSITOR_EXAMPLE

We use the first approach for the MML library. IFL expressions are usually short and do not dependon types. Introducingauxiliary classesfor this problem could result in an explosion of classes.

Another problem where a compromise between type safety and generality has to be found man-ifests itself in the featureis_identityof classMML_RELATION[G, H]. A necessary condition for arelation to be theidentity relationis the equality of thisdomainandrangesets. Unfortunately, thesimple expressiondomain.is_equal(range) is not valid, since the formal generic parametersG andHare unrelated. This problem also arises at various other places.

To remedy this problem, we introduce the concept oftype stripping. TheTypeable Facetincludesa featureuntyped, which has a type derived from the current type of ’Current’, except that allformalgeneric parametersof the base class are replaced byANY. The following example illustrates this:

Page 66: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

6.2. DESIGN OF THE MML LIBRARY 63

deferred classPAIR_EXAMPLE[G, H]

inheritMML_ANY

undefineuntyped

end

MML_TYPEABLE[PAIR_EXAMPLE[G, H]]

feature {MML_ANY} −− Type

untyped: PAIR_EXAMPLE[ANY, ANY] is−− The object‘current’ as typeless object.

doResult:= Current

end

end−− classPAIR_EXAMPLE

Therefore, the general strategy for type safety is the following: Start with a type-less implementationusing onlyANYas type, and then incrementally infer types untiltyping problemsoccur (see featurecomposed). This approach has been proven very successful and has led to the discovery of a numberof errors in the MML class library.

6.2.7 Object Equality/Mathematical Equality

The last section presenting the design decisions behind the MML library is dedicated toobject equal-ity. We have already discussed whyreference equalityis not suitable in our context. However, evenob-ject equalitymight be too strong in some cases. Consider an instance of classMML_SET[MML_SET[G]] and another instance of classMML_POWERSET[G]. Should these to instances considered to beequal if they contain the sameset-valued elements? In a mathematical context they should, since thetwo instances represent the same abstraction and also the same object.

That is the reason for anotherequality relationcalledmathematical equality. This relation stateswhether two objects aremathematically equivalent. The common ancestor classMML_ANYintro-duces the featureequals(other: MML_ANY) which implements this relation. Note that contrary tois_equal(other: like Current) the signature is not declared usingresult type covarianceto bettercapture the nature ofmathematical equality. It can be questioned whether twoequality relationsareindeed necessary in the MML library. For reasons of simplicity, MML objects do not support theob-ject equalityrelation anymore. The implementation ofis_equalin classMML_ANYhas been designedto replaceobject equalityby mathematical equality:

Page 67: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

64 CHAPTER 6. THE MATHEMATICAL MODEL LIBRARY (MML)

deferred classEQUALITY_EXAMPLE

inheritANY

redefineis_equal

end

feature−− Comparison

is_equal(other: like Current): BOOLEANis−− Is ‘other’ considered equal to‘current’?

doResult:= equals(other)

ensure thenimplementation_of_equal: Result.is_equal(equals(other))

end

equals(other: ANY): BOOLEANis−− Is ‘other’ mathematically equivalent to‘current’?

deferredend

end−− classEQUALITY_EXAMPLE

To implement themathematical equality relationwe have to perform the following steps:

1. Defer is_equalin everymodel interface

2. Undefineis_equalin everyfeature adaptation clauseof themodel implementation

3. Implementis_equalin everymodel implementationif necessary

These steps ensure that thefeature adaptation clausesof the MML library remain as short as possible.Experience has shown that almost anymodel implementationneeds a specialized implementation oftheequality relationanyway, thus causing not much extra work to be done.

6.3 The Classes of the MML Library

After the last section describing the general design, we present the mathematical model classes pro-vided by the MML library. There are three basic class categories:mathematical model classes(sec-tion 6.3.1), facet classes(section6.3.2), andauxiliary classes(section6.3.3). Each of these categoriesis described in detail in the following sections.

6.3.1 Mathematical Model Classes

This section describes themathematical model classesof the MML library.

• MML_SPECIFICATION: This specialmarker classis used to exportmodel features. It doesnot provide any features at all, but has onlydocumentation purposes. Newly introducedmodelfeaturesare declared in afeature clausewhich exports its features toMML_SPECIFICATIONandANY. See section6.4for a detailed role description of this class.

Page 68: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

6.3. THE CLASSES OF THE MML LIBRARY 65

• MML_ANY: The common ancestor classof the MML library is responsible for adefault imple-mentationof themathematical equality relationand for the introduction ofmathematical typeinformation. In classMML_ANY the object equality relationis replaced by its mathematicalcounterpart. For a list of applicable operations see appendixB.2.1andB.4.

• MML_PAIR: ClassMML_PAIR [G, H] represents the mathematical notion of a2-tuple, orpair. It provides different operations to access the tuple components (featuresfirst, secondandelement) and features conversion operations likeinversedandidentity_pair. Additionally, classMML_PAIRimplements theTypeable, Quantifiable andProcessable Facet(see section6.2.1).The operations provided byMML_PAIRare listed in appendixB.2.2.

• MML_SET: ClassMML_SET[G] models the notion of amathematical set. It provides oper-ations forset membership(featureis_member), functions to randomly access the set elements(featuresany_elementandany_item), queries forset containmentlike is_superset, is_subsetand others, plus basic set operations asset union(featureunited) andset intersection(featureintersected). Additionally, classMML_SETimplements theTypeable, Quantifiable, Process-able, Filterable, Convertible, MappableandExtendible Facet(see section6.2.1). Operationsapplicable toMML_SETinstances are listed in appendixB.2.3.

• MML_POWERSET: ClassMML_POWERSET[G] is an extension to theMML_SET[G] classwhich implements the notion of a set of sets (apowerset). Apart from all the functionalityinherited fromMML_SET, MML_POWERSETintroduces the concept ofgeneralized set unionandintersection. The class therefore implements the samefacetsasMML_SET. Its applicableoperations are listed in appendixB.2.4.

• MML_RELATION: ClassMML_RELATION[G, H] introduces the concept of a mathematicalrelation based on a set of pairs. It features operations to query the type of the relation (fea-turesis_reflexive, is_symmetric, and others) and implements conventional projection operationssuch asdomain, rangeandimage, associated with severaldomain restrictionandrange restric-tion functions. Further, classMML_RELATIONintroduces thecompositionoperation whichcombines two relations and theinversionoperation for relations. Another category of opera-tions provided by relations aretransitive closures. ClassMML_RELATIONprovides a featuretransitive_closureand a featurereflexive_transitive_closurefor transitive closuresandreflexivetransitive closures, respectively. This class implements theTypeableandMappable Facet(seesection6.2.1). All available operations are listed in appendixB.2.5.

• MML_FUNCTION: Based on classMML_RELATION, the MML library provides the notionof functions in classMML_FUNCTION[G, H]. This class declares features to query the typeof a function (featuresis_partial, is_total, and others). Like classMML_RELATION, classMML_FUNCTIONalso definesfunction intersectionand function union, as well asfunctioncompositionand inversion. Additionally, the class introduces a special type of closure, thesequence closure. Function models implement the same facets as relations. The operationsavailable on functions are listed in appendixB.2.6.

• MML_BAG: The notion ofmultisetsis represented by classMML_BAG [G]. Similar to classMML_SET[G], multisets also offer features forbag containment(featuresis_superbag, is_sub-bag and others). It also provides a very convenient function to convertmultisetsinto randomsequencesof the elements. The remaining operations are similar to those from theset model

Page 69: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

66 CHAPTER 6. THE MATHEMATICAL MODEL LIBRARY (MML)

MML_SET[G]. Additionally, multisets also implement theTypeable, Quantifiable andPro-cessable Facet(see section6.2.1) to make it possible to iterate over the same element multipletimes according to itsmultiplicity. The multiset operations are listed in appendixB.2.7.

• MML_SEQUENCE: ClassMML_SEQUENCE[G] represents a mathematical sequence. Thisclass provides features to insert and remove elements from a sequence (featuresappended,prepended, extended_at, pruned_at, and others), features forsequence containment(featuresis_subsequence, is_supersequence, and others). Additionally, classMML_SEQUENCEalsooffers operations likesequence reversal, sequence partitionandsequence decomposition. Acomplete list of features applicable tosequence objectscan be found in appendixB.2.8.

• MML_GRAPH: The lastmodel classin the MML library models the notion of adirected graph.Graphs are represented as pairs of anode setand anedge relationin the MML library. classMML_GRAPH [G] naturally inherits fromMML_PAIR [MML_SET [G], MML_RELATION[G, G]]. This class offers features to insert and remove new nodes from the graph (featuresnode_extendedandnode_pruned) and similarly, features to change the edges of a graph (fea-turesedge_extendedandedge_pruned). Further, classMML_GRAPHalso provides features toquery forgraph containment(featuresis_supergraph, is_subgraph, and others), very similar tosets. Additionally, it supports also simple queries forgraph connectivityandgraph complete-ness. Its applicable features are listed in appendixB.2.9.

6.3.2 Facet Classes

This section describes the differentfacet classesof the MML library, based on the previously intro-ducedfacetsin section6.2.1. All operations provided by the following facets are listed in appendixB.3.

• MML_CONVERTIBLE: This facet classoffers features to convert mathematical objects intoother objects. Currently, classMML_CONVERTIBLEoffers a featureidentity_pairto create apair with itsfirst andsecondelement equal to thecurrent object. This facility is used at variousplaces in classMML_RELATIONand its implementations.

• MML_EXTENDIBLE: ClassMML_EXTENDIBLEis an internal classwhich provides an in-terface for mathematical objects which support the insertion and removal of elements. Thisclass provides two featuresextendandprune, which both are notpure. It is used in allmodelclassesof the MML library, but should not be used by any clients of the class library.

• MML_FILTERABLE: This class provides the concept of a mathematical structure whose el-ements can be filtered according to aunary predicate. Featurefiltered has signaturefiltered(FUNCTION [ANY, TUPLE [G], BOOLEAN]): like Current. It is used by nearly all classes inthe MML library.

• MML_MAPPABLE: ClassMML_MAPPABLErepresents the concept of a structure containingtransformable elements and offers a featuremappedwhich performs the transformation. It hassignaturemapped(FUNCTION[ANY, TUPLE [G], H]): MML_SET[H]. The only argument ofthis feature is themapping function, mapping an element of typeG to a corresponding elementof typeH. This class is primarily used in classMML_RELATIONand its implementations.

Page 70: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

6.3. THE CLASSES OF THE MML LIBRARY 67

• MML_PROCESSABLE: TheProcessable Facetprovides two kinds of features:Pure featuresdesigned to be used by clients of the MML class library, andimpure featuresfor internal use.Featureapplied can be used by clients to apply an action to all elements of a mathematicalstructure. Its signature isapplied(PROCEDURE[ANY, TUPLE[G]]). The other featuresdo_alland its conditional variantdo_if are used internally and are not exported to clients of the classlibrary.

• MML_QUANTIFIABLE: This class represents the notions ofexistentialanduniversal quanti-fiers. Both quantifiers take an argument of typeFUNCTION [ANY, TUPLE [G], BOOLEAN]representing aunary predicate. This class is used throughout the whole MML class library,often in conjunction withMML_FILTERABLE.

• MML_REDUCEABLE: Featurereducedof classMML_REDUCEABLEimplements the func-tional accumulateintroduced in section4.9.4.3. This functional takes three arguments: Aninitial value of typeG, an operator function of typeFUNCTION [ANY, TUPLE [G, G], G] anda mapping functionFUNCTION [ANY, TUPLE [H], G]. The mapping function can be used ifthe values to be accumulated have to be computed first from the element of the structure. If thisis not the case, theidentity functioncan be used as argument.

• MML_TYPEABLE: TheTypeable Facetprovides the two important concept ofmathematicaltype informationandmathematical compatibility. The feature which implements mathemati-cal compatibility,is_compatible, is primarily used in the implementations ofis_equalof classMML_ANY. The features providingmathematical type informationare designed to be only usedby clients of the MML library.

6.3.3 Auxiliary Classes

In this section we present theauxiliary classesof the library.

• MML_FUNCTIONALS: ClassMML_FUNCTIONALSis an auxiliary classused by variousmodel implementationclasses. It offershigher-order agentsand otherfunctionalswhich arevery convenient to use initerationsover collection andquantifiersfrom first-order logic. Otherfeatures offered by this class areBoolean operators(featuresanded, ored, negated, and others)and functionals forfunction currying, function compositionandfunction iteration. All availablefeatures are listed in appendixB.3.

Page 71: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

68 CHAPTER 6. THE MATHEMATICAL MODEL LIBRARY (MML)

6.4 Usage of the Class Library

The last section has described the different types of classes in the MML library. Here in this sectionwe describe how to use the MML library. Section6.4.1 describes the compilation process of theMML library. In section6.4.2we revisit the specification process of section3.3and explain it againin the context of the MML class library.

6.4.1 Compiling the Class Library

The MML class library in its current version does not need any additional libraries to compile cor-rectly. The following components are required:

• ISE EIFFELSTUDIO 5.3

• ISE EIFFELBASE Class Library

The class library depends on the EIFFELBASE library shipped with EIFFELSTUDIO 5.3. To compilethe MML library, open EIFFELSTUDIO and create a new project from one of the ACEfilesin the rootof the MML code base. All files use relative path names only. In order to resolve the cluster paths inthe MML code base correctly, the developer has to set the environment variable ’$MML’ to the pathof the code base root.

The ACEfiles itself are completelyplatform-independentand can be used on all platforms sup-ported by ISE EIFFELSTUDIO.

6.4.2 Specification with the Class Library

This section gives a summary on how to use the MML library for specification of EIFFEL classes.The actual specification process using mathematical models is described in detail in section3.3. Thefollowing steps have to be performed to introduce a new model if using the MML library:

1. Feature Clause Declaration: Declare afeature clauseexported both toMML_SPECIFICATIONandANY.

Each class introducing newmodel featuresis required to declare a new feature clause withappropriate export status. The library provides a special marker classMML_SPECIFICATIONfor this purpose. By convention, model feature clauses are placed at the beginning of the classtext, annotated with the comment ’Model’. More details can be found in section5.2.1, inparticular theModel Feature Declaration Rule.

Page 72: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

6.4. USAGE OF THE CLASS LIBRARY 69

2. Inheritance Clause Declaration: Declare aninheritance clausefor MML_SPECIFICATIONif the class does not already conform toMML_SPECIFICATION.

In case themodel classunder specification does not already conform toMML_SPECIFICATION,let the class inherit fromMML_SPECIFICATIONaccording to theModel Class InheritanceRule of section5.2.1. The example below shows the newly introduced inheritance clause:

deferred classSET_EXAMPLE[G]

inheritMML_SPECIFICATION

feature {MML_SPECIFICATION, ANY} −− Model

set_model: MML_SET[G] is−− The set model

deferredensure

pure_feature: is_equal(old Current)result_not_void: Result/= void

end

end−− classSET_EXAMPLE

3. Model Selection: Select the appropriatemodel implementationsfrom the MML library to im-plement the identifiedmodel features.

Each one of the model features representing a particularabstraction functionhas to be mappedto corresponding classes of the MML library. Use a specific MML class which represents theappropriate abstraction. Note that combinations of several models are possible likeMML_PAIR[MML_SET[NODE], MML_RELATION[NODE, NODE]], which represents adirected graph.

4. Model Implementation: Implement eachmodel featuresuch that a validmodel instanceisreturned.

According to theModel Implementation step of section3.3 and theModel ImplementationRule of section5.2.1, model featureshave to provide anon-void resultrepresenting amodelobject. If the model featureis an attribute, this step can be neglected. In case themodel featureis a function, any implementation is required to create the corresponding ’Result’ entity andinitialize it in such a way that thepostconditionand theabstraction invariantof the modelfeature, and anygluing invariant involving that model, are satisfied. The code snippet belowshows a possible implementation of amodel featurerepresenting amathematical multiset:

Page 73: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

70 CHAPTER 6. THE MATHEMATICAL MODEL LIBRARY (MML)

deferred classBAG_EXAMPLE[G]

inheritLINEAR[G]

MML_SPECIFICATION

feature {MML_SPECIFICATION, ANY} −− Model

bag: MML_BAG[G] is−− The bag model

docreate{MML_DEFAULT_BAG[G]} Result.make_emptyfrom

startuntil

afterloop

Result:= Result.extended(item)forth

endensure

pure_feature: is_equal(old Current)result_not_void: Result/= void

end

end−− classBAG_EXAMPLE

5. Contract Specification: Specify the contracts of themodel class.

This step is analogous to the one described in section3.3.

6. Equality Relation: Implement theequality relationof themodel classaccordingly.

As described in section3.3, theequality relationis an important cornerstone of the specificationof classes with mathematical models. After the previous discussions, the rule is now very simpleto determine: Anymodel classintroducing one or moremodel featureshas to redefine existingimplementations ofis_equalor must introduce a newequality relation. Each introducedmodelfeaturehas to be tested for equality, and the results have to be ’and-ed’ with the result of theexisting implementation, if any. This ensures that an object is equal if and only if all its modelsare equal.

7. Gluing Invariants : Directly or indirectly relate all the introducedmodel featuresto the existingones.

This step is analogous to the one described in section3.3.

Page 74: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

6.5. LIMITATIONS OF THE CLASS LIBRARY 71

6.5 Limitations of the Class Library

Some of the current limitations of the MML class library are listed in this section.

The EIFFEL type system in the current standard [Mey92] has some shortcomings which haveturned out to be relevant for the design of the MML class library. Multiple inheritance of genericclasses can cause unpredictable behavior. If a classA inherits twice or more times from the sameclassB, but with differentactual generic parameters, polymorphic feature calls to features of classB cannot be correctly resolved. Renaming of feature names resolves all name clashes. But for theresolution of the correct feature implementation, we have to consider two separate cases: If theactualgeneric parametersconform to each other, withoutoverloadingof features there is no possibility toever resolve these feature calls correctly. Since the EIFFEL language does not offer overloading, caseswith conformingactual generic parametershave to be forbidden.

For non-conformingactual generic parametersthere is no reason to disallow multiple inheritanceof the same class. All feature calls can be correctly resolved from thestatic typeof the call target.Unfortunately, no EIFFEL compiler supports this at the moment. The tendency in the upcoming EIF-FEL standard [Mey] is to disallow multiple inheritance of the same generic class with differentactualgeneric parametersin general. More about this problem can be found in categoryEiffel Type Systemof section6.6.

Another limitation of the MML class library is partly related to its mathematical nature and partlyto its ’functional style’ implementation. Specifications using mathematical models offered by theMML library cannot express constraints involvingreference equality. The interface classesof theMML library model pure mathematical models, which are in no way related to the notion of refer-ences. Additionally, the design of the MML library only allowsimmutable objects, objects whoseapplicable operations are allpure. These two main characteristics of the MML library imply thatMML classes are not able to modelreference equality. In object-oriented systems, reference equalityis an integral part. It has to be investigated to what extentreference equalitycan be simulated bymathematical models.

The EIFFEL type system does not seem powerful enough to express mathematical models in atype-safe way. The missing option to declareanonymous generic parametersas in featurecomposed(other: MML_RELATION[H, I ]): MML_RELATION[G, I ] of classMML_RELATION[G, H] and theinability to declare thebase classof a type usinganchored declarationrequire a lot of patches in theimplementation to gain as much type-safety as possible. The approach during the design of the classlibrary has been to use as much type information as possible. For cases where the type system of theEIFFEL language is not able to give a solution, where have introduced the concept oftype stripping.The Typeable Facet(see section6.2.1) provides a feature to convert a mathematical object to anuntyped object. In these cases, type safety is not guaranteed anymore on thelevel of the elements in amathematical structure, but on theobject level, it is of course guaranteed.

Last, the current version of the MML library does not supportcontinuous functions. The imple-mentation class MML_DEFAULT_FUNCTIONcan only modelfinite discrete functions. However, theinterface class MML_FUNCTIONfully supportscontinuous functions. Clients of the MML librarywhich need support forcontinuous functionstherefore only have to provide a default implementationfor continuous functions.

Page 75: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

72 CHAPTER 6. THE MATHEMATICAL MODEL LIBRARY (MML)

6.6 Implementation Problems

The last section of this chapter about the MML library lists some of the problems that have been en-countered during the implementation of the class library. We are presenting the problems in differentcategories. All problems are referring to the MML implementation developed with ISE EIFFELSTU-DIO 5.3.

• Inline Agents:

• Functional Programming: Experience has shown thatinline agentsare a necessary andpowerful tool forfunctional programming, as required in IFLmodel contracts. Unfortu-nately, only the upcoming EIFFEL standard [Mey] supportsinline agents. In the currentversion of the MML class library, we have to resort towrapper features. Additionally,operator featuresare not supported by the ISE compiler. Allwrapper featureshave beendeclared with an ’obsolete’ clause stating that these wrappers can be removed as soon asinline agentsare implemented in the ISE EIFFEL distribution.

• Missing Compiler Support: The ISE compiler currently does not support the creation ofagents from attributes or constants. Luckily,attributesto be used asagentscan be declaredas functions returning the value of aninternal implementation attribute. The same alsoapplies toagentson open targetsof basic typesand classNONE. The ISE compiler isnot able to generate code for these language constructs, although the standard explicitlyallows these constructs.

• Class Interface:

• Declarations in Eiffel: The EIFFEL language has been designed to be strict with respectto feature declaration. Redefinitions of features have to be explicitly stated in afeatureadaptation clause. Together withfeature renamingandfeature undefinition, the adaptationclauses can become tedious to create and to maintain. A possible solution to this problemis given in categoryEiffel Language Specification.

• Missing Tool Support: This is a rather general problem. The EIFFEL community missessome powerful tools forrenamingof class featuresandattributes, and in general supportfor refactoring. Tools which are able to handle the complexfeature renaming operationsin EIFFEL classes would ease the work of the developer significantly, andseamless devel-opmentwould be put into practice finally.

• Design Decisions:

• Common Ancestor Class: Most of the time, the design of a class library requires thechoice for acommon ancestor class. After the initial design phase, it was clear that a classMML_ANYshould capture all properties common to mathematical objects such asmathe-matical equality, type informationandcompatibility. The question has arisen whether theelements in the mathematical structures also have to agree to acommon ancestor class.As it turned out, theobject equality relationinduced by classANYis sufficient.

Page 76: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

6.6. IMPLEMENTATION PROBLEMS 73

• Auxiliary Functionals : The MML classes are implemented using manygeneric func-tionals and higher-order agents. The first thought has been to include these function-als into the implementation classes ofMML_SET. However, classes likeMML_PAIRwhich do not inherit fromMML_SETalso need the facilities provided by higher-orderfunctions. Moreover, these facilities are probably also needed by clients of the class li-brary, which is the reason why these features have to be available in themodel interfaces.We therefore decided to create a newfacility class MML_FUNCTIONALSwhich pro-vides access tofunctionalsandhigher-order agents. Client classes simply inherit fromMML_FUNCTIONALSby facility inheritance.

• Generic Tuples vs. Pairs: The implementation ofgeneric n-tuplesis difficult if notimpossible to achieve with the current facilities offered by the Eiffel language and run-time environment (see categoryEiffel Kernel Classes). We have therefore decided toonly implement a specialized variant of atuple, 2-tuplesor pairs. Experience has shownthat pairs are sufficient for most uses. Additionally, the MML class library also offerssequences(classMML_SEQUENCE) which could be used asuntyped tuplesin the formof MML_SEQUENCE[ANY] instances.

• Covariant Result Types: Covariant redefinitionof feature result typessometimes canlead to code duplication when used in conjunction with multiple inheritance and the strictinterface/implementation separation principle (see section6.2.2) applied to the mathemat-ical models in the MML library (see classesMML_RELATIONandMML_FUNCTION.Nevertheless, we have decided to usecovariancewhere appropriate.

• Types vs. Set of Elements: The modeling of mathematical relations for the MML libraryhas raised the question whether a relation should be defined by adomainandrangesetwith a pair set describing the relationship between the two sets, or just by thepair setitself. More generally, it is unclear whether the type of thedomainandrangesets can bedescribed by the set of elements (thedomainandrange, respectively) itself. The advantageof the first approach is the ability to define a relation on parts of adomainset. Experiencehowever has shown that this is rarely needed. We have therefore decided to describe arelation by apair set, and to derive thedomainandrangesets from thepair setitself.

• Eiffel Type System:

• Declaration of Formal Generic Parameters: During the implementation of the modelclassMML_RELATION[G, H], different approaches have been implemented. One ap-proach uses formal generic set parameters to parameterize the domain and range set of re-lations. The formal parameter list looks likeMML_RELATION[D -> MML_SET[G], R->MML_SET[H]]. The class itself inherits consequently fromMML_SET[MML_PAIR[G,H]]. Unfortunately, the ISE compiler seems to dislike this construct and complains aboutunknownformal generic parameters GandH. This limitation can be circumnavigated bystating the generic parameters before declaring the set parameters as inMML_RELATION[G, H, D -> MML_SET[G], R -> MML_SET[H]]. In the current library version, a simplersolution has been found (see classMML_DEFAULT_RELATION).

Page 77: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

74 CHAPTER 6. THE MATHEMATICAL MODEL LIBRARY (MML)

• Anonymous Types: As already discussed in section6.2.6, the EIFFEL language doesnot allowanonymous types. Types derived fromgeneric classesare based on these classesand not on single features. The featurecomposedof classMML_RELATION[G, H] whichhas signaturecomposed(MML_RELATION[H, I ]): MML_RELATION[G, I ] is not validin EIFFEL. All known EIFFEL compilers complain about an unknown class nameI anddo not recognize thatI is a formal generic parameter. There are two solutions to thisproblem: First, one could write anauxiliary class MML_COMPOSITION[G, H, I ] whichwould implement the featurecomposeddescribed above and perform the necessary typecasts. Second,anonymous typescould be replaced byANY, thus loosing the relationshipbetween the argument type and the result type of featurecomposed. In order to avoid anexplosion of classes in the MML library, we have chosen the second approach.

• Generic Anchored Type Declaration: Featurecomposedof classMML_RELATIONposes even another problem. In order to ensure that relations can only be composed withrelations, and functions only with functions, we have to state that thefeature argumentsare either ofrelation or function type, but not mixed. Unfortunately,anchored declara-tion is only possible on atype basis, but in our case thebase classof the type should becovariantly declared; theformal generic parameterscannot be declared usinganchoreddeclaration. The signature of featurecomposedwould look like compose(like Current[H, ANY]): like Current [G, ANY]. Note that this is not a valid EIFFEL feature signature.Our proposal is to investigate the extension ofcovariant redefinitionto base classesoftypes. Theformal generic parameterscould be covariantly constrained as inFOO [G ->like Current], and the base class could be covariantly declared as (like Current) [G]. Inevery case, the usage of this extended form ofcovariant redefinitionis not limited to theexample above and would improve the expressiveness of the EIFFEL type system further.

• Constrained Genericity for Reference Types: Currently, the EIFFEL language does notprovide means to specify thatformal generic parametersshould be instantiated withrefer-enceor expanded typesonly. Sometimes this can lead to problems when using expressionsof generic types on the right-hand side of an assignment instruction. The solution is to useassignment attemptin conjunction with a creation constraint of the formFOO [G -> createmakeend]. However, this can yield circular reference in the inheritance clauses.

• Multiple Inheritance of Generic Classes: The current EIFFEL standard [Mey92] allowsa descendant class to inherit twice or more times from the same generic class with differ-ent actual parameters. Apart from the very complex feature adaptation clauses with large’ rename’ and ’select’ clauses to resolve name clashes and other ambiguities, this canalso cause unpredictable behavior. Consider the following example from the MML classlibrary: classMML_SET[G] implements theQuantifiable Facet(see section6.2.1) by in-heriting fromMML_QUANTIFIABLE[G]. Among the descendant classes ofMML_SET,classMML_POWERSET[G] provides specific operations on sets of sets and inherits natu-rally from MML_SET[MML_SET[G]]. The inheritedQuantifiable Facet is only definedon sets, but ideally we would like another one on the elements in the sets. The intro-duction of another inheritance relation withMML_QUANTIFIABLE[G] (the other one isnow defined on sets because of inheritance) causes problems: The ISE compiler is notable to resolve feature calls to quantifier features correctly anymore. Theoretically, afterresolving any name clashes, the settings are unambiguous. TypeG andMML_SET[G]never conform to each other, which makes it possible for the compiler to always deducethe correct feature from thestatic typeof thefeature call target.

Page 78: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

6.6. IMPLEMENTATION PROBLEMS 75

• Eiffel Kernel Classes:

• TUPLE: This class does not offer a feature toreversea tuple. Thereversed tupleof a tu-ple (a1, a2, . . . , an) is the tuple(an, an−1, . . . , a1), with its indexes sorted in descendingorder. Unfortunately, this class does not offer a way to dynamically create a tuple withthe necessary number of elements and their associated types. The number of types hasto be known at compile-time, which can not always be guaranteed. Consider the featureinversedof classMML_RELATION[G, H]: Since a relation is asetof pairs (2-tuples),inversing a relation means inversing the tuples contained in the relation. For the specialcase of pairs, the implementation ofinversedfor classMML_PAIR[G, H] is easy. How-ever, for general n-tuples, there is no way to implement aninversedquery because of themissing run-time reflection support. Since most of the functionality requiring tuples canbe implemented using pairs, it has been decided to only implement2-tuplesinstead ofgenericn-tuples.

• TUPLE: Another problem related to classTUPLE concernsobject equality. Tuple ob-jects can only be created as objects using the built-inreference equalitycomparison. If wewould want to store manifest integer constants (which are of typeINTEGER_REFsurpris-ingly), we get wrong results if we compare the content of the tuple with entities of typeINTEGER. The reason for this is the defaultreference equalitycomparison which cannotbe changed inmanifest tuples. A better policy would be to useobject equalitycomparisonas default, at least forbasic numeric types.

• Eiffel Language Specification:

• Old Expressions: A unique and very useful feature of the EIFFEL language are ’old’expressions, Boolean expressions inpostconditionswhich refer to thepre-stateof thecomputation, that is the state before the feature call. Unfortunately there is a problemin the language specification. An expression ’old e’ of type T is evaluated before thestatements of the feature implementation are executed. The result of the evaluation isstored in a reference entity of typeT. This approach works fine with expanded types likeINTEGER, REALand other basic numeric types, but does not yield the desired result withreference types. Recall the special assertion typePure Feature Assertion(see section3.3). Usually, these assertions are of the formis_equal(old Current). Since ’Current’ is aread-only entity whose reference value never changes, ’old Current’ is a tautology. In thiscase, the ’old’ expression only compares the two reference values instead of comparingthe two object pointed to by the references. It has to be noted that neithershallow equalitynordeep equalitywould be sufficient. A specialobject equality relationwould have to beintroduced, which does not consider the object structure itself, but rather the logical objectstructure. Extended type systems like theUniverse Type System[MPH99] may provide away out of this dilemma.

• Assignment Attempt: In EIFFEL, type casts (and in particulardynamic down casts) areimplemented using a special form of assignment ’?=’ calledassignment attempt. Thesemantics of this construct are the following: If the reference on the right-hand side is not’Void’ and conforms to the dynamic type of the left-hand side, the value is assigned to theentity of the left-hand side. Otherwise, the assignment target receives the value ’Void’.Unfortunately,assignment attemptin EIFFEL is an instruction rather than an expression,thus prohibiting its use in assertions. The solution would be to implementassignment

Page 79: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

76 CHAPTER 6. THE MATHEMATICAL MODEL LIBRARY (MML)

attemptas an expression or introduce an’instanceof’ operator as provided by the JAVA

language.

• Undefining Features: In the current EIFFEL standard [Mey92] only effected featurescan be undefined infeature adaptation clauses. However, in our opinion this languagerule is too restrictive for one important reason: If adescendant classeffects a deferredfeature inherited from anancestor class, and later on theancestor classdecides to providea general implementation for this feature, all clients are broken. Allowing to undefinedeferred featureswould help in this case and improveseamless developmentpromoted bythe EIFFEL method.

• Ternary Boolean Expressions: Assertions in EIFFEL frequently usecase differentiationin the form of ’a implies b and not a implies c’. Depending on the complexity of theexpressiona, assertions can become very complex and verbose. Aternary Boolean ex-pression’ if c then s elset end’ as provided by JAVA /C like languages, with boths andtbeingBoolean expressionsthemselves, would be a nice shortcut to makecase differentia-tion assertionseasier to read.

• Complex Feature Adaptation Clauses: The feature adaptation clauses of some MMLclasses are quite complex and become hard to manage. The EIFFEL language should pro-vide higher-level operations on feature adaptation clauses. Valuable operations would be:Prefix all feature names which yield a name clash with a common prefixp; Always selectthemost specialized implementationin case ofmultiple inheritance; Automatically rede-fine all features which arereimplementedin the class. The manual management offeatureadaptation clauseshas proven to be too tedious and error-prone. Afeature adaptationlanguagebased onregular expressionscould help in cases of very complex adaptationclauses.

• Grammar of Agent Call Targets: In the current EIFFEL standard [Mey92], the allowedconstructs foragent targetsare quite limited. The language grammar states that only’parenthesized’ expressions are allowed. Unfortunately, this restriction prohibits featurecall chains such as ’agenta.b.c.d.f(?)’. Feature implementations are not affected by thisrestriction, since temporary variables can be declared anytime. In assertions however, thisrestriction makes it impossible to specify many contracts with the use of agents.Inlineagentsintroduced in the upcoming EIFFEL standard [Mey] probably alleviate this prob-lem.

• Object Equality Relation:

• ANY: The equality relationis_equalinduced by classANY raises interesting problemsin the context of mathematical models. On the one hand, the static typing and the typesafety of the EIFFEL language has to be preserved inmodel implementation classes, buton the other hand,covariant redefinitionof the equality relationis_equal(other: likeCurrent) is too strong for many cases. Imagine an object of typeMML_RELATION[G,H] which has to be compared to an object of typeMML_SET[MML_PAIR [G, H]]. Incase the two objects contain the same pairs with the same elements (compared usingobjectequality), these objects should be considered equal.Covariant redefinitionof the argumentis therefore too strong. But a signatureis_equal(ANY) is neither desirable. The currentimplementation of the MML class library therefore does not useanchored declarationforthe feature argument, but insteadmanuallyredefines the argument type according to theimplementation class.

Page 80: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

6.6. IMPLEMENTATION PROBLEMS 77

• TUPLE: ClassTUPLEusesreference equalitycomparison as default. In some cases, thedefault setting is not sufficient and would have to be changed. For further information seecategoryEiffel Kernel Classes.

Page 81: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

78 CHAPTER 6. THE MATHEMATICAL MODEL LIBRARY (MML)

6.7 Further Work

The last section of this chapter provides an overview of the future development of the MML classlibrary. In our opinion, the main topics are:

• High-Level Mathematical Models: The current version of the MML library only providesmodels for the most fundamental mathematical notions likepairs, sets, relations, functions,multisetsandsequences. Graphsare supported by classMML_GRAPH. Based on this class,models fornetworksand treesare easily implemented. Other more complex mathematicalstructures can be composed from the existing models.

• Support for Continuous Functions: The model interface class MML_FUNCTIONalreadysupportscontinuous functions. However, the current version of the class library does not providean implementation forcontinuous functionsor for infinite functions. It has to be investigatedwhether these types of functions are indeed necessary, and how easily implementations for theseconcepts can be created.

• Introducing Inline Agents : The upcoming EIFFEL standard [Mey] introducesinline agents,the ability to use ananonymous feature implementationasagent. Currently, the MML libraryuses a lot ofwrapper featuresto compensate for the missing concept ofinline agents. Hopefully,themodel implementation classescan be cleaned up significantly usinginline agents.

• Introducing Operators : The currentmodel interface classesof the MML library do not sup-port prefix and infix operators. The limited support of the EIFFEL language forfree operatornamesrestricts the use of operators significantly. In the upcoming EIFFEL standard [Mey], freeoperator namescan consist of a larger set of characters, making the selection of operator nameseasier.

Page 82: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Chapter 7

Specifications of Fundamental DataStructures

In this part of the thesis report we apply the acquired mathematical concepts to the most fundamentaldata structures of the EIFFELBASE library, using contracts written in the IFL language supported bythe MML library.

7.1 Overview

We have treated the necessary mathematical background in chapter4. Based on these insights and thepresentations of the IFLcontract language(chapter5) and the MMLclass library(chapter6), wegive the proof of concept that a collection of mathematical notions in conjunction with an expressivefunctional contract language and a powerful class library are indeed sufficient to specify advanced datastructures. In section7.2 we describe our approach to annotatedata structuresof the EIFFELBASE

library with mathematical models. Based on this specification experience, we are listing eventualproblems encountered in the specifications of EIFFELBASE classes in section7.4. Section7.6 dis-cusses how to further use the annotated EIFFEL classes. In the last section of this chapter (section7.5)we also shed some light on the benefits of mathematical models for specification of class libraries.

7.2 The Specification Process

The specification process for the EIFFELBASE library should be efficient and finally produce classspecifications which are ascompleteas possible. Since thedata structure classesof the EIFFELBASE

library usually have a relatively large class interface, we are going to restrict ourselves to the mostcommonly used abstractions, in order to favor completeness of the specifications. We therefore try tochoose a set of classes which is as representative as possible and which shows most of the problemsthat can occur during specification. Our approach to specify thedata structure classesinvolves thefollowing steps:

79

Page 83: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

80 CHAPTER 7. SPECIFICATIONS OF FUNDAMENTAL DATA STRUCTURES

Data Structure Specification Process:

1. Determine the most genericcommon ancestorclassesA.

2. Introducemodel features ffor the current classC if necessary.

3. Specify the contracts of all features in theflat formof C using all previously introducedmodelfeatures f.

4. Determine alldirect descendantsof C which areancestorsof at least one EIFFELBASE datastructure classand continue with step (2).

We now provide a more detailed description of each step of thedata structure specification process:

Step (1) is used to determine thecommon ancestorsof the class set chosen to be specified withmathematical models. In the EIFFEL type system, computing acommon ancestorclass is a trivialtask: All EIFFEL classes automatically inherit from thepredefined class ANY. We therefore start thespecification process in classANY, meaning that the current class is set to classANY.

Step (2) describes how to introduce newmodel featuresdesigned to represent a newfacet ormathematical abstractionimplemented by the current class. If the abstraction represented by classCis not yet concrete enough to be captured by mathematical models, we leave allexisting contractsandtry to complement them with the different contract types identified earlier (section5.3.2).

Otherwise, if we can identify amathematical abstractionwhich can be represented by a mathe-matical model, we introduce one or moremodel featuresof appropriate type. The process of introduc-ing new models cannot be formally described, but has to be rather guided by experience and intuition.More on this topic is listed under theModel Type Ruleof section5.2.1.

In step (3) we perform the actual specification of the current classC. To this purpose, we usethe flat form F of C. The introduction of newmodel assertionsis doneincrementally. We considerthe feature contractsin F. If no model assertionexists already for a particularmodel feature f, weintroduce a new one, describing thecontractwith respect to the particularmathematical abstractionrepresented byf. We use the following kinds of assertions for the EIFFELBASE class specifications:

• Definition Assertions: To define theresultcomputed byfunctions.

• Pure Feature Assertions: To express that an EIFFEL feature does not change thestateof thecurrent object.

• Immutable Argument Assertion: To state that objects passed asactual feature argumentsarenot changed by an EIFFEL feature.

• Other Regular Assertions: Regular EIFFEL assertions describingpreconditionsandpostcon-ditions.

Page 84: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

7.3. THE EIFFELBASE CLASS SPECIFICATIONS 81

For class invariants, we use the following kinds of assertions:

• Abstraction Invariants : Invariants describingabstraction functionsof mathematical models.

• Gluing Invariants : Invariants that relate severalmodel featurestogether.

• Model Invariants : Invariants specifyingglobal constraintsonmodel features.

• Other Regular Invariants : Regular EIFFEL assertions describingclass invariants.

Note that some kinds of assertions have to be updated with every newmodel featuresthat is introduced.This is the case withpure feature assertions, whereimmutabilityof the model has to be verified, orwith definition assertionsand various other kinds ofinvariant assertions.

Step (4) finally describes the process of moving upward in the EIFFELBASE class hierarchy. Weconsider all thedirect descendantsof C and check whether they areancestorsof one of thedatastructuresthat we want to specify. These classes are exactly the candidates to continue with thespec-ification process. After having determined the set of valid classesV for another iteration, we starttheData Structure Specification Processon all the candidates, but beginning with step (2). The fi-nal result of this process is aclass hierarchyfor thedata structure classesusing mathematical models.

In the next section, this process is applied to a representative set ofdata structure classesbelong-ing to the EIFFELBASE class library.

7.3 The EiffelBase Class Specifications

We introduce thedata structuresto be specified in this chapter. The framework developed so far, inparticular the IFLcontract languageand the mathematical models from the MMLclass library, isapplied todata structuresof the EIFFELBASE class library. We choose the classes to be specifiedaccording to the following criteria:

1. Usage of the Data Structure: Choosedata structuresfrom the EIFFELBASE that are widelyused in common applications

2. Diversity of Concepts: Select classes that representabstract conceptswhich are as original aspossible

3. Sufficient Documentation: Choose classes whose abstraction can be derived from thefeaturecommentsas easily as possible

As it turns out, criterion (3) is the one which is satisfied the least. Most EIFFELBASE classes containonly shortenedfeature commentswhich range from one to three lines of text. The real shortcominghowever are the rudimentary classheader commentsin the ’indexing’ clauses. All the properties of aclass that cannot be expressed in aclass invariantshould be stated in the ’indexing’ clause. The samealso applies tofeature comments, which are designed to listpreconditionsandpostconditionsthat arenot stated in a ’require’ clause and an ’ensure’ clause, respectively.

Page 85: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

82 CHAPTER 7. SPECIFICATIONS OF FUNDAMENTAL DATA STRUCTURES

We therefore have to search fordata structure classeswhich are sufficiently documented and com-monly used. Based on the criteria mentioned above, we choose the following classes:

• BAG: Deferred class implementing the concept of amathematical multiset(see section4.8.2)

• LINEAR_SUBSET: Deferred class representingmathematical sets(see section4.4) which addi-tionally can betraversedin a linear order.

• DYNAMIC_LIST: Deferred class representing the concept of alinearly traversable sequence ofelementswhich can bedynamicallymodified.

• STACK: Deferred class representing alast-in first-out dispenserwithout any concrete imple-mentation.

• QUEUE: Deferred class representing afirst-in first-out dispenser, also without any concreteimplementation.

Figure 7.1: The EIFFELBASE Class Specifications

Page 86: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

7.4. SPECIFICATION PROBLEMS 83

The specifications for the five classesBAG, LINEAR_SUBSET, DYNAMIC_LIST, STACKandQUEUEare given in appendixC. The complete collection of specifications can be found in the MML codebase in the following clusters:

• specification/hierarchy: The EIFFELBASE class hierarchy specifications

• specification/structures: The EIFFELBASE data structure specifications

7.4 Specification Problems

The specification of the set of chosendata structure classessometimes was not easy and lead to thediscovery ofheavy underspecification, contradictionsin contractsand flaws in thetaxonomyof theEIFFELBASE library. We discuss the encountered problems in two sections. First, we listgeneralproblemsnot involving a particular class in section7.4.1. Section7.4.2lists problems which are di-rectly related to a specific EIFFEL class. If possible, we would also like to give a possible solution forthe problem being discussed.

All problems mentioned in the next two sections are referring to the implementation of EIFFELBASE

shipped with ISE EIFFELSTUDIO 5.3.

7.4.1 General Problems of EiffelBase

The section of general EIFFELBASE-related problems is divided into several problem categories. Eachcategory describes an aspect of EIFFELBASE which caused problems with respect to specification withmathematical models.

• Active Data Structures:

• Iteration Facilities : Internal cursors ofactive data structuresand functionals such asfor_all, there_existsanddo_all do not represent the same concept and should bestrictlydistinguished. ClassTRAVERSABLEintroduces both cursor featuresstart and after aswell as support for quantifiersfor_all, do_all, and so on. However, functionals likedo_allare already applicable in classCONTAINER. Thelinearity of theTRAVERSABLEclass isnot necessary for an implementation of logic quantifiers.

This problem manifests itself in classTRAVERSABLE_SUBSET. Besides that the classdoes not inherit fromTRAVERSABLE(despite its apparent similarity), it represents awrong abstraction. We cannot define a currentiteration elementof a set, since sets tonot have a definedorder on their elements by definition. Hence features implementingoperations on a cursor do not make much sense in such classes. However, the functionaldo_all and the quantifiersfor_all and there_existsare well defined on sets and shouldtherefore belong to the class interface ofTRAVERSABLE_SUBSET.

One solution to this problem arefacetsas presented in section6.2.1.

Page 87: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

84 CHAPTER 7. SPECIFICATIONS OF FUNDAMENTAL DATA STRUCTURES

• Equality Relation: Theequality relationof active data structuresinvolves not only theelements of the structure, but also acursor positionand other internal data. Unfortunately,it is nowhere specified whether twoactive data structureswith the same elements butdif-ferent cursor positionsare considered equal. We have decided to neglect cursor positionsand to only compare the elements of the structures.

• Polluted Code: Generally, the EIFFELBASE classes representingactive data structurescontain a lot of code related tostructure traversal(internal iterators). It can be arguedwhether a cleaner separation of data structure- and iteration code is desired. In our view,the use ofexternal iteratorscould bring many advantages from the developer’s point ofview. External iteratorsare concurrent, groupiteration-related codetogether and can bepart of anindependent class hierarchyof iterators. The other less radical solution is tofollow more the interface/implementation principle and to usefacets(see sections6.2.1and6.2.2).

• Composite Features: Manyhigh-level operationslike the featuremerge_leftof classDY-NAMIC_CHAIN internally use a cursor to search and update elements in the structure.This is very convenient from animplementation viewpoint, but dangerous from anoper-ational point of view. Although the EIFFELBASE class library has not been designed forconcurrent use, featureoccurrencesof classLINEARdemonstrates why this approach issometimes not the best one: The implementation ofoccurrencesis notpurebecause of thecalls to featuresearch. This feature is inherentlyimpure, thanks to theCommand/QuerySeparation Principle[Mey97]. The common understanding of the semantics of featureoccurrenceshowever suggests that it should have apure implementation.

• Class Hierarchy:

• Abstraction of Classes: The EIFFELBASE class library contains many classes which donot introduce features for themselves, but instead inherit from a number of distinct classesrepresenting totally different concepts. The problems with this approach once more lie inthe the contracts: Not all features of the original concept also make sense in the derivedconcept. Let use show this problem with an example: classINTEGER_INTERVALinheritsfrom SETto express thecollection-characterof an interval. This inheritance relationshipseems unnatural for two reasons: First, intervals have atotal order and could thereforebetter be modeled by sequences. Second, even though classSETis deferred, it alreadycontains to much functionality such as element removal which is not applicable here. Aclear distinction ofimmutableandmutable structurescould help in this case.

• Feature Introduction vs. Facet Accumulation: This is a rather general problem andinvolves two common design strategies: On the one hand aninheritance hierarchyofimplementation classeswhich introduce new features as soon as the become necessary,and on the other hand aninheritance hierarchyof classes which implement a set ofinter-face classeswhile choosing partial implementations from a set of otherimplementationclasses. A good example to illustrate these two different methods is thedeferred classBOX: It only introduces a new featurefull, but inherits from classCONTAINERas well.Clients which want to use thefull aspect automatically inherit a container behavior, whichis not necessarily desired. ClassBOXwould be a lot more useful if it did not inherit fromCONTAINER, and clients ofBOXwould inherit from the correspondingfacet classesmod-eling the desired container behavior.

Page 88: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

7.4. SPECIFICATION PROBLEMS 85

• Linearity/Bi-linearity : Are indeed both concepts needed in the EIFFELBASE? ClassBILINEAR, which inherits twice fromLINEAR, is not easy to specify, since it is notclear whichiteration featuresare contributed by whichinheritance relationwith LIN-EAR. Using a more general implementation using appropriate status queries such asfor-ward_traversable, backward_traversableand adaptedpreconditions, BILINEAR couldalso be used as a replacement forLINEAR.

• Read Only Operations: Related to the problem of classINTEGER_INTERVALwith itsSET implementation, it has to be investigated to what extent classes representingim-mutable structurescould be introduced in the EIFFELBASE library. Immutable setswouldsolve the above-mentioned problem. Generally, an implementation formutable struc-turesshouldinherit from animmutable structure. The EIFFELBASE classCOLLECTIONdemonstrates this dilemma quite well: It provides too many operations for element changewhich are not used anymore indescendant classesmodeling immutable structureslikeTUPLEor INTEGER_INTERVAL.

• Specification Style:

• Void References: The designers of the EIFFELBASE class library use atolerant styleforpreconditions: References to ’Void’ are implicitly allowed, but the MML library cannothandlevoid references. There is no concept ofreferencesin mathematics, but onlyobjectidentities. The goal of the MML library is to model mathematics as closely as possible,which prohibitsvoid referencesas elements in data structures. Nevertheless references to’Void’ can be modeled by adummy void objectwithout any loss of generality.

• Indexing of Arrays : The mapping ofmodel indexesto structure indexesis not explicit.In order to be as general as possible, we would have to define amapping functionwhichtakes care ofindex conversion. Since the EIFFELBASE library uses thecanonical non-zerobased indexing, we use thisindexing stylein the MML class library as well.

• Feature Naming:

• Uniform Feature Naming: The EIFFEL style guidelines suggestuniform namingof fea-tures which perform similar or analogous operations. However, the plan ofemphasizingcommonalityis sometimes pursued too careless. Different concepts like the currentitera-tion elementof a data structure (classTRAVERSABLE) and the result of anagent functioncall (classFUNCTION) both use the feature nameitem. In this case, the emphasis on com-monality is not justified in our opinion and yields a class interface which is unnecessarilyhard to understand.

• Higher-Order Functions:

• Linearity and Functionals/Quantifiers: ClassLINEARintroduces the higher-order func-tions for_all, there_exists, do_all. These functionals have nothing to do with the conceptof linearity and should be moved up to the level of collections (classCOLLECTION). Seealso categoryActive Data Structures.

Page 89: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

86 CHAPTER 7. SPECIFICATIONS OF FUNDAMENTAL DATA STRUCTURES

• Pure Objects:

• Pure Methods: The EIFFELBASE library strictly follows object-oriented design princi-ples. Most feature calls are of the formx.f wherex is the current object (the target ofthe feature call) andf is the name of the feature to call. These features arecommandswhich apply the operation to the target, but do not return a new object. The problem withthis approach is that all these features are notpure. However, in mathematics there existsno concept of mutable objects. Additionally, feature calls involving commands cannotbe used in expressions, thus prohibiting the use of these features in assertions. A goodexample for this discrepancy is classSETwith its featuresintersect, subtractandmerge.

• Specification of Axioms: Since the EIFFELBASE library does not adhere to mathematicalstandards (there are no functions which return the changed object, but leave the targetof the feature call intact), it is not possible to state important axioms without resortingto cloningor creation expressions. Consider theclass invariantfrom an imaginary classRELATION[G, H]:

inversed.inversed.is_equal (Current) (7.1)

Most classes of the EIFFELBASE do not allow to express axioms like the above one, sincethey only offerimpure featureswhich would change the state of the current object duringthe evaluation of assertions. The solution is to resort tocloning (calling the feature onthecloned object) or creation expressions(calling the feature on an anonymously createdobject), both of which lacks simplicity and clarity.

• Reusability of Contracts:

• Sequence Model Contracts: During the specification of the data structures, it has becomeapparent that too manysequence modelswhere used. As mentioned in section7.5, thiscould be the sign of a design problem in the class hierarchy of EIFFELBASE. Either theabstraction of a sequence has been overused, or the designers failed to extract a sufficientlygeneral concept of animmutable sequence.

7.4.2 Class-Specific Problems of EiffelBase

The section forclass-specific problemsof the EIFFELBASE library lists the problems in the order ofthe class they appear. Each problem is associated with one or more features, or marked as a conceptualproblem. We explain the problem in short and try to give a possible solution if possible, similar tosection7.4.1. The following list of problems is certainly not complete, but gives an overview of themost important issues and the diversity of problems encountered during specification.

• ARRAY

• prunable, extendible: These queries always return ’False’, since the size of an array cannotbe changed. In the descendant classARRAYED_LIST, they always return ’True’, becausearrayed lists automatically grow upon inserting new elements. This can lead to somehowconfusing contracts such as the ones in featuresextendandprune.

Page 90: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

7.4. SPECIFICATION PROBLEMS 87

• wipe_out: Obsolete clauses are certainly not the right way to declare a feature asinappli-cable. Since the number of elements in an array cannot be changed by definition, classARRAYshould not inherit fromCOLLECTION, or COLLECTIONshould factor out theoperations applicable toimmutable collectionsto a separate class, and letARRAYinheritfrom it. Moreover, the implementation ofwipe_outcallsdiscard_items, which has a con-tract with completely different semantics.

• BAG

• CONCEPTUALPROBLEM: ClassBAGis located too high in theclass hierarchyof EIFFEL-BASE. All implementation classes modeling the concept of sets such asARRAYED_SETalso inherit from classBAG, thus also inheriting featureoccurrences. Although set im-plementations of occurrences always return1, sets usually do not offer such features. Itseems that classBAGis a too general class, not representing the mathematical counterpartof amultiset, but rather the concept modeled by theExtendible Facet(see section6.2.1).

• CHAIN

• index_of: ClassCHAIN redefines this feature and implements a wrapper which remem-bers the current cursor position before a call to theimpure implementationprovided byfeaturesequential_index_of, and restores it afterwards. It is not clear why theancestorversionof index_ofis not apure featurein the first place.

• index_of, sequential_index_of: These features areheavily underspecified: It is not appar-ent what happens if the element whose index has to be retrieved is not in the chain. Onlythe feature comments provide further help, but in a rather minimalistic way.

• remove: This feature needs apreconditionwhich states that the cursor should be at avalidposition. Unfortunately, that cannot be covered by the existing featureprunable. Foroperations likeremove, one more general feature similar toextendibleandprunable isrequired to express assertions related tocursor positions.

• start, finish, forth, back: These features do not specify their effect on an empty chain.

• CONCEPTUAL PROBLEM: ClassCHAIN inherits twice fromSEQUENCE. ClassSE-QUENCE itself inherits fromBILINEAR, which inherits twice fromLINEAR. It is notclear why a chain should implicitly inherit four times from classLINEAR. It neither seemsjustified to introduce aninheritance relationto reuse thepartial implementationsof LIN-EAR and BILINEAR, respectively. Due to the duplication of features in classCHAIN,many features have to be renamed and hidden, leading to potential CATcalls [Mey97].

• CONCEPTUAL PROBLEM: Since classCHAIN inherits twice fromSEQUENCE, it alsoinherits twosequence models. At first sight, it seems like these two features have to be keptdistinct. However, from a physical point of view, they represent the same mathematicalsequence (the data structure represented by classCHAIN) and can therefore be merged.From a mathematical point of view, this is an argument not to inherit more than once fromSEQUENCE, or more general, from a class providing the samemodel feature.

Page 91: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

88 CHAPTER 7. SPECIFICATIONS OF FUNDAMENTAL DATA STRUCTURES

• COLLECTION

• fill : This feature has been proven very problematic to specify in all its occurrences in theclass hierarchy of the EIFFELBASE library. Thefeature commentstates that the imple-mentation ”[fills] the current object with as many elements from the other structure aspossible”. The only preconditionof fill expresses thatextendiblemust be ’True’. Vaguespecifications as this one make it nearly impossible to apply mathematical model specifi-cations.

• CURSOR, CURSOR_STRUCTURE

• CONCEPTUAL PROBLEM: The intent of classesCURSORandCURSOR_STRUCTUREis not obvious. The EIFFELBASE class library usesactive data structureswith internalcursors. It is not clear why classCURSORand a wholeclass hierarchyof cursor classeshave been introduced in the first place.

• DYNAMIC_CHAIN

• put_front, put_left, put_right and others: Thefeature commentof these features states:”Do not move cursor”. There are at least two ways of interpreting this sentence. First,not moving the cursor could mean that the cursor stays on the same element after thefeature call as before. Second, it could denote that the cursor position itself is not changed.In our opinion, the first interpretation makes more sense. Additionally, it is not clearwhat happens when the cursor is at an undefined position. The tolerant contract styleof EIFFELBASE complicates a rigorous specification of such features with mathematicalmodels.

• DYNAMIC_LIST

• CONCEPTUALPROBLEM: ClassDYNAMIC_LISTinherits twice fromDYNAMIC_CHAIN.Like classCHAIN, it seems not justified to inherit fromDYNAMIC_CHAINjust to reuseits (partial) implementation. Obviously,mismatchesin thecontractsprohibited the use ofsimple redefinitionand the ’Precursor’ keyword, which is a sign of an unjustifiedinheri-tance relation.

• INTEGER_INTERVAL

• capacity: This feature has hiddenassertion checkswhich are not implementation-related.The ’check’ clause contains assertions requiring defined lower and upper bounds. In fact,these assertions are hidden contracts, which should be rather declared in aprecondition.

• extend, put: These features are inherited from classINDEXABLEand renamed. ClassINTEGER_INTERVALthen introduces new featuresextendandput with implementationsto extend therange of the interval. All feature contracts are also inherited, but meansomething completely different in this context: The contracts ofINTEGER_INTERVALstate that the bounds of the interval have to be set, whereas the contracts ofINDEXABLEexpress that a key-value pair is inserted into a container. Moreover, the contracts alsocontradict those inherited from classSET.

Page 92: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

7.4. SPECIFICATION PROBLEMS 89

• wipe_out: The inheritedpostconditionof wipe_outstates thatis_emptyshould be ’True’,but theinterval boundsyield a capacity of two: the attributelower_internalis set to0 andupper_internalto 1, therefore the capacity isupper_internal − lower_internal + 1.This contradicts with thedefinition assertionof featureis_empty.

• prune, indexable_put: These features have been commented asinapplicable, their con-tracts however state a change of the models of this class. Although the implementation ofthese features is empty, this could potentially lead to contradictions in the contracts.

• CONCEPTUAL PROBLEM: The notion of logic quantifiers is reimplemented in classIN-TEGER_INTERVAL. This class defines its own featuresfor_all andexiststo implementuniversalandexistential quantifiers. Actually, classSETshould have introduced this con-cept already, or classINTEGER_INTERVALcould implement theQuantifiable Facet(seesection6.2.1).

• CONCEPTUAL PROBLEM: Why should an integer interval of classINTEGER_INTERVALbe indexable by integers itself? Intervals are completely defined by bounds, and checkswhether an integer is in the interval are simple range checks on its bounds. Therefore theimplementation as anindexable data structureis hardly justified.

• LINEAR

• has: The implementation of this feature usesstart which is notpure, and does not revertthe cursor position. If the implementation ofhasneeds to move theinternal cursor, itshould at least remember thecursor positionand restore it later.

• occurrences: The same problem as in featurehasalso arises in featureoccurrences: Theimplementation uses theinternal cursorand calls featuresearch, which isimpureby def-inition (Command/Query Separation Principle[Mey97]).

• CONCEPTIONAL PROBLEM: ClassLINEAR introduces the concept of alinear sequencewith a cursor positionafter and the queryoff. As already discussed in categoryClass Hi-erarchy of section7.4.1, it can be argued whether the two concepts linearity/bi-linearitycould be merged. In our opinion, the more general concept ofbilinear sequencesis prefer-able. Two additional queries to determine whether the cursor can be moved forward andbackward have to be introduced. Thepreconditionsof the corresponding features wouldcall these queries if the cursor has to be moved.

• LINEAR_SUBSET

• extend: Thepreconditionof this feature simply states that the element is a member of theset after the feature call. However, nothing is said about where the element is insertedif not already in the structure. SinceLINEAR_SUBSEThas adefined orderon the setmembers, this is an important point which has to be stated in the feature contracts.

• merge: What happens to thesequence modelof the current object when merging two sets?In this case one can only guess, and is therefore not able to give a rigorous specification.

• wipe_out: A similar problem occurs in featurewipe_out. It is not clear what happensto the cursor after a call towipe_out. As it turned out, some implementations ofLIN-EAR_SUBSETmove the cursor toafter and some move it tobefore.

Page 93: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

90 CHAPTER 7. SPECIFICATIONS OF FUNDAMENTAL DATA STRUCTURES

• CONCEPTUAL PROBLEM: ClassLINEAR_SUBSETrepresents an ambiguous concept.Mathematical setsdo not have apartial order by definition. It can be doubted whetherclassLINEAR_SUBSETrepresents a valid concept. Indeed, as it turns out in descendantclasses, the fact thatLINEAR_SUBSETalways has a currentiteration elementis not com-patible with the notion of a set. Moreover, an iteration over a linear set which changesthe set itself has undefined results. The result of these operations is not dependent fromthe order of the elements, but from the non-determinism in the data structure. Such adependency is clearly not desired.

• CONCEPTUAL PROBLEM: ClassLINEAR_SUBSETprovides the featurebeforeand allother features of classBILINEAR, but does not inherit from it. This problem actuallyraises already in classTRAVERSABLE_SUBSET. See alsoTRAVERSABLE_SUBSET.

• LIST

• CONCEPTUAL PROBLEM: ClassLISTcontains only feature implementations which couldhave been introduced already inCHAIN. In order to simplify the class hierarchy of theEIFFELBASE library, this class could be merged withCHAIN.

• QUEUE

• extend, put, force: These features have been declared assynonymsin classQUEUE. How-ever,ancestor versionsof extenddo not move the cursor position, whereas everyextendin a queue sets the new tail element (and therefore changes also the cursor position). Thiscould lead to contractions inmodel contracts.

• CONCEPTUAL PROBLEM: The concept of an queue contains no current element, but onlya headand atail element. What effect do the implementations ofitem, prune, remove,replaceand others, have on the currentiteration element? Once more, we have to make anassumption that the currentiteration elementis equal to thehead element, the element thatis going to be dequeued next. Thereforeremoveandreplaceoperate on thehead elementandforcesets the newtail element.

• SEQUENCE

• prune, prune_all: It is not clear why these features should move the cursor tooff incase the element to be pruned is not found. These kind of side-effects are dangerous andunnecessary, since the occurrence of an element can be verified before. Featurepruneshould leave the cursor unchanged in this case.

• TABLE

• bag_put: Featureput of classBAG is not applicable to tables. It is renamed and hiddenin order to not occupy the feature name for the featureput of classTABLE, which is usedto associate a value with a key. Once more, feature hiding rises the question whether theinheritance relationbetween these two classes is indeed justified.

• extend: ClassTABLEinherits the featureextendof classBAG. This feature is not hiddenand therefore part of the class interface. It is not clear whichkeythevaluepassed asactualfeature argumentis associated with. Unfortunately, the feature comments do not providefurther information.

Page 94: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

7.4. SPECIFICATION PROBLEMS 91

• put: The featureput (value: G; key: K) is not specified at all. A possiblepostconditionwould beitem(key).is_equal(value).

• prune: Index structureslike TABLEusually containvalueswhich occur multiple times inthe structure. However, featureprunedoes not specify whichvalueis removed from thestructure, or whether allvaluesassociated with anykeyare removed.

• CONCEPTUAL PROBLEM: We already mentioned this problem regarding theinheritancerelation betweenINTEGER_INTERVALandINDEXABLE, a descendant class ofTABLE.In addition to the problem stated there, classTABLE is sometimes used in places wherethe keysin the table have to be occurring in strictly ascending order, like in sequences.ClassTABLEseems to be the wrong abstraction in these cases.

• Conceptual Problem: Thekeysof a table are stored as aset, since they have to be uniquewithin the structure. ClassTABLEhowever inherits fromBAG. It is not clear whetherthemultiset-characterof classTABLEshould refer to the values in the structure. A morenatural approach would be to express theset-characterof the keys in the table.

• TRAVERSABLE, TRAVERSABLE_SUBSET

• is_empty: This feature is still deferred, but theclass invariantalready demonstrates acorrect implementation:Result= (count= 0). Therefore, the feature could be effectedearlier in theinheritance chain, e.g. already in classSET, which provides the necessaryfeaturecount.

• CONCEPTUAL PROBLEM: ClassTRAVERSABLE_SUBSETdoes not inherit from classTRAVERSABLE, even though classTRAVERSABLE_SUBSETimplements all features of-fered byTRAVERSABLE. This design decision prohibits any polymorphic use of instancesof classTRAVERSABLEand yields toextensive code duplication. The reason for this deci-sion is apparent.TRAVERSABLEis adata structure classand not afacet class. Modelingclass hierarchies morefacet-orientedas the MML class library does helps to avoid thesekind of problems.

• CONCEPTUAL PROBLEM: Since classTRAVERSABLE_SUBSETdoes not inherit fromclassTRAVERSABLE, all iteration-related featuresandquantifiershave to reimplemented.Surprisingly,TRAVERSABLE_SUBSETprovides noquantifiersand only asubsetof theiteration featuresintroduced inTRAVERSABLE. In our view, the last two conceptual prob-lems arise because of the lack of agents at the time of the design of the EIFFELBASE,which could have been used in features likedo_all.

• CONCEPTUAL PROBLEM: All descendants fromTRAVERSABLE_SUBSETsuffer fromthemismatchof linearity andmathematical sets. The descendant classLINEAR_SUBSETeven forces atotal orderon the clients of this class.put_leftandmove_itemare operationswhich cannot be defined on sets. The situation is even aggravated in descendants likeLINKED_SETor ARRAYED_SET, which introduce several other features involvingcursormovementsor are dependent on atotal order.

Page 95: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

92 CHAPTER 7. SPECIFICATIONS OF FUNDAMENTAL DATA STRUCTURES

7.5 Benefits of Mathematical Models

We have shown a relatively extensive list of problems which turned to surface during the specification(see section7.2) of the EIFFELBASE classes. Based on the experience gained during thespecificationphaseand itsoccurring problems, we try to compile a list of thebenefitsthat mathematical modelscould bring if applied todata structure classeson a regular basis:

• Partial State Change Specification: Ability to specify which parts of thestate spacechange

Mathematical models ease the difficulty of specifying that certain aspects of an object arechanged by a feature call. Let us take an example from the EIFFELBASEclassDYNAMIC_CHAINto illustrate this point:

Example: Sequence Element Extension

deferred class interfaceDYNAMIC_CHAIN_EXAMPLE[G]

feature−− Element change

put_front(other: like item)−− Add ‘other’ at beginning.−− Do not move cursor.

requireother/= void

ensuresequence.is_equal(old sequence.prepended(other))(old cursor>= sequence.lower_bound) implies cursor.is_equal(old cursor+ 1)sequence.first.is_equal(other)(old cursor< sequence.lower_bound) implies cursor.is_equal(old cursor)other.is_equal(old other)bag.is_equal(old bag.extended(other))indexable.cardinality.is_equal(old indexable.cardinality+ 1)(old not sequence.is_defined(cursor)) implies not sequence.is_defined(cursor)

end−− classDYNAMIC_CHAIN_EXAMPLE

In this example thestate spacerepresenting thesequence with its elementsis changed, whereasthecursor stateremains the same under this operation.

• Definition Assertions: Assertions to specify computation results inpostconditions

Mathematical models facilitate the specification of features that perform complex tasks. Thefollowing example again is an extract from the EIFFELBASE library, showing a query that de-termines whether another set isdisjoint with the current one:

Page 96: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

7.5. BENEFITS OF MATHEMATICAL MODELS 93

Example: Set Disjointness Property

deferred class interfaceSUBSET_EXAMPLE[G]

feature−− Disjointess

disjoint (other: SUBSET_EXAMPLE[G]): BOOLEAN−− Do current set and‘other’ have no items in common?

requireother/= voidobject_comparison.is_equal(other.object_comparison)

ensureResult.is_equal(set.is_disjoint(other.set))Result.is_equal(set.intersected(other.set).is_empty)(set.is_emptyor other.set.is_empty) implies Resultis_equal(old Current)other.is_equal(old other)set.is_equal(old set)

end−− classSUBSET_EXAMPLE

• Specification of Abstract Axioms: Feasibility to stateaxiomsasclass invariants

Mathematical models provide ahigh-level view of specificationthat favors short and expressivecontracts. Expressing strongclass invariantsusing conventional EIFFEL facilities is sometimesimpossible sinceclass interfacesnormally are not designed to beside-effect free. However,model class libraries like the MML library which are particularly designed for specificationusing mathematical models guaranteeside-effect freeness, making the specification ofaxiomsalot easier.

Example: Complete Graph

Consider a classCOMPLETE_GRAPHwith two model features nodesandedgesrepresentingthe set of nodes belonging to this graph and its associated edge set expressed as a relationover the node set, respectively. The obviousclass invariantfor COMPLETE_GRAPHcan beexpressed in one line:

nodes.cartesian_product (nodes).is_superset (edges)

The class in the EIFFELBASE library which represents the notion of sets (classSUBSET) un-fortunately contains fewside-effect freeoperations. This undesirable property makes manyEIFFELBASE classes difficult, if not impossible, to specify without mathematical models.

• Specification of Composite Operations: Feasibility to easily specifycomposite operationsusingshared assertions

Model assertionsusing class libraries like the MML library usually are quite verbose due to thefeature naming recommendationsof the EIFFEL style guidelines. Moreover, complex operationsmay also need manycase differentiations. Luckily, common subexpressionsin model contractscan be factored out and help to keepmodel contractsas short as possible. Boolean expressionsthat are used at several places in the specification are simply transformed into a correspondingpredicate. Thanks to theside-effect freenessof the IFL language, the approach ofassertionoutsourcingis perfectly valid.

Page 97: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

94 CHAPTER 7. SPECIFICATIONS OF FUNDAMENTAL DATA STRUCTURES

• Design of Class Hierarchies: Ability to check whether aclass hierarchymodels the conceptsof aproblem domainwithout redundancy

Mathematical models not only provide a good basis for the specification of EIFFEL classes, butalso have other advantages. They can help to validate aclass hierarchywith respect to aminimalnumber of classesand anon-redundant modelingof the concepts in theproblem domain. Thefact that severalmodel featuresof the same type exist in a class interface can be a hint thattoo many classes are modeling the same concept or a similar one. Additionally,inheritancerelationscan be verified by taking theflattened contract formof theancestor class. Themodelcontractsof a class which wants to inherit from this ancestor must comply with theflattenedcontract formof the ancestor (yielding no contradictions in its contracts).

7.6 Usage of Model Specifications

After the last two sections on EIFFELBASE-related problems (section7.4) and a discussion aboutthe benefits of mathematical models (section7.5), we would like to clarify whatclass specificationsusing mathematical models can be used for. Three basic use cases for annotated EIFFEL classes arepresented below:

• Runtime Assertion Checking: Createproxy classesimplementing thespecification classandextending the EIFFELBASE implementation class.

There are two possibilities to use model-specified EIFFEL classes forruntime assertion check-ing. First, regular EIFFEL classes can directly be annotated with mathematical models usingeffected model features. The disadvantage of this option is that we do not consider theflatform of the class, thus potentially missing importantinherited featuresduring the specificationprocess. But on the other hand, we do not have to create any additional classes. Second, wecan generate thecontract formof the class and create adeferred interface class. This classis the basis for our specification process described in section7.2. After having specified thespecification class, we create aproxy classclass which inherits both from the EIFFELBASE im-plementation classand the createdspecification class. The advantage of this approach is a veryflexible assertion checking mechanism. Depending on whetherassertion checkingis desired,simply inherit from thespecification class.

• Class Interface Documentation: Usemodel-annotated classesfor annotationanddocumen-tation purposes.

Mathematical model not only provide a solid specification of EIFFEL classes, but also serve todocument a class in an efficient way. The clarity and expressiveness of mathematical modelssurpassfeature commentseasily. The EIFFEL method uses very few documentation anyway(usually about two or three lines per feature). The advantage ofdocumentation by mathematicalmodelsis that the promise of alwaysup-to-dateand complete documentationby Design byContractTM [Mey97] is kept, which is demonstrated by the following example:

Page 98: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

7.7. CONCLUSION 95

Example: Source Code Documentation forCHAIN Class:

deferred class interfaceCHAIN_EXAMPLE[G]

feature−− Element change

merge_left(other: like Current)−− Merge‘other’ into current structure before cursor−− position. Do not move cursor. Empty‘other’.

requireextendiblecursor>= sequence.lower_boundother/= voidnot is_equal(other)

ensure(old cursor.is_equal(sequence.lower_bound)) implies

sequence.is_equal(old other.sequence.concatenated(sequence))(old cursor> sequence.upper_bound) impliessequence.is_equal(old sequence.concatenated(other.sequence))(old cursor> sequence.lower_boundand cursor<= sequence.upper_bound) implies

sequence.is_equal(old sequence.interval (sequence.lower_bound, cursor− 1).concatenated(other.sequence).concatenated(sequence.interval (cursor, sequence.upper_bound)))

cursor.is_equal(old cursor+ 1)bag.is_equal(old bag.added(other.bag))indexable.cardinality.is_equal(old indexable.cardinality+ other.indexable.cardinality)other.sequence.is_emptyand other.bag.is_emptyand other.indexable.is_empty

end−− classCHAIN_EXAMPLE

• Contract Correctness Proofs: Prove that theregular assertionsof a contract are implied by itsmodel assertions.

Specification classesare the basis forcontract correctness proofs. The following chapter8describes theproof processin detail.

7.7 Conclusion

This chapter has shown that specification of class libraries using mathematical models is possible andcan bring substantial benefits to both developers and clients. In section7.2 we have presented ourapproach to specify EIFFELBASE classes. Section7.3 describes the process of choosing the mostsuitable classes for specification. We have identified the following criteria:

• Usage of the data structure in common applications

• Diversity of concepts represented by the classes

• Sufficient documentation available to developers

Page 99: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

96 CHAPTER 7. SPECIFICATIONS OF FUNDAMENTAL DATA STRUCTURES

The following classes have been selected for specification using mathematical models:

• BAG(see appendixC.1.2)

• LINEAR_SUBSET(see appendixC.1.1)

• DYNAMIC_LIST(see appendixC.1.3)

• STACK(see appendixC.1.4)

• QUEUE (see appendixC.1.5)

In section7.4we have listed the problems encountered during the specification of these classes. Sec-tion 7.4.1covers general problems of the EIFFELBASE class library, whereas class-specific problemsare listed in section7.4.2. The most important benefits of using mathematical models are listed insection7.5:

• Partial State Change Specification: The ability to specifypartial changesof thestate spaceofa software system.

• Definition Assertions: The ability to givepreciseandexpressivedefinitions offeature imple-mentationsin its postcondition.

• Specification of Abstract Axioms: The ability to specifyclass invariants.

• Specification of Composite Operations: The ability to factor outshared assertions.

• Design of Class Hierarchy: The ability to check whether aclass hierarchymodels the conceptsof theproblem domainaccordingly.

In the section7.6we have presented the most importantuses casesof annotated EIFFEL classes:

• Runtime Assertion Checking

• Class Interface Documentation

• Contract Correctness Proofs

Finally, based on the experience of the specification phase and the problems that turned to surface, wewould like to mention a few other issues which we have become aware of.

As listed in section7.4.1and section7.4.2, there are quite a few mismatches in theinheritance hi-erarchyof the EIFFELBASE library. During specification, this kind of problem manifests itself incontradictions of contracts.Regular assertionsor model assertionswhich appear in theflattenedcontractof a feature can contain contradictions, meaning the contract can never be satisfied by anyclient or feature implementation. Common sources of these problems are misunderstandings instatechangesor indexing problemsin array-like data structure (see section7.4.2).

Another characteristic of the EIFFEL language arefeature name synonyms, the ability to associatemore than one name with a feature implementation. Despite its usefulness,synonymous feature namescan bring a lot of trouble when combined withinheritance. Consider a featuref in a classA and a

Page 100: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

7.7. CONCLUSION 97

featureg in a classB. Assuming thatf andg possess contracts with compatible semantics, we canredefine both features in a descendant classC of A andB, using f andg assynonymsof the rede-fined implementation. Different semantics are too easily mixed by usingsynonyms, in particular if thefeatures are poorly specified withregular assertions. In conjunction with language processing toolssuch as thecontract flattener, which are able to extract theflattened contract formof a model class,mathematical models can help to discover this type of problem. A good example for this policy is theclassSTACKwith the synonymsput, extendandforce.

A related problem of the EIFFEL method is the concept offeature hiding, the ability to make theexport statusmore restricted indescendant classes. Many classes in the EIFFELBASE library (e.g.TUPLE) make heavy use offeature hiding. The problem of this concept is that it breakspolymor-phism. The rule that every feature applicable to anancestor base typeis also applicable in thebasetypeof descendant classesis not valid anymore, leading to possiblerun-time errors. The specificationof EIFFEL classes using mathematical models prohibits most such export restrictions. Usually, fea-tures inherited from animplementation classare hidden in order to not pollute the class interface oftheclient class. The classINTEGER_INTERVALdemonstrates this quite well: The inherited featureput is certainly not applicable anymore to the abstraction of amodifiable interval of integers. Thequestion therefore raises whether the selected inheritance relation (classSET) is indeed justified. Thiskind of problems is flagged by thecontract flattener(see chapter9), which indicates a potential CATcall [Mey97] in these cases.

The last remark we would like to make is the growing importance of reusability. The EIF-FELBASE class library provides a classTRAVERSABLEwhich represents the notion of a structurewhose elements can be traversed in a linear order, and each element is visited exactly once. Simi-larly, classTRAVERSABLE_SUBSETrepresents sets that can be traversed according to the descrip-tion given before. However, it is not clear whyTRAVERSABLE_SUBSETdoes not inherit fromTRAVERSABLE, but instead implements all the necessary functionality itself. It has to be said thatTRAVERSABLE_SUBSETis a deferred class, so descendant classes can provide an implementationvia inheritance. Although this solves thecode redundancy problem, the reusability of specifications(and its associated proof obligations) is not guaranteed. It seems that class libraries should also bedesigned with reusability of specification in mind. The interface/implementation separation principle(section6.2.2) which has been applied to the MML library fully supports the reuse ofcontractsandproof obligations.

Page 101: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

98 CHAPTER 7. SPECIFICATIONS OF FUNDAMENTAL DATA STRUCTURES

Page 102: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Chapter 8

Proving Contract Correctness

In this chapter we are investigating how to provecontract correctnessof regular assertionsas anapplication of mathematical models.

8.1 Overview

This chapter consists of three sections. Section8.2 introduces a process calledcontract flatteningwhich is used to extract a class interface consisting ofmodel contractsonly. This concept will be usedin section8.3 where we describe how to obtainproof obligationsfor correctness proofs ofregularassertions. In section8.4we are discussing when a specification can be considered complete.

8.2 The Contract Flattening Algorithm

To be able to formally introduce proof obligations forregular assertionsin the next section, we needto introduce the concept ofcontract flattening. Contract flatteningis a process which eliminatesreg-ular assertionsand transforms them into equivalentmodel assertions. The final state of thecontractflatteningprocess is a class interface containingmodel assertionsonly. The algorithm forcontractflatteningof a classC consists of the following steps:

Contract Flattening Algorithm :

1. Create thecontract formof C.

2. Replace every occurrence of afunction call expression Einvolving a non-model feature fbythecontractof f.

3. Repeat step (2) until no such expressionsE exist anymore in thecontract formof C.

We provide now a detailed description of each of the steps of thecontract flatteningalgorithm.

Step (1) creates thecontract formof the class C. Thecontract formis aflat formof a class withno associated implementation. It is important to realize thatcontract flatteningis only defined on theset ofpreconditions, postconditionsandinvariantsof a class.

99

Page 103: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

100 CHAPTER 8. PROVING CONTRACT CORRECTNESS

In order to work properly, we have to take a flat view of a class interface. Thecontract formis theneasily created by replacing all feature implementations by the ’deferred’ keyword and make classCitself deferred.

Step (2) is a little bit more complicated. We first have to give a definition ofnon-model features.These features are exactly the functions of theflat form of a class which have not been designed torepresentmathematical modelsaccording to the definitions of section3.2and section5.2.1. We do nothave to consider attributes (they cannot have contracts in the current EIFFEL standard) and procedures(since they do not occur in expressions). Let us now consider a contractc with an assertion containinga function call expressione on an arbitrary targett havingf as feature name referring to a non-modelfeature with the (possibly trivial) set ofpreconditions Pandpostconditions Q. We can now distinguishthe following cases for every assertionA in thepostconditions Qof f :

• A is adefinition assertion: The call expressione is substituted by theactual feature argumentof A (see section5.3.2).

• A is not adefinition assertion: In this case, the assertionA is ’and-ed’ with thec.

For thepreconditions P, the situation is similar: Since there are nodefinition assertionsin precondi-tions, all assertionsA are ’and-ed’ with the existing contractc as well. Note that since the contracts ofan EIFFEL class normally are not written in the IFL language, we also have to account fordefinitionassertionswith thereference equality operator’=’.

Step (3) starts the recursive part of thecontract flatteningalgorithm. The replacing ofcall expres-sionsis repeated until there exists no contract anymore such that step (2) can be applied. The finalresult of this process is theflattened contract formcontainingmodel contractsonly. The set ofregu-lar assertionsthat have been flatted in conjunction with the generated assertions during thecontractflatteningprocess is calledflattened assertions.

The flattened contract formof an EIFFEL class will be used in the next section presenting theconstruction ofproof obligationsfor contract correctness proofs.

8.3 Proof Obligations for Contracts

An important question for EIFFEL classes and the correctness of its contracts is the following: Dothe existingregular assertionscomply with a class specification using mathematical models? In thischapter we would like to investigate this problem.

The necessary and sufficient condition forcontract correctnessis that for everyprecondition,postconditionand invariant the set ofmodel assertionsis at least as strong as the set ofregularassertions. In other words, the set ofmodel assertionsshould imply the set ofregular assertions. Weformalize this in the following definition for a contract correctness proof obligation:

Page 104: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

8.4. SPECIFICATION COMPLETENESS 101

• Contract Correctness Proof Obligation:

Theproof obligationfor a contractc with regular assertions Randmodel assertions Mis theimplicationA ⇒ C with:

• The antecedentA being the conjunction of all assertions inM.

• The consequentC being theflattened assertions Fobtained fromRby contract flattening.

Two special cases which perhaps are not so obvious have to be considered as well: The case of anempty set ofmodel assertionsand similarly, an empty set ofregular assertions.

An empty set ofmodel assertionsis equivalent to a model assertion ’True’. From the definitionof logical implication, it follows that theproof obligationis reduced to theflattened assertionsin c.Theproof obligationstherefore consists of showing satisfiability ofF.

The other case is an empty set ofregular assertions. Similar to the case above, it follows that theproof obligationis discharged.

8.4 Specification Completeness

Apart from thecontract correctness proofs, we have to discuss what conditions have to be satisfied bya specification in order to becomplete. A definition ofspecification completenessfor model contractsis quite easy to give:

• Definition: Model Class Specification Completeness

A model class cis completelyspecified if and only if everypostconditionin theflat formof ccontains an assertion referencing eachmodel featureof c at least once.

Obviously, the definition above does not guaranteespecification completenessin the sense that everydesired property can be deduced from the class specification. However for our purposes, this definitionis sufficient. Additionally, by using this definition,specification completenesscan be easily verifiedby language processing tools like thecontract flattenerintroduced in chapter9.

The inverse concept of thespecification completenessintroduced above is thespecification com-pletenessfor regular contracts. In this case, we cannot give such a simple approximative solutionas for theModel Class Specification Completeness. Since we used an approximative definition inthe discussions above, we have to find another solution. Fortunately, theproof obligationsfor con-tract correctnesscan take us further: We simply inverse the implication and receive the followingdefinition:

• Definition: Eiffel Class Specification Completeness

An EIFFEL classc is completelyspecified if and only if for every contractC theregular asser-tions imply themodel assertionsof C.

Note that due to the similarity to the definition ofContract Correctness Proof Obligations, thediscussions of section8.3also apply to theEiffel Class Specification Completenessdefinition.

Page 105: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

102 CHAPTER 8. PROVING CONTRACT CORRECTNESS

Page 106: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Chapter 9

The Contract Flattener

In this chapter we present a language processing tool that helps in automating the process of generatingtheflattened contract formwith associatedproof obligationsfor the verification ofregular assertions.

9.1 Overview

The first section of this chapter, section9.2, gives an overview of the functionality offered by thecon-tract flattenerapplication. In section9.3we present the design ideas behind this language processingtool and describe the architecture of the application. Finally, section9.4 provides a short manual onhow to use thecontract flattenerto generate theflattened contract formsof EIFFEL classes with itsassociatedproof obligations.

9.2 Functionality of the Contract Flattener

This section of chapter9 presents the functionality provided by thecontract flattenerapplication. Thisapplication provides the following functionality:

• IFL Language Verification :

Model classescan be checked for correct and completemodel contracts.

• Language Correctness:Thecontract flattenerapplication is a language processing tool which verifiesmodel con-tractswith respect to the IFL language specification. It extractsmodel features(see sec-tion 3.2) and determines the associatedmodel assertions. All model assertionsare thensubject to the following verification passes:

• Model Class Validity Checks: Verify that amodel classis model-valid(see section5.4.1, and in particular validity errorIFLVMC )

• Model Feature Validity Checks: Verify that amodel classis feature-valid(see sec-tion 5.4.2and section3.2)

• Model Expression Validity Checks: Verify that amodel classis expression-valid(see section5.4.3and section5.3for further reference)

103

Page 107: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

104 CHAPTER 9. THE CONTRACT FLATTENER

If a model classdoes not pass one of the checks above, all further processing of thisclass is aborted, and the class is not considered forcontract flatteningor proof obligationgeneration. An appropriate error message is displayed in the console window.

• Specification Completeness:Model classescan be checked for completeness of specification inmodel contracts.

• Model Specification Validity Checks: Verify that a model classhas a completemodel specification(see section5.4.4)

If a model classdoes not pass the validity check described above, an appropriate warningmessage is displayed in the console. Model specification validity errors are not severeerrors which make further processing impossible. Hence themodel classis considered forcontract flatteningor proof obligation generation.

• Generation of Flattened Contract Form:

Model classescan be transformed into theflattened contract form. This form of an EIFFEL classis not only used for the generation ofproof obligations, but also serves its purpose as a pure,mathematical specification of an EIFFEL class. See section8.2for a description of theflattenedcontract formand how it is generated.

• Generation of Proof Obligations:

Based on theflattened contract form, the IFL contract flattener is also able to generate theassociatedproof obligations, as described in section8.3.

This is a short overview of the facilities offered by thecontract flattenerapplication. The usage ofthis tool is described in section9.4. The next section presents the design ideas behind thecontractflattener.

9.3 Design of the Contract Flattener

Thecontract flattener applicationhas been designed with a few key principles in mind. Similar to thepresentation of the design of the MML library (section6.2), we would like to present the design ofthe application in categories. The following design ideas have influenced the implementation of thisapplication:

• Reusing the Gobo Eiffel Tools:

Our first key design principle is to reuse the existing facilities of the GOBO EIFFEL TOOLS

[Bezb]. No changes should be necessary to the source code of the GOBO libraries, since it isstill under development. It turned out that the current release of the GOBO EIFFEL TOOLS,version 3.3, is not sufficient for our purposes. To compute theflattened contract formof anEIFFEL class, we have to create itsflat form. The GOBO EIFFEL TOOLS provide a partialimplementation toflatten featuresinto the interface of a class, but do not support theflatteningof contracts. Unfortunately, even recent snapshots of the repository, taken at the time of writing,do not provide enough functionality. Although the missing functionality could be implementedby thecontract flattener applicationitself, it would require major changes in the GOBO libraryclasses, which is certainly not a good idea at this stage of the development process of the GOBO

EIFFEL TOOLS. We have therefore decided to only implement parts of the application. The

Page 108: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

9.3. DESIGN OF THE CONTRACT FLATTENER 105

pure feature analysisand the some parts of thecontract flattening algorithmin particular haveto be postponed until the desired functionality is available and the development has becomemore stable. The application has been developed using ISE EIFFELSTUDIO 5.3.

• Extending the Gobo Eiffel Tools:

As already mentioned, one of the primary goals has been to not alter any GOBO EIFFEL TOOLS

distribution. However, this approach requires a series of extensions that implement the desiredextra functionality. Therefore the followingextension classeshave been introduced:

• IFL_CLASS: Extension class ofET_CLASSproviding the storage formodel featuresanddifferentcompilation status flags, indicating which steps have already been executed andwhether they have successfully terminated.

• IFL_CONTRACT: Common ancestor class for the contract classesIFL_PRECONDITIONS,IFL_POSTCONDITIONSandIFL_INVARIANTSwhich are extensions to the correspond-ing ET_XXXassertion classes. The contract class provides storage formodel assertionsandproof obligations. Additionally, it keeps track of which models are involved in thecorresponding contract.

• IFL_UNIVERSE: Extension class ofET_LACE_UNIVERSEwhich extends the compila-tion steps (4) and (3) (see categoryAbstract Syntax Tree Visitors) of the EIFFEL parserwith theModel Collection Steps, Contract Flattening Stepsand theCode GenerationStep. The universe classIFL_UNIVERSEis thedriver classof the IFL parser.

• IFL_FACTORY: Extension class ofET_AST_FACTORYwhich provides support for IFLclasses, IFL contractsand IFLvalidity error objects.

• IFL_ERROR_HANDLER: Extension class ofET_ERROR_HANDLERwhich providessupport for the IFL specificvalidity errors(see section5.4).

• IFL_VALIDITY_ERROR: Extension class ofET_VALIDITY_ERROR(see section5.4).

• IFL_IMPLEMENTATION_CHECKER: Extension class which provides a new imple-mentation ofET_FEATURE_CHECKERin classIFL_FEATURE_CHECKER.This classis described in the stepModel Assertion Collection.

• IFL_ANCESTOR_BUILDER: Extension class ofET_ANCESTOR_BUILDERwhich usesa somehow more liberal policy to handle errors of language constructs which are not com-patible with the upcoming EIFFEL standard [Mey]. The internal validity error IFLVAG(a class cannot have twoidentical ancestor classeswith different generic parameters, seesection6.6) is reported as a warning only.

• IFL_FEATURE_FLATTENER: Extension class ofET_FEATURE_FLATTENERwhichimplements thecontract flattening processduring the generation of theflat formof a class.

Page 109: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

106 CHAPTER 9. THE CONTRACT FLATTENER

Figure 9.1: The Contract Class Hierarchy

• Abstract Syntax Tree Visitors:

The entirecontract flattener applicationis designed as a specialized EIFFEL compiler whichdoes not produce low-level source code or even object code, but generates differentflat formsof a class, in particular theflattened contract formand a set ofproof obligations. The applicationperforms several passes over theabstract syntax tree(AST) built from the GOBO EIFFEL Parser.These passes are performed by specialvisitor classesdesigned according to the ’Visitor’ designpattern [GHJV95]. There are six compilation passes which are equivalent to ISE’s compilationsteps of their Melting Ice TechnologyTM [Eif], calleddegrees. The actual functionality of thecontract flatteneris implemented in degrees 4 and 3. Degree 4 determines themodel featuresof a class and degree 3 verifiesmodel assertionsand generates theflattened contract formandtheproof obligations.

• Model Collection Steps:

The following steps describe howmodel informationis extracted from an EIFFEL class. If aclass has not been processed in a predecessor compilation step, it will not be considered furtherby the successor compilation step. The following three steps are executed:

• Model Feature Collection:This compilation step determines themodel featuresof an EIFFEL class. Note that theclasses are already available in theirflat form (the features have been flattened, but thecontracts are not yet processed). Avisitor objectis used to traverse the AST, searchingfor features that are directly exported toMML_SPECIFICATION. Thesemodel featuresare marked on a class basis and stored in a set for further processing. The correspondingfunctionality is implemented by classIFL_FEATURE_COLLECTOR.

• Model Assertion Collection:After the model featuresof a class have been identified, anothervisitor objecttraversedthe contracts of theflattened featuresand searches for occurrences of calls tomodel fea-tures. Similar to theModel Feature Collectionstep, the resultingmodel assertionsarestored in their corresponding contracts and marked with a tag, indicating that this as-sertion is subject tocontract flatteningand the computation ofproof obligations. Thiscompilation step is implemented in the extension classesIFL_FEATURE_CHECKERandIFL_IMPLEMENTATION_CHECKER.

• Model Verification Step:

The last compilation step of this category is theverification step. It is implemented byclassIFL_LANGUAGE_VERIFIER. The rule-based implementation follows closely thestructure of section5.4, where we have listed allvalidity errorsof the IFL language. As

Page 110: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

9.3. DESIGN OF THE CONTRACT FLATTENER 107

already mentioned at the beginning of this chapter, thepure feature analysisis not yetimplemented. Classes which contain invalidmodel featuresor invalid model assertionsare not considered for theContract Flattening Steps.

Figure 9.2: The Model Checker Class Hierarchy

• Contract Flattening Steps:

The second series of compilation steps does the actual computation on the AST. The followingtwo steps are performed during degree 3:

• Computation of the Flattened Contract Form:

All classes in the universe which have been verified asmodel-validare candidates for theflattened contract formcomputation. The algorithm is an implementation of theContractFlattening Algorithm described in section8.2and is executed as avisitor objectof classIFL_ASSERTION_FLATTENER.

• Computation of Proof Obligations:

Similar to the computation of the flattened contract form, this compilation step is onlyexecuted if the class for which proof obligations should be generated ismodel-valid. Thealgorithm is an implementation based on the definition ofContract Correctness ProofObligation given in section8.3. It is combined with avisitor objectinstantiated by classIFL_IMPLICATION_BUILDERwhich implements alinear traversalover all contracts ofthe class being processed.

Page 111: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

108 CHAPTER 9. THE CONTRACT FLATTENER

Figure 9.3: The Visitor Class Hierarchy

• Code Generation Step:

The last compilation step of thecontract flattener applicationis thecode generationstep, theoutput of the computed information to anoutput directory(see section9.4.2 for a referenceon command-line arguments). For each class which has been successfully processed in oneof the Contract Flattening Steps, a separate output file is generated. The files containingtheflattened contract formhave the extension*.int, files for proof obligationshave extension*.pro. The output of both compilation steps is pure EIFFEL code, making it easy to further usethe source files (see section7.6).

Figure 9.4: The Model Printer Class Hierarchy

Page 112: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

9.4. USAGE OF THE CONTRACT FLATTENER 109

9.4 Usage of the Contract Flattener

The contract flattener applicationis a command-line oriented tool to process universes of EIFFEL

classes described by ACEfiles. The ACEfileshave to follow the syntactical conventions of the ISEEIFFEL implementation. In section9.4.1, we describe how to compile the application from sourcecode. We explain the different command-line switches which are used to control the application.Section9.4.2shows thesynopsisof the application’s command-line interface.

9.4.1 Compiling the Application

Thecontract flattener applicationuses advanced facilities of the GOBO EIFFEL TOOLS [Bezb]. Thecurrent release of these tools at the time of writing is version 3.3. However, for some algorithmslike feature flattening, a more recentdeveloper versionis required. Since the GOBO EIFFEL TOOLS

are experimental code which has not yet been released, taking a developer version is inevitable inthis case. To summarize, thecontract flattener applicationneeds the following components for itscompilation:

• ISE EIFFELSTUDIO 5.3

• ISE EIFFELBASE Class Library

• GOBO EIFFEL TOOLS Developer Version

The application depends on the EIFFELBASE class library shipped with EIFFELSTUDIO 5.3. A recentsnapshot of the GOBO EIFFEL TOOLScan be retrieved from the repository on SourceForge [Bezb]. Tobe able to compile thecontract flattener application, open EIFFELSTUDIO and create a new projectfrom one of the ACEfiles in the root of the IFL code base. These files use relative path namesonly. In order to resolve the cluster paths in the IFL code base correctly, the developer has to set theenvironment variable ’$IFL’ to the path of the code base.

The ACEfiles itself are completelyplatform-independentand can be used on all platforms sup-ported by ISE EIFFELSTUDIO.

9.4.2 Command Line Arguments

The following command-line switches are supported in the current version:

Synopsis:

IFLC [-?/-HELP]IFLC [-V/-VERBOSE] [-I/-INTERFACES] [-P/-PROOFS]ace_file out_directory

ace_file The ACE file describing the universe to processout_directory The path of the directory where the output should be generated

?/HELP Display help information on the command lineV/VERBOSE Display additional information about the compilation processI/INTERFACES Generate class interfaces from classes annotated with modelsP/PROOFS Generate proof obligations for classes annotated with models

Page 113: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

110 CHAPTER 9. THE CONTRACT FLATTENER

9.5 Further Work

The contract flattenerapplication in its current version does not yet implement all of the desiredfunctionality. The two main improvements which have to be done in future versions of this tools arepure feature analysisand thecontract flattening algorithm.

Determining pure features in an EIFFEL universe requires a global analysis of the EIFFEL classesin the universe. The problem withfeature purityis that it can only be determined from a concreteimplementation. But the EIFFEL language offers the concept ofdeferred features, operations whoseimplementation is not available, but delegated to descendant classes, which have the obligation to pro-vide a corresponding implementation. Unfortunately, this concept turnsfeature purityinto a relativenotion, which can only be computed relative to a particular universe of EIFFEL classes. The compu-tation ofpure featuresis therefore notcontinuous(the addition of a class to the universe can result inmajor changes in the class hierarchy) and cannot be executed incrementally. We have decided to deferthe model validity error checksinvolving pure featuresuntil the EIFFEL language provides supportfor feature purityin the form of the ’pure’ keyword of the upcoming EIFFEL standard [Mey].

Another shortcoming of the current version of the contract flattener application is the limitedsupport forcontract flattening. At the moment, the developer versions of the GOBO EIFFEL TOOLS

[Bezb] do not provide an implementation to create theflat formof features which include its contracts.Moreover, facilities to evaluate a feature name occurring in an assertion in the context of a certain typeare missing. Our implementation of the contract flattener therefore focuses on the verification of IFLbasedmodel contracts. The computation of theflattened contract formhas been postponed until themissing facilities are available.

Page 114: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Chapter 10

Summary of this Document

This chapter provides a summary of the work presented in this master thesis report.In chapter2 we have compared some of the most representative software development processes

of the different approaches to formal software construction. The only representative for a fully math-ematical approach which involves mathematical proofs of entire systems is the B Method [Abr96]. Aradically different approach which tries to annotate existing code written in JAVA is the JML spec-ification language [LPC+, LBR], supporting textual annotations of class interfaces in the form ofJAVADOC comments. Although JML specification expressions can be used as input for translationsto theorem prover languages like PVS or ISABELLE [BCC+03], JML remains a purely annotatingdocumentation language. The third approach taken by the EIFFEL Method [Mey92] incorporatessemi-formal specifications in the programming language itself, using ordinary EIFFEL expressions towrite assertions in contracts.

Chapter3 provides an introduction to mathematical models. We have provided a detailed descrip-tion of the mathematical model terminology and describe how the specification of EIFFEL classes isimproved using mathematical models. A process consisting of five steps is given as a guideline forthe specification process. Section3.4discusses what benefits and improvements mathematical modelscan bring with respect to conventional Design by ContractTM [Mey97].

The following chapter4 provides the necessary mathematical background. It starts with a shortoutline of notational conventions and basic constructs of logic calculus (section3.2). The followingsections4.4, 4.5, 4.6 and 4.7 present the notions of sets, tuples, relations, functions, respectively,and other mathematical structures as sequences (section4.8.1) and multisets (section4.8.2). Thelast section4.9of chapter4 gives an introduction to higher-order functions and presents some usefulgeneric functionals which are widely used in the Mathematical Model Library (MML).

Chapter5 introduces the contract specification language IFL. We have described the design pro-cess of the language in section5.2and created the necessary notation based on chapter3. Section5.3is dedicated to IFL expressions, the basic blocks of contract specification. We have given an overviewof the language validity rules and list its validity errors in section5.4. The last section5.5 of thischapter provides a complete specification of the IFL language grammar.

Chapter6 is dedicated to the Mathematical Model Library (MML). We have shown the principaldesign ideas of the MML library in section6.2: The concept of facets (section6.2.1), the principleof interface/implementation hiding (section6.2.2), default implementations (section6.2.3), the fea-ture declaration/feature implementation principle (section6.2.4), specification versus implementation(section6.2.5), type safety versus generality (section6.2.6) and the relationship between object equal-ity and mathematical equality (section6.2.7). The following section6.3 presents the classes of the

111

Page 115: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

112 CHAPTER 10. SUMMARY OF THIS DOCUMENT

MML library in detail. In section6.4 we describe how to apply the facilities provided by the MMLlibrary to model contracts. We have further noted some limitations of the current MML version insection6.5 and have discussed the various problems encountered during the implementation phase(section6.6). The last section of this chapter, section6.7, provides an outlook of further work that canbe done in this area.

Chapter7 delivers the proof of concept of the acquired insights and gives model specificationsof the most fundamental data structures of the EIFFELBASE library. We have presented the processused during specification (section7.2) and have shown the resulting model-annotated EIFFEL classes(section7.3). In section7.6 we have discussed how model specifications can be used for run-timeassertion checking. Section7.4 presents the problems encountered during the specification of thedata structures, followed by a discussion of the potential benefits gained by model-annotated EIFFEL

classes of class libraries in section7.5.The next chapter8 is a practical application of the concepts presented so far and presents the

process of proving contract correctness. We first have introduced the concept of contract flatteningin section8.2, a process used to create the flattened contract form of a class. With the help of asimple algorithm for contract flattening listed in section8.2, we have shown our approach for contractcorrectness proofs (section8.3). A further section of this chapter is dedicated to the question whethera specification is complete (section8.4).

Chapter9 presents a language processing tool called contract flattener for the automatic creationof the flattened contract form of EIFFEL classes. In section9.2, we have given an overview of thefunctionality offered by this tool and have described the software architecture and design of the appli-cation (section9.3). Section9.4 is designed as a user’s manual for this tool, and the last section9.5of this chapter discusses further work and improvements to be implemented in future versions of thistool.

Page 116: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Chapter 11

Conclusion

In this thesis report we have shown that mathematical models are an expressive tool for specifica-tion of EIFFEL classes. The use of a sophisticated class library which provides the necessary math-ematical notions as EIFFEL classes makes specifying complicated relationships between objects inobject-oriented software systems possible.

The model specification approach is particularly suitable to the specification of advanced datastructures. Even complex graph problems can be easily specified using ordinary mathematical con-structs of set theory and relation algebra. Classes which have been specified with mathematical modelsprovide a sound basis for contract correctness proofs and documentation. However, it remains opento what extent mathematical models can be used for the specification of complex systems such asgraphical user interface classes or distributed software systems. The number of necessary modelsprobably would increase drastically. But the principle concept that is not directly supported by math-ematical models is the notion of time. Many applications need to make sure that an action is alwaysexecuted once before another one gets triggered. Thanks to theCommand/Query Separation Principle[Mey97] in conjunction withAbstract Data Types(ADT’s), such constraints can be modeled usingstatus queries answering whether a particular operations has successfully finished. The complexity ofsuch systems may prohibit the specification of such constraints.

But even if mathematical models are probably not powerful enough to express more complexsystems, partial specifications help to automatically create source documentation and provide a formaldescription of subproblems in the problem domain. Much of the specification complexity can behidden by well-designed model class libraries, resulting in an efficient specification process for classesrepresenting advanced data structures.

113

Page 117: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

114 CHAPTER 11. CONCLUSION

Page 118: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Appendix A

IFL Grammar

A.1 Syntax and Notation

The syntax of the following grammar description is based on the EBNF formalism. We adopt the fol-lowing notational conventions: Names are written in mixed-case letters and usually denote grammarrules. Keywords and other tokens of the IFL language are written inbold face. Predefined objectsof the EIFFEL language like the entities ’Current’, ’ Result’ or ’ Void’ are written in mixed-case lettersusingitalic face.- - Commentsrelated to grammar rules are noted in the traditional EIFFEL style.

The start symbol of the IFL language grammar is ’Contract’. The following tokens of the IFL lan-guage areterminal symbolsborrowed from the EIFFEL language. In order to be complete, we listthem again:

• Bit: (0 | 1)+ (b |B)

• Character: ”’(a− zA− Z) ”’

• Comment: ’- -’(.)∗ (\n (’ ’ \t\r)∗ ’- -’ (.)∗)∗

• FreeOperator:(& |@ |# | ’ |’) (a− zA− Z)∗

• Identifier: (a− zA− Z) (a− zA− Z0− 9 | ’_’ )∗

• Integer:(0− 9) (0− 9 | ’_’ )∗

• Real: [Integer] ’.’ [Integer] [(e |E) [+|−] Integer]

• String: ”” (a− zA− Z) ””

A.2 The Grammar Rules

1. CONTRACT ::= Precondition | Postcondition | Invariant

2. Agent ::=agent[ AgentTarget ] AgentUnqualified | [( Declarations) ] [ : Type ] Routine

3. AgentArgument ::= Expression |{ Type} | ?

4. AgentArguments ::= AgentArgument | AgentArguments, AgentArgument |- - empty

115

Page 119: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

116 APPENDIX A. IFL GRAMMAR

5. AgentTarget ::= Entity |{ Type} | ( Expression)

6. AgentUnqualified ::= ( Identifier |prefix “ Prefix “ | infix “ Infix “ | [] ) [ ( AgentArguments) ]

7. Array ::= < < Expressions> >

8. Assignment ::= (Result| Identifier ):= Expression

9. Attempt ::= (Result| Identifier )?= Expression

10. Auxiliary ::= Debug | Check |retry

11. Binary ::= Expression Infix Expression

12. BinaryOperator ::=+ | - | * | / | < | > | <= | >= | // | \\ | ^ | and | or | xor | implies

13. Body ::=deferred | ( do | once[ Keys ] |pure ) Compound |external String [aliasString ]

14. Branch ::=inspectExpression [whenWhen ] [elseCompound ]end

15. Call ::= [ CallTarget. ] CallChain

16. CallArguments ::= Expression | CallArguments, Expression| - - empty

17. CallChain ::= CallUnqualified | CallChain. CallUnqualified

18. CallTarget ::=Current | Result| ( Expression)

19. CallUnqualified ::= Identifier [( CallArguments) ]

20. Characters ::= Character.. Character

21. Check ::=checkClausesend

22. Choice ::= Constant | Range |{ Type}

23. Choices ::= Choice | Choices, Choice |- - empty

24. Class ::= Identifier [[ Types] ]

25. Clause ::= [ Identifier: ] Expression

26. Clauses ::= Clause | Clauses [; ] Clause |- - empty

27. Compound ::= Instruction | Compound [; ] Instruction |- - empty

28. Condition ::= Expressionthen Compound

29. Conditional ::=if ( Condition |elseifCondition ) [elseCompound ]end

30. Constant ::= Bit |True | False| [ + | - ] Integer | [+ | - ] Real | Character | [once] String

31. Control ::= Conditional | Branch | Loop

32. Create ::=create { Type} [ . CallUnqualified ]

33. Creation ::=create[ { Type} ] ( Result| Identifier ). CallUnqualified

Page 120: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

A.2. THE GRAMMAR RULES 117

34. Debug ::=debug[ Keys ] Compoundend

35. Declarations ::= Identifiers: Type | Declarations; Identifiers: Type | - - empty

36. Entity ::= Current | Result| Identifier

37. Expression ::= Entity | Void | Call | Operator | Agent | Constant | Array | Tuple | Old | Create

38. Expressions ::= Expression | Expressions, Expression |- - empty

39. Header ::= [ Precondition ] [localeDeclarations ]

40. Identifiers ::= Identifier | Identifiers , Identifier

41. Infix ::= BinaryOperator | FreeOperator

42. Initialization ::= Compound [ Invariant ] [variant Clause ]

43. Instruction ::= Creation | Call | Assignment | Attempt | Control | Compound | Auxiliary

44. Interval ::= [+ | - ] Integer.. [ + | - ] Integer

45. Invariant ::=invariant Clauses

46. Keys ::= String | Keys, String |- - empty

47. Loop ::= from Initializationuntil Expressionloop Compoundend

48. Old ::= old Expression

49. Operator ::=( Expression) | Unary | Binary

50. Postcondition ::=ensure[ then ] Clauses

51. Precondition ::=require [ else] Clauses

52. Prefix ::= UnaryOperator | FreeOperator

53. Range ::= Interval | Characters | Strings

54. Routine ::= Header Body [ Postcondition ] [rescueCompound ]end

55. Strings ::= [once] String .. [ once] String

56. Tuple ::=[ Expressions]

57. Type ::= Class |expandedClass |referenceClass |like ( Current | Identifier )

58. Types ::= Type | Types, Type |- - empty

59. Unary ::= Prefix Expression

60. UnaryOperator ::=not | + | -

61. Void ::= Expression (= | /=) Void

62. When ::= Choicesthen Compound | When Choicesthen Compound

Page 121: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

118 APPENDIX A. IFL GRAMMAR

Page 122: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Appendix B

MML Library Features

B.1 IFL Language Concepts

Feature Operation Expression

is_equal Object Equality Relation n.a.

equals Mathematical Equality Relation a = b

is_compatible Mathematical Compatibility Relation n.a.

untyped Object Type Stripping n.a.

B.2 MML Library Classes

This appendix lists all the facilities provided by the classes in the Mathematical Model Library(MML). The name of the MML feature is listed in the left-most column, together with a descrip-tion of the performed operation. In the right-most column, we state the mathematical expression forthe library feature. If a feature is not listed in the corresponding class section, it may be inherited orlisted in one of the general categories at the end of appendixB.2.

We use the following notational conventions in this appendix:

• Variables of arbitrary types are denoted byx andy.

• Functionshave names starting with lower-case lettersf , g, ...

• Predicatesstart with capital lettersP , Q, ...

• Collectionsreceive names in lower-case lettersc, d, ...

• Operators are denoted by lower-case letterso, ...

• Integer variables receive the namesi, ...

• Functionalsare referenced by their names in lower-case letters likefunct, ...

Some features of the MML class library cannot be directly expressed in mathematical terms andreceive ann.a. to indicate this.

119

Page 123: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

120 APPENDIX B. MML LIBRARY FEATURES

B.2.1 MML_ANY

Feature Operation Expression

is_pair_valued Pair Value Property n.a.

is_set_valued Set Value Property n.a.

is_relation_valued Relation Value Property n.a.

is_function_valued Function Value Property n.a.

is_graph_valued Graph Value Property n.a.

B.2.2 MML_PAIR

Feature Operation Expression

element Pair Element Access n.a.

first First Element n.a.

second Second Element n.a.

is_identity Identity Pair Property n.a.

inversed Inversed Pair p−1

B.2.3 MML_SET

Feature Operation Expression

any_element Non-deterministic Choice n.a.

any_item Constrained Non-deterministic Choice n.a.

identity_relation Identity Relation Conversion n.a.

power_set Powerset Conversion n.a.

random_sequence Random Sequence Conversion n.a.

cartesian_product Cartesian Product Conversion n.a.

cardinality Set Cardinality ‖x‖is_member Set Membership Property x ∈ y

is_empty Empty Set Property n.a.

is_subset Set Subset Property x ⊇ y

is_superset Set Superset Property x ⊆ y

is_proper_superset Set Proper Superset Property x ⊃ y

is_proper_subset Set Proper Subset Property x ⊂ y

is_partition Set Partition Property n.a.

intersected Set Intersection x ∩ y

united Set Union x ∪ y

subtracted Set Subtraction x\ydifference Set Symmetric Difference x⊕ y

extended Set Element Insertion n.a.

pruned Set Element Removal n.a.

Page 124: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

B.2. MML LIBRARY CLASSES 121

B.2.4 MML_POWERSET

Feature Operation Expression

generalized_united Generalized Set Union ∪x

generalized_intersected Generalized Set Intersection ∩x

is_generalized_disjoint Generalized Set Disjointness Property n.a.

is_generalized_partition Generalized Set Partition Property n.a.

B.2.5 MML_RELATION

Feature Operation Expression

is_identity Identity Relation Property n.a.

is_reflexive Reflexive Relation Property n.a.

is_irreflexive Irreflexive Relation Property n.a.

is_symmetric Symmetric Relation Property n.a.

is_asymmetric Asymmetric Relation Property n.a.

is_antisymmetric Antisymmetric Relation Property n.a.

is_transitive Transitive Relation Property n.a.

united Relational Union r ∪ s

intersected Relational Intersection r ∩ s

extended Relational Extension n.a.

domain Relation Domain dom r

range Relation Range ran r

image_element Relational Image Element n.a.

image Relational Image r [s]anti_image_element Relational Anti Image Element n.a.

anti_image Relational Anti Image n.a.

domain_element_restricted Domain Element Restriction n.a.

domain_restricted Domain Restriction r / s

range_element_restricted Range Element Restriction n.a.

range_restricted Range Restriction r . s

domain_element_anti_restricted Domain Element Anti Restriction n.a.

domain_anti_restricted Domain Anti Restriction r E s

range_element_anti_restricted Range Element Anti Restriction n.a.

range_anti_restricted Range Anti Restriction r D s

Page 125: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

122 APPENDIX B. MML LIBRARY FEATURES

B.2.6 MML_FUNCTION

Feature Operation Expression

is_continuous Continuous Function Property n.a.

is_discrete Discrete Function Property n.a.

is_invertible Invertible Function Property n.a.

is_finite Finite Function Property n.a.

is_partial Partial Function Property n.a.

is_total Total Function Property n.a.

is_injective Injective Function Property n.a.

is_surjective Surjective Function Property n.a.

is_bijective Bijective Function Property n.a.

is_defined Argument Defined Property n.a.

intersected Functional Intersection f ∩ g

united Functional Union f ∪ g

evaluated Function Evaluation f(x)inversed Functional Inversion f−1

composed Functional Composition f ◦ g

sequential_closure Sequential Closure f++

transitive_closure Transitive Closure f+

reflexive_transitive_closure Reflexive-Transitive Closure f∗

B.2.7 MML_BAG

Feature Operation Expression

multiplicity Bag Multiplicity mult x y

is_member Bag Membership Property x ∈ y

is_empty Empty Bag Property n.a.

is_subbag Bag Subset Property x ⊇ y

is_superbag Bag Superset Property x ⊆ y

is_proper_superbag Bag Proper Superset Property x ⊃ y

is_proper_subbag Bag Proper Subset Property x ⊂ y

intersected Bag Intersection x ∩ y

united Bag Union x ∪ y

subtracted Bag Subtraction x\ydifference Bag Symmetric Difference x⊕ y

extended Bag Element Insertion n.a.

pruned Bag Element Removal n.a.

added Bag Addition n.a.

removed Bag Removal n.a.

Page 126: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

B.2. MML LIBRARY CLASSES 123

B.2.8 MML_SEQUENCE

Feature Operation Expression

is_member Sequence Membership Property x ∈ s

is_defined Index Definition Property n.a

is_subsequence Sequence Subsequence Property s ⊇ t

is_supersequence Sequence Supersequence Property s ⊆ t

is_proper_subsequence Sequence Proper Subsequence Property s ⊃ t

is_proper_supersequence Sequence Proper Supersequence s ⊂ t

lower_bound Lower Index Bound lower s

upper_bound Upper Index Bound upper s

subtracted Sequence Subtraction n.a.

extended_at Sequence Element Insertion n.a.

pruned Sequence Element Removal n.a.

pruned_at Sequence Element Removal n.a.

replaced Sequence Element Replacement n.a.

interval Sequence Subinterval n.a.

reversed Sequence Reversal s

first First Sequence Element first s

last Last Sequence Element last s

tail Sequence Tail tail s

front Sequence Front front s

appended Sequence Element Appending n.a.

prepended Sequence Element Prepending n.a.

concatenated Sequence Concatenation s ./ t

filtered Sequence Filtering s � t

is_partition Sequence Partition Property s ] t

B.2.9 MML_GRAPH

Feature Operation Expression

edge_extended Graph Edge Insertion n.a.

edge_pruned Graph Edge Removal n.a.

node_extended Graph Node Insertion n.a.

node_pruned Graph Node Removal n.a.

is_weakly_connected Graph Weak Connectivity Property n.a.

is_strongly_connected Graph Strong Connectivity Property n.a.

is_subgraph Graph Subgraph Property x ⊇ y

is_supergraph Graph Supergraph Property x ⊆ y

is_proper_subgraph Graph Proper Subgraph Property x ⊃ y

is_proper_supergraph Graph Proper Supergraph Property x ⊂ y

Page 127: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

124 APPENDIX B. MML LIBRARY FEATURES

B.3 MML Generic Operations

Feature Operation Expression

filtered Collection Filtering f � g

mapped Collection Mapping map f c

applied Collection Processing apply p c

accumulated Collection Accumulation acc o i c

there_exists Existential Quantifier ∃x : P (x)for_all Universal Quantifier ∀x : P (x)curried Function Currying curry f

composed Function Composition f ◦ g

iterated Function Iteration iter f x

negated Logical Negation ¬x

ored Logical Disjunction x ∨ y

xored Logical Exclusive Disjunction n.a.

anded Logical Conjunction x ∧ y

implied Logical Implication x ⇒ y

B.4 MML Conversion Operations

Feature Operation Expression

identity_pair Identity Pair Conversion n.a.

identity_relation Identity Relation Conversion n.a.

power_set Powerset Conversion n.a.

random_sequence Random Sequence Conversion n.a.

cartesian_product Cartesian Product Conversion n.a.

Page 128: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Appendix C

EiffelBase Class Specifications

C.1 EiffelBase Model Structures

This appendix presents the EIFFELBASE class specifications mentioned in chapter7.

C.1.1 LINEAR_SUBSETdeferred class interface

SPECIFICATION_LINEAR_SUBSET[G]

feature−− Access

index: INTEGER−− Current index

ensureResult>= sequence.lower_boundResult<= sequence.upper_bound+ 1Result.is_equal(cursor)

feature−− Comparison

is_equal(other: like Current): BOOLEAN−− Is ‘other’ attached to an object considered equal to current object?

ensure thenResultimplies sequence.is_equal(other.sequence)Resultimplies set.is_equal(other.set)

is_subset(other: SPECIFICATION_SUBSET[G]): BOOLEAN−− Is current set a subset of‘other’?

ensure thensequence.is_equal(old sequence) and cursor.is_equal(old cursor)

is_superset(other: SPECIFICATION_SUBSET[G]): BOOLEAN−− Is current set a superset of‘other’?

ensure thensequence.is_equal(old sequence) and cursor.is_equal(old cursor)

feature−− Status report

before: BOOLEAN−− Is cursor at left from first item?

ensureResult.is_equal(not sequence.is_defined(cursor))cursor< sequence.lower_boundis_equal(old Current)

125

Page 129: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

126 APPENDIX C. EIFFELBASE CLASS SPECIFICATIONS

sequence.equals(old sequence)cursor.is_equal(old cursor)set.equals(old set)

islast: BOOLEAN−− Is cursor at last item?

ensureResult.is_equal(cursor.is_equal(sequence.upper_bound))is_equal(old Current)sequence.equals(old sequence)cursor.is_equal(old cursor)set.equals(old set)Resultimplies sequence.is_defined(cursor)

off : BOOLEAN−− Is there no current item?

ensure thenResult.is_equal(not sequence.is_defined(cursor))

valid_index(number: INTEGER): BOOLEAN−− Is ‘number’a valid index?

ensureResult.is_equal(number>= sequence.lower_bound− 1)Result.is_equal(number<= sequence.upper_bound+ 1)is_equal(old Current)number.is_equal(old number)sequence.equals(old sequence)cursor.is_equal(old cursor)set.equals(old set)

feature−− Cursor movement

go_i_th(i: INTEGER)−− Move cursor to‘i’ −th item.

requirevalid_index(i)i >= sequence.lower_bound− 1 and i <= sequence.upper_bound+ 1

ensurecursor.is_equal(i)i.is_equal(old i)sequence.equals(old sequence) and set.equals(old set)i < sequence.lower_boundimplies beforei > sequence.upper_boundimplies aftercursor.is_equal(i)

feature−− Element change

extend(other: G)−− Ensure that set includes‘other’.

ensure thensequence.equals((old sequence).extended_at(other, (old sequence).upper_bound))cursor.is_equal(old cursor)

merge(other: SPECIFICATION_SUBSET[G])−− Add all items of‘other’.

ensure thensequence.interval (sequence.lower_bound, (old sequence).upper_bound).equals(old sequence)cursor.is_equal(old cursor)

put_left(other: G)−− Insert‘other’ before the cursor.

require elseother/= voidnot before

Page 130: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

C.1. EIFFELBASE MODEL STRUCTURES 127

ensure thenindex= old index+ 1

feature−− Removal

prune_all(other: G)−− Remove all occurrences of‘other’.

ensure thenset.equals((old set).pruned(other))

wipe_out−− Remove all items.

ensure thensequence.is_emptyset.is_emptycursor> sequence.upper_boundnot sequence.is_defined(cursor)

feature−− Conversion

linear_representation: SPECIFICATION_LINEAR[G]−− Representation as a linear structure

ensure thenResult.for_all (agentset.is_member(?))Result.for_all (agentsequence.is_member(?))sequence.equals(old sequence)cursor.is_equal(old cursor)set.equals(old set)

feature−− Duplication

duplicate(number: INTEGER): like Current−− New structure containing min (‘number’, ‘count’) items from current structure

ensure thenResult.sequence.for_all (agentsequence.is_member(?))number<= countimplies Result.sequence.count.is_equal(number)number>= countimplies Result.sequence.count.is_equal(count)sequence.equals(old sequence)cursor.is_equal(old cursor)

feature−− Element Change

fill (other: SPECIFICATION_CONTAINER[G])−− Fill with as many items of‘other’ as possible.

ensure thensequence.interval (sequence.lower_bound, (old sequence).upper_bound).equals(old sequence)other.linear_representation.for_all (agentset.is_member(?))cursor.is_equal(old cursor)

feature−− Status Report

is_inserted(other: G): BOOLEAN−− Has‘other’ been inserted by the most recent insertion?

ensure thenResultimplies set.is_member(other)Resultimplies sequence.is_member(other)

invariant

before.is_equal(cursor.is_equal(0))

end−− classSPECIFICATION_LINEAR_SUBSET

Page 131: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

128 APPENDIX C. EIFFELBASE CLASS SPECIFICATIONS

C.1.2 BAGdeferred class interface

SPECIFICATION_BAG[G]

feature {MML_SPECIFICATION, ANY} −− Model

bag: MML_BAG[G]−− The bag model

ensureis_equal(old Current)Result/= void

feature−− Access

has(other: G): BOOLEAN−− Does structure include‘other’?

ensure thenResult.is_equal(bag.is_member(other))bag.is_equal(old bag)

feature−− Measurement

occurrences(other: G): INTEGER−− Number of times‘other’ appears in structure

requireother/= void

ensureResult.is_equal(bag.multiplicity (other))is_equal(old Current)bag.is_equal(old bag)other.is_equal(old other)

feature−− Comparison

is_equal(other: like Current): BOOLEAN−− Is ‘other’ attached to an object considered equal to current object?

ensure thenResult.is_equal(bag.is_equal(other.bag))bag.is_equal(old bag)

feature−− Status report

changeable_comparison_criterion: BOOLEAN−− May ‘object_comparison’be changed?

ensure thenbag.is_equal(old bag)

is_empty: BOOLEAN−− Is there no element?

ensure thenResult.is_equal(bag.is_empty)bag.is_equal(old bag)

object_comparison: BOOLEAN−− Must search operations use‘equal’?

ensure thenbag.is_equal(old bag)

feature−− Element change

extend(other: G)−− Add a new occurrence of‘other’.

ensure thenbag.is_equal(old bag.extended(other))

Page 132: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

C.1. EIFFELBASE MODEL STRUCTURES 129

bag.multiplicity (other).is_equal(old bag.multiplicity (other))

feature−− Removal

prune(other: G)−− Remove one occurrence of‘other’ if any.

ensure thenbag.is_equal(old bag.pruned(other))

prune_all(other: G)−− Remove all occurrences of‘other’.

ensure thenbag.is_equal(old bag.domain_element_anti_restricted(other))

wipe_out−− Remove all items.

ensure thenbag.is_empty

feature−− Element Change

put (other: G)−− Ensure that structure includes‘other’.

ensure thenbag.is_equal(old bag.extended(other))bag.multiplicity (other).is_equal(old bag.multiplicity (other))

feature−− Status Report

extendible: BOOLEAN−− May new items be added?)

ensure thenbag.is_equal(old bag)

is_inserted(other: G): BOOLEAN−− Has‘other’ been inserted by the most recent insertion?

ensure thenbag.is_equal(old bag)

prunable: BOOLEAN−− May items be removed?

ensure thenbag.is_equal(old bag)

feature−− Status Setting

compare_objects−− Ensure that future search operations will use‘equal’

ensure thenbag.is_equal(old bag)

compare_references−− Ensure that future search operations will use‘=’

ensure thenbag.is_equal(old bag)

invariant

linear_representation.for_all (agentbag.is_member(?))linear_representation.is_empty.is_equal(bag.is_empty)

end−− classSPECIFICATION_BAG

Page 133: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

130 APPENDIX C. EIFFELBASE CLASS SPECIFICATIONS

C.1.3 DYNAMIC_LISTdeferred class interface

SPECIFICATION_DYNAMIC_LIST[G]

feature−− Removal

remove−− Remove current item.

require elseprunablewritablesequence.is_defined(cursor)

ensure thensequence.is_equal(old sequence.pruned_at(cursor))sequence.is_emptyimplies cursor.is_equal(sequence.upper_bound+ 1)indexable.cardinality.is_equal(old indexable.cardinality− 1)cursor.is_equal(old cursor)

wipe_out−− Remove all items.

ensure thencursor.is_equal(sequence.lower_bound− 1)

end−− classSPECIFICATION_DYNAMIC_LIST

Page 134: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

C.1. EIFFELBASE MODEL STRUCTURES 131

C.1.4 STACKdeferred class interface

SPECIFICATION_STACK[G]

feature−− Removal

remove−− Remove current item.

ensure thencursor.is_equal(old cursor− 1)

feature−− Conversion

linear_representation: SPECIFICATION_LINEAR[G]−− Representation as a linear structure

ensure thenResult.sequence_model.is_equal(sequence)sequence.is_equal(old sequence)cursor.is_equal(old cursor)bag.is_equal(old bag)

feature−− Element change

append(other: SPECIFICATION_SEQUENCE[G])−− Append a copy of‘other’.

ensure thencursor.is_equal(old cursor+ other.sequence_model.count)

extend(other: G)−− Push‘other’ onto top.

ensure thensequence.is_equal(old sequence.appended(other))cursor.is_equal(old cursor+ 1)

replace(other: G)−− Replace top item by‘other’.

ensure thensequence.is_equal(old sequence.front.appended(other))

invariant

not sequence.is_emptyimplies cursor.is_equal(sequence.upper_bound)

end−− classSPECIFICATION_STACK

Page 135: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

132 APPENDIX C. EIFFELBASE CLASS SPECIFICATIONS

C.1.5 QUEUEdeferred class interface

SPECIFICATION_QUEUE[G]

feature−− Removal

remove−− Remove current item.

ensure thennot sequence.is_emptyimplies cursor.is_equal(old cursor)

feature−− Conversion

linear_representation: SPECIFICATION_LINEAR[G]−− Representation as a linear structure

ensure thenResult.sequence_model.is_equal(sequence)sequence.is_equal(old sequence)cursor.is_equal(old cursor)bag.is_equal(old bag)

feature−− Element change

append(other: SPECIFICATION_SEQUENCE[G])−− Append a copy of‘other’.

ensure thencursor.is_equal(old cursor)

force(other: G)−− Add ‘other’ as newest item.

requireother_not_void: other/= void

ensuresequence.is_equal(old sequence.appended(other))bag.is_equal(old bag.extended(other))other.is_equal(old other)cursor.is_equal(old cursor)

put (other: G)−− Ensure that structure includes‘other’.

ensure thensequence.is_equal(old sequence.appended(other))cursor.is_equal(old cursor)

extend(other: G)−− Add a new occurrence of‘other’.

ensure thensequence.is_equal(old sequence.appended(other))cursor.is_equal(old cursor)

invariant

not sequence.is_emptyimplies cursor.is_equal(sequence.lower_bound)sequence.is_emptyimplies cursor.is_equal(sequence.lower_bound− 1)

end−− classSPECIFICATION_QUEUE

Page 136: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

C.2. EIFFELBASE CLASS HIERARCHY 133

C.2 EiffelBase Class Hierarchy

The class specificationsare only listed in theirshort formto save space. The advantages of math-ematical models and the gained completeness of specification are easily recognizable even from theexamples in this appendix. Since the classes of the underlying data structureclass hierarchycontain alot of duplicated code, we decided not to include the referenced EIFFELBASE library classes into thisdocument.

We advise the interested reader to consult the MML code base, which provides the followingclusters related to model specification:

• specification/hierarchy: The EIFFELBASE class hierarchy specifications

• specification/structures: The EIFFELBASE data structure specifications

Page 137: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

134 APPENDIX C. EIFFELBASE CLASS SPECIFICATIONS

Page 138: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Appendix D

Mathematical Definitions

D.1 Fundamental Logic

Syntax Name Page

x ∧ y Logical Conjunction 22x ∨ y Logical Disjunction 22¬x Logical Negation 22x ⇒ y Logical Implication 22

∀x : X • P (x) Universal Quantifier 23∃x : X • P (x) Existential Quantifier 23

D.2 Sets

Syntax Name Page

{a1, a2, . . . , an} Manifest Set 23x = y Set Equality 23x 6= y Set Inequality 23x ∈ X Set Membership 23x /∈ X Set Non-Membership 23

∅ Empty Set 24P1X Non-Empty Subset 24X ⊆ Y Subset 24X ⊂ Y Proper Subset 24

X ∪ Y Set Union 24X ∩ Y Set Intersection 24X \ Y Set Difference 25

135

Page 139: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

136 APPENDIX D. MATHEMATICAL DEFINITIONS

D.3 Tuples

Syntax Name Page

(a1, a2, . . . , an) Manifest Tuple 25(x, y) Ordered Pair 25first First Element 26second Second Element 26

D.4 Relations

Syntax Name Page

X ↔ Y Binary Relation 27x 7→ y Maplet 27id X Identity Relation 27dom X Domain Projection 27ranX Range Projection 27

X ◦ Y Relational Composition 28X / Y Domain Restriction 28X . Y Range Restriction 28X E Y Domain Anti-Restriction 29X D Y Range Anti-Restriction 29

X -1 Inverse Relation 29X [Y ] Relational Image 30R+ Transitive Closure 30R* Reflexive-Transitive Closure 30

D.5 Functions

Syntax Name Page

f : X 9 Y Partial Function 31f : X → Y Total Function 31f : X � Y Finite Function 31f ∩ g Functional Intersection 32f t g Functional Union 32

Page 140: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

D.8. FUNCTIONALS 137

D.6 Sequences

Syntax Name Page

〈x1, x2, . . . , xn〉 Manifest Sequence 33seq X Finite Sequence 33seq1 X Non-Empty Finite Sequence 33rank X Finite Injective Sequence 33

X ./ Y Sequence Concatenation 34first First Sequence Element 34last Last Sequence Element 34front Sequence Front 34tail Sequence Tail 34

X∼ Reverse Sequence 35X � Y Sequence Filtering 35X G Y Sequence Disjointness 36X ] Y Sequence Partitioning 36

D.7 Multisets

Syntax Name Page

[[x1, x2, . . . , xn]] Manifest Bag 37bag X Finite Multiset 37bag1 X Non-Empty Finite Multiset 37x ∈ X Multiset Membership 38x /∈ X Multiset Non-Membership 38mult Y x Multiset Multiplicity 38

D.8 Functionals

Syntax Name Page

f ◦ g Functional Composition 39curry f Function Currying 39

map Map Functional 40filter Filter Functional 41accumulate Accumulate Functional 41forall Forall Functional 41

Page 141: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Index

abstractcontract,43data type,15, 56machine,9syntax tree,106

abstractionfunction,14, 14, 16, 43, 44, 69, 81invariant,14, 16, 44, 69, 81mathematical abstraction,14, 15, 15, 19, 57,

80accumulate,41, 67ACE file, 68, 109active

data structure,84ADT, 15, 47, 56agent

inline agent,52, 72, 76, 78algebra

relation algebra,9, 55, 57, 58, 113ancestor,80, 81

class,58, 65common ancestor,80

anonymoustype,62

antecedent,101ANY, 49, 62–64, 68, 72, 74, 76, 80argument

actual argument,100ARRAY, 86, 87ARRAYED_LIST, 86ARRAYED_SET,87, 91assertion,10

case differentiation assertion,76checking,94contract assertion,13definition assertion,47, 47, 51, 80, 81, 89,

92, 96, 100flattened assertion,100, 101immutable argument assertion,17, 80

immutable model assertion,17, 17invariant assertion,81model assertion,13, 14, 14–17, 46, 47, 80,

93, 95, 96, 99–101, 103, 105–107pure feature assertion,17, 17, 80, 81regular assertion,13, 13, 14, 20, 80, 95–97,

99–101, 103shared assertion,93, 96

assignmentattempt,74, 75

AST, 106, 107attribute,14

class attribute,16axiom,93, 96

B method,7, 9BAG, 82, 83, 87, 90, 91, 96bag,seemultiset,57, 111

containment,65bijective

function,31BILINEAR, 85, 87binary

operator,48BOOLEAN, 47Boolean

operator,53BOX, 84

calculuspredicate calculus,23

callCAT call, 97feature call,56

cardinality,22, 23, 24Cartesian product,15, 16, 27, 57, 59case

differentiation,49, 93cast

138

Page 142: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

INDEX 139

type cast,75CHAIN, 87, 88, 90CHARACTER,10, 47class

ancestor class,58, 65attribute,16auxiliary class,64, 67base class,71compositor class,62deferred class,59, 61, 84facet class,64, 66, 84, 91generic class,14implementation class,71, 94interface class,71, 94internal class,66invariant,81, 93, 96marker class,64model class,15, 44, 45, 47, 50, 64, 66, 69,

70, 97, 101, 103, 104proxy class,94specification class,94

cleanfeature,43, 46, 46, 48

closurereflexive transitive closure,30, 65sequence closure,36, 40, 65transitive closure,30, 37, 60, 65

codegeneration,9

COLLECTION,85, 87, 88command,17, 86comment

feature comment,81, 94header comment,81

compatibilitymathematical compatibility,58, 67, 72

completespecification,51

COMPLETE_GRAPH,93completeness

graph completeness,66specification completeness,47, 101

composed,62composite operation,96composition

function composition,39, 40, 65, 67relation composition,28, 39, 62, 65

compositorclass,62

concatenationsequence concatenation,34

conjunctionlogical conjunction,22

connectivitygraph connectivity,66strong connectivity,19

consequent,101CONTAINER,83, 84containment

bag containment,65graph containment,66sequence containment,66set containment,65

contract,19abstract contract,43correctness,99flattened contract,96flattener,103, 104flattening,19, 99, 101, 110form, 99, 100model contract,13, 14, 15, 17, 43–46, 51, 72,

90, 93, 94, 99–101, 103, 104, 110regular contract,14, 101specification,17

correctnesscontract correctness,99, 100

creationprocedure,48

curry,39currying,39, 40

function currying,67CURSOR,88cursor

internal cursor,15, 16, 88CURSOR_STRUCTURE,88

decompositionsequence decomposition,34, 66system decomposition,56, 57

deepequality,49

deferredfeature,46

definition

Page 143: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

140 INDEX

by comprehension,26by extension,26

degree,106descendant

direct descendant,80, 81Design by ContractTM , 7, 10, 13, 94, 111difference

set difference,25differentiation

case differentiation,49, 93DIRECTED_GRAPH,19discrete

function,55disjointness

sequence disjointness,36disjunction

logical disjunction,22dispenser,82do_all,83documentation,94domain,21, 27, 27, 57, 73

restriction,28, 65DYNAMIC_CHAIN, 84, 88, 92DYNAMIC_LIST, 82, 83, 88, 96

EiffelBase,19, 41, 47, 49, 53, 68, 79–81, 83–88,90–97, 109, 112, 125, 133

EiffelStudio,68, 72, 83, 105, 109equality,23

deep equality,49, 75mathematical equality,58, 63–65, 72model equality,18object equality,16–18, 20, 49, 63, 65, 72, 75,

76reference equality,48, 49, 53, 56, 63, 71, 75,

77set equality,23shallow equality,49, 75

equivalencerelation,70

errorvalidity error,49

evaluationpartial evaluation,39

exception,14exists,42expanded

inheritance,58export

status,97expression

Boolean expression,10model expression,51old expression,52, 75pure expression,14, 16, 43, 46, 46, 47, 52regular expression,54, 76ternary Boolean expression,76

extendibility,7external

feature,44, 48, 50, 51

facet,56, 56, 57, 60, 65, 66, 80class,64, 66convertible facet,57, 65extendible facet,57, 65filterable facet,57, 65mappable facet,57, 65processable facet,58, 65, 66quantifiable facet,58, 65, 66reduceable facet,58typeable facet,58, 65, 66

featurecall, 56clean feature,46, 46, 48comment,81, 94deferred feature,46, 76, 110external feature,44, 48, 50, 51hiding,97impure feature,67model feature,14, 14–18, 20, 43–45, 47, 49–

51, 64, 68–70, 80, 81, 87, 93, 94, 101,103, 105–107

once feature,44, 48, 50, 51operator feature,72pure feature,17, 43, 44, 45, 45, 46, 48, 50,

51, 67, 87, 110purity, 44, 45, 48wrapper feature,72, 78

fieldmodel field,10

filter, 41filtering

sequence filtering,35finite

Page 144: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

INDEX 141

function,31relation,26sequence,33, 33

firstpair first,25, 28sequence first,35

flatteningcontract flattening,19, 99, 101, 104, 110feature flattening,109

for_all, 83forall, 41form

contract form,94, 99, 100flat form, 16, 51, 80, 94, 99–101, 104–106,

110flattened contract form,94, 97, 100, 103, 104,

106–108, 110, 112short form,133

frontsequence front,35

FUNCTION,85function,31, 57, 78, 111

abstraction function,14, 14, 16, 43, 44, 69,81

acyclic function,36bijective function,31composition,39, 40, 65, 67continuous function,71, 78currying,39, 40, 67discrete function,55, 58, 71finite function,31, 58, 71, 78higher-order function,38, 40identity function,40, 67injective function,31intersection,32, 65inversion,33, 65iteration,40, 67mapping function,57, 66, 85once function,48partial function,31pure function,17surjective function,31total function,31union,32, 38, 65

functionalaccumulate,41, 67exists,42

filter, 41forall, 41iterate,40map,40reduce,41

garbage collection,10generation

code generation,9genericity,10GRAPH,15graph,57, 58, 60

containment,66directed graph,66, 69strongly-connected graph,19

H.B. Curry,39hiding

feature hiding,97hierarchy

inheritance hierarchy,96

identityfunction,40, 67object identity,56relation,27

IFL_ANCESTOR_BUILDER,105IFL_ASSERTION_FLATTENER,107IFL_CLASS,105IFL_CONTRACT,105IFL_ERROR_HANDLER,105IFL_FACTORY,105IFL_FEATURE_CHECKER,105, 106IFL_FEATURE_COLLECTOR,106IFL_FEATURE_FLATTENER,105IFL_IMPLEMENTATION_CHECKER,105, 106IFL_IMPLICATION_BUILDER, 107IFL_INVARIANTS, 105IFL_LANGUAGE_VERIFIER,106IFL_POSTCONDITIONS,105IFL_PRECONDITIONS,105IFL_UNIVERSE,105IFL_VALIDITY_ERROR, 105image

relation image,30immutability,47immutable

object,45, 45, 46, 56, 71

Page 145: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

142 INDEX

implementationmodel implementation,16, 61, 67

implication,101logical implication,22, 101

impurefeature,67

INDEXABLE, 88, 91information hiding,59inheritance

expanded inheritance,58implementation inheritance,10multiple inheritance,10relation,56

injectivefunction,31sequence,33

INTEGER,47, 75INTEGER_INTERVAL,84, 85, 88, 89, 91, 97INTEGER_REF,75interface

model interface,59–61intersection

function intersection,32, 65generalized intersection,24, 58, 65powerset intersection,58set intersection,24, 56, 65

invariant,10, 81, 99, 100abstraction invariant,14, 16, 44, 69, 81class invariant,14, 15, 81, 93, 96gluing invariant,15, 15, 18–20, 69, 81model invariant,19, 81regular invariant,81

inverserelation,29

inversionfunction inversion,65relation inversion,65

iterate,40iteration,67

function iteration,40, 67relation iteration,30

iteratorexternal iterator,84internal iterator,84

Java,7, 10JavaDoc,10

JIVE, 10

Larch,10last

sequence last,35LINEAR, 84, 85, 87, 89LINEAR_SUBSET,82, 83, 89–91, 96linked

list, 14LINKED_SET,91LINKED_LIST, 14–16, 18, 19LIST, 90list, 55

linked list,14–16, 18sequential list,15

machineabstract machine,9

map,40maplet,27, 56mapping,seefunction

finite mapping,31function,57

Melting Ice TechnologyTM , 106membership

multiset membership,38set membership,23

messagepassing,56

mismatchimpedance mismatch,55

MML_ANY, 63, 65, 65, 67, 72MML_BAG, 58, 65MML_COMPOSITION,74MML_CONVERTIBLE, 66MML_DEFAULT_FUNCTION, 71MML_EXTENDIBLE, 66MML_FILTERABLE, 66MML_FUNCTION, 58, 65, 71, 73, 78MML_FUNCTIONALS, 67, 73MML_GRAPH, 58, 66, 78MML_MAPPABLE, 66MML_PAIR, 58, 65, 69, 73MML_POWERSET,58, 65, 74MML_PROCESSABLE,67MML_QUANTIFIABLE, 67, 74MML_REDUCEABLE, 67

Page 146: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

INDEX 143

MML_REDUCEABLE_SET,60MML_RELATION, 58, 62, 65, 66, 69, 73, 74MML_SEQUENCE,58, 66, 73MML_SET, 58, 63, 65, 65, 69, 73, 74MML_SPECIFICATION,64, 68, 69, 106MML_TYPEABLE, 67MML_ANY, 44MML_FUNCTION, 55MML_PAIR, 55MML_SET, 55MML_SPECIFICATION,45, 50model

assertion,14, 14–17, 46, 47, 80, 93, 95, 99–101, 103, 105–107

class,15, 44, 45, 47, 50, 66, 69, 70, 97, 101,103, 104

contract,14, 15, 17, 43–46, 51, 72, 93, 94,99–101, 104, 110

equality,18expression,51feature,14, 14–18, 20, 43–45, 47, 49–51,

64, 68–70, 80, 81, 87, 93, 94, 101, 103,105–107

field, 10implementation,16, 61, 67interface,59–61invariant,19, 81object,69selection,15

multiplicity, 38multiset,37, 57, 58, 65, 78, 82, 111

membership,38multiplicity, 38

negationlogical negation,22

network,57, 60, 78NONE,49, 72NUMERIC, 60

objectequality,49identity,56immutable object,45, 45, 46, 71model object,69

object-orientedprogramming,56

obligationproof obligation,19

oldexpression,52

oncefeature,44, 48, 50, 51function,48

operationcomposite operation,93, 96

operator’and then’,51’or else’,51binary operator,48, 60Boolean operator,49, 51, 53, 67

non-strict,51infix operator,78non-strict operator,49prefix operator,78reference operator,51unary operator,48

ordertotal order,84

overloading,71model overloading,10operator overloading,10

pair,56, 65, 78first, 25, 26, 28ordered pair,25, 25, 26, 28, 58second,25, 26, 28

parameteractual generic parameter,71formal generic parameter,62, 74

parser,106partial

evaluation,39partition

equivalence partition,15, 16sequence partition,66

partitioningsequence partitioning,36

polymorphism,97postcondition,10, 16–19, 45, 47, 49, 51, 52, 69,

75, 80, 81, 89, 91, 92, 96, 99–101powerset,22, 27, 57, 58, 65

intersection,58, 65union,58, 65

Page 147: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

144 INDEX

precondition,10, 16, 45, 80, 81, 85, 87–89, 99,100

predicate,93unary predicate,41, 42, 57, 66, 67

procedurecreation procedure,48, 51once procedure,48

productCartesian product,15, 16, 27, 57

programmingfunctional programming,72object-oriented programming,7, 56refinement-based programming,7

proofcorrectness proof,19obligation,19, 99, 103, 104, 106, 108

propertycharacteristic property,26

proxyclass,94

pureexpression,14, 16, 43, 46, 46, 47, 52feature,17, 43, 44, 45, 45, 46, 48, 50, 51, 67,

110function,17query,17, 44, 50

purityfeature purity,45, 48

quantifier,10, 67existential quantifier,10, 23, 23, 42, 58, 67,

89universal quantifier,10, 23, 23, 41, 42, 58, 89

query,17pure query,14, 17, 44, 50

QUEUE,82, 83, 90, 96

range,21, 27, 27, 57, 73restriction,28, 65

ranking,33REAL, 47, 75reduce,41refactoring,72reference,56

equality,48, 53refinement,9regular

assertion,95, 99–101, 103expression,54, 76

relation,26, 57, 78, 111algebra,9, 55, 57, 58, 113binary relation,26, 27composition,39, 62domain,27, 27equality relation,17, 70, 84finite relation,26functional relation,31, 56identity relation,27image,30inheritance relation,56inverse relation,29inversion,65iteration,30mathematical compatibility relation,58mathematical equality relation,58range,27, 27reflexive transitive closure,30transitive closure,30

restrictiondomain restriction,28, 65range restriction,28, 65

reusability,7reuse,7reversal

sequence reversal,35, 66rule

external query rule,44model argument rule,44model class inheritance rule,45model feature declaration rule,45model implementation rule,44model type rule,44once query rule,44pure query rule,44

secondpair second,25, 28

selectionmodel selection,15

SEQUENCE,87, 90sequence,14, 33, 57, 58, 78, 111

closure,36, 65concatenation,34containment,66

Page 148: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

INDEX 145

decomposition,34disjointness,36filtering, 35finite sequence,33, 33first, 35front, 35injective sequence,33, 33last,35partition,66partitioning,36random sequence,65reversal,35, 66tail, 35

SET,84–86, 88, 89, 91set,23, 55, 57, 65, 78, 82, 111

Booleans,22containment,65difference,25empty set,24infinite set,26Integers,22intersection,24, 65membership,65powerset,57proper subset,24Reals,22subset,24theory,9, 55, 57–59, 113union,24, 65

shallowequality,49

sharedassertion,93

side-effect,51abstract side-effect,48concrete side-effect,48

specification,9complete specification,51completeness,47, 101contract specification,17high-level contract specification,19minimal contract specification,19state change specification,18

STACK, 82, 83, 96, 97status

export status,97step

refinement step,9stripping

type stripping,62, 71structure

active data structure,84subexpression

common subexpression,93SUBSET,45, 93subset,24, 24substitution,9surjective

surjective function,31symbol

terminal symbol,115synonym,96, 97synopsis,109system

decomposition,56, 57, 66

TABLE, 90, 91tail

sequence tail,35tautology,17theory

set theory,9, 55, 57–59, 113there_exists,83TRAVERSABLE,83, 85, 91, 97TRAVERSABLE_SUBSET,83, 90, 91, 97tree,78

abstract syntax tree,106TUPLE,75, 77, 85, 97tuple,25, 55, 57, 65, 111type

abstract data type,15, 56anonymous type,62, 74base type,14, 44basic type,47, 72Boolean type,46expanded type,74information,65numeric type,44, 47, 60reference type,17, 44, 47, 74static type,71, 74stripping,62, 71unified type system,10

typingstrong typing,62

Page 149: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

146 INDEX

unaryoperator,48predicate,66, 67

unionfunction union,32, 38, 65generalized union,24, 58, 65powerset union,58set union,24, 56, 65

universalquantifier,67

validexpression-valid,103feature-valid,103model-valid,50, 51, 103, 107

validity error,49IFLVEB-1, 51IFLVEB-2, 51IFLVEC, 51IFLVEE-1, 51IFLVEE-2, 51IFLVEF-1, 51IFLVEF-2, 51IFLVEF-3, 51IFLVMA, 50IFLVMC, 50IFLVME, 50IFLVMF, 50IFLVMF-17, 50IFLVMF-2, 50IFLVMF-3, 50IFLVMT, 50IFLVSD, 51IFLVSM, 51VAPE, 45

variant,10VDM, 10

Z specification language,7, 9

Page 150: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

Bibliography

[Abr96] J. R. Abrial, The B-Book: Assigning Programs to Meanings, Cambridge UniversityPress, 1996.

[B-C] B-Core Ltd.,Abstract Machine Notation, Retrieved Jun 2004 fromhttp://www.b-core.com/onlinedoc/amnotation.html .

[BCC+03] L. Burdy, Y. Cheon, D. Cok, M. Ernst, J. Kiniry, G. T. Leavens, K. Rustan, M. Leino,and E. Poll,An overview of JML tools and applications, Eighth International Work-shop on Formal Methods for Industrial Critical Systems (FMICS 03) (Th. Arts and W.Fokkink, eds.), Electronic Notes in Theoretical Computer Science (ENTCS), vol. 80,Elsevier, June 2003, pp. 73–89.

[Beza] E. Bezault, Gobo Eiffel Libraries, Retrieved Mar 2004 fromhttp://www.gobosoft.com .

[Bezb] , Gobo Eiffel Tools, Retrieved Apr 2004 fromhttps://sourceforge.net/projects/gobo-eiffel .

[BP03] C.-B. Breunesse and E. Poll,Verifying JML specifications with model fields, FormalTechniques for Java-like Programs. Proceedings of the ECOOP’2003 Workshop, 2003,Technical Report 408, ETH Zurich, pp. 51–60.

[CL94] Y. Cheon and G. T. Leavens,A Quick Overview of Larch/C++, Journal of Object-Oriented Programming7 (1994), no. 6, 39–49.

[CLRS01] T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein,Introduction to Algorithms,Second Edition, MIT Press, 2001.

[Eif] Eiffel Software, Eiffel Studio: A Guided Tour, Retrieved Jun 2004 fromhttp://betadocs.eiffel.com/eiffelstudio/general/guided_tour/studio/index-17.html .

[GHJV95] E. Gamma, R. Helm, R. Johnson, and J. Vlissides,Design Patterns: Elements ofReusable Object-Oriented Software, Addison-Wesley, 1995.

[LBR] G. T. Leavens, A. L. Baker, and C. Ruby,JML: A notation for detailed design, Re-trieved Feb 2004 fromftp://ftp.cs.iastate.edu/pub/leavens/JML/jmlkluwer.pdf .

[LC] G. T. Leavens and Y. Cheon,Design by Contract with JML, Retrieved Feb 2004 fromftp://ftp.cs.iastate.edu/pub/leavens/JML/jmldbc.pdf .

147

Page 151: In Copyright - Non-Commercial Use Permitted Rights ...28352/eth-28352-01.pdf · ematical Model Library (MML), providing the necessary support to write powerful and expressive model

148 BIBLIOGRAPHY

[Lea96] G. T. Leavens,An Overview of Larch/C++: Behavioral Specifications for C++ Mod-ules, Specification of Behavioral Semantics in Object-Oriented Information Modeling(Haim Kilov and William Harvey, eds.), Kluwer Academic Publishers, Boston, 1996,pp. 121–142.

[LMMPH00] M. Labeth, J. Meyer, P. Müller, and A. Poetzsch-Heffter,Formal Verification of a Dou-bly Linked List Implementation: A Case Study using theJIVE System, Tech. Report 270,Fernuniversität Hagen, 2000.

[LPC+] G. T. Leavens, E. Poll, C. Clifton, Y. Cheon, C. Ruby, D. Cok, and J. Kiniry,JML Ref-erence Manual Draft, Retrieved Feb 2004 fromftp://ftp.cs.iastate.edu/pub/leavens/JML/jmlrefman.pdf .

[Mey] B. Meyer,Eiffel: The Language, Work in Progress, Retrieved Apr 2004 fromhttp://www2.inf.ethz.ch/~meyer/ongoing/etl/ .

[Mey92] , Eiffel: The Language, Prentice Hall, 1992.

[Mey97] , Object-Oriented Software Construction, 2nd edition, Prentice Hall, 1997.

[Mey03] , Towards practical proofs of class correctness, ZB 2003 (D. Bert et al., ed.),LNCS 2651, Springer-Verlag Berlin, 2003, pp. pp. 359–387.

[MPH99] P. Müller and A. Poetzsch-Heffter,Universes: A type system for controlling rep-resentation exposure, Programming Languages and Fundamentals of Programming(A. Poetzsch-Heffter and J. Meyer, eds.), Fernuniversität Hagen, 1999.

[Sch03] B. Schoeller,Strengthening Eiffel contracts using models, Proceedings of the Workshopon Formal Aspects of Component Software FACS’03, 2003, UNU/IIST Report No.284.

[Wik] Wikipedia, The free encyclopedia, Retrieved Jun 2004 fromhttp://en.wikipedia.org/wiki/Eiffel_programming_language .