Top Banner
A Proof Obligation Generator for the IFAD VDM-SL Toolbox Bernhard K. Aichernig M¨arz1997 Diplomarbeit in Telematik durchgef¨ uhrt am IICM – Ordinariat f¨ ur Softwaretechnologie der Technischen Universit¨ at Graz Begutachter: O.Univ.Prof. Dipl.-Ing. Peter Lucas Betreuer: Dr. Peter Gorm Larsen
101

A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Mar 11, 2018

Download

Documents

vunhi
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

A Proof Obligation Generatorfor the

IFAD VDM-SL Toolbox

Bernhard K. Aichernig

Marz 1997

Diplomarbeit in Telematik

durchgefuhrt am

IICM – Ordinariat fur Softwaretechnologieder Technischen Universitat Graz

Begutachter: O.Univ.Prof. Dipl.-Ing. Peter LucasBetreuer: Dr. Peter Gorm Larsen

Page 2: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Ich versichere, diese Arbeit selbststandig verfaßt, andere als die angegebe-nen Quellen und Hilfsmittel nicht benutzt und mich auch sonst keinerunerlaubter Hilfsmittel bedient zu haben.

Page 3: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Zusammenfassung

In den letzten Jahren hat das Interesse an formalen Methoden in der Software-entwicklungstark zugenommen. Einer der Grunde dafur, ist die Verfugbarkeit von Werkzeugen, welcheden Entwickler in der Anwendung formaler Methoden unterstutzen. Diese Diplomar-beit beschreibt eine Erweiterung der IFAD VDM-SL Toolbox, einem CASE Tool, dasdie Vienna Development Method VDM unterstutzt. Unter anderem bietet die ToolboxSyntax- und Typenprufung von formalen Spezifikationen, die in VDM-SL, der Spezi-fikationssprache von VDM, geschrieben sind. Da eine statische Typenprufung im allge-meinen unentscheidbar ist, muß diese unvollstandig sein. In traditionellen Programmier-sprachen werden die notwendigen zusatzlichen Konsistenzprufungen zur Laufzeit durchge-fuhrt. Dieser Ansatz ist fur Spezifikationen nicht anwendbar, da diese im allgemeinen nichtexekutierbar sind. Deshalb, mussen die “problematischen” Teile, welche die Unentscheid-barkeit verursachen vom Anwender auf ihre Richtigkeit gepruft werden. Fehlermeldungenund Warnungen helfen ihm dabei. Anstatt des Generierens von Fehlermeldungen wird indieser Diplomarbeit der Ansatz des Generierens von Proof Obligations beschrieben. ProofObligations sind unbewiesene Theoreme, welche Aussagen uber eine bestimmte Eigen-schaft der Spezifikation machen damit diese konsistent ist. Kann man diese beweisen, soist der betroffene Teil der Spezifikation konsistent. Das Ziel des Diplomarbeitsprojekteswar die Spezifikation eines Proof Obligation Generators in VDM-SL als Erweiterung zurbestehenden Static Semantics der Toolbox. Die Proof Obligations sind so gestaltet, daß siein das derzeit in Entwicklung befindliche Beweis-Tool der Toolbox geladen werden konnen.

i

Page 4: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

ii

Page 5: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Abstract

During the last years, the interest in formal methods for software development has beengrowing rapidly. One of the reasons for this is the availability of tools to support the devel-oper in using these formal methods. This thesis describes an extension of the IFAD VDM-SL Toolbox, a CASE tool supporting the Vienna Development Method VDM. Amongstother features the Toolbox supports parsing and type checking of specifications writtenin VDM-SL, the specification language of VDM. Static type checking in VDM-SL is un-decidable in general and therefore the type checker must be necessarily incomplete. Intraditional programming languages the additional consistency checks are performed at runtime. This approach is not feasible, because specifications are not executable in general.Hence, it is up to the user to verify the consistency of a specification for the “difficult”parts introducing undecidability. In the existing type checker the user is supported byerror messages and warnings generated during type checking. Instead of providing errormessages, in this thesis the approach of generating proof obligations for consistency is de-scribed. A proof obligation is an unproven theorem stating that a certain property musthold in order for the specification to be consistent. If a proof obligation can be proved,then the part referred to in the specification is consistent. The goal of the thesis projectwas the specification of a proof obligation generator in VDM-SL as an extension to theexisting static semantics of VDM-SL. The proof obligations are designed to be importedinto a theorem prover for the Toolbox which is currently under development.

iii

Page 6: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

iv

Page 7: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Preface

This thesis is written as a partial fulfillment of the requirements for the degree of Diplomin-genieur der Telematik at the Technical University of Graz (TU-Graz) in Austria.

The thesis project was carried out at the Institute of Applied Computer Science, IFAD,at Odense, Denmark. The work was performed during the period 1st August 1996 to 31thJanuary 1997, in which both research and development took place.

The subject of this thesis is the specification of a proof obligation generator as anextension to the existing type checker of the IFAD VDM-SL Toolbox. The central ideasin this thesis have also been presented at the TIAPS Workshop held at IFAD on the 28thand 29th of November 1996.

This work was supervised by O.Univ.-Prof. DI Peter Lucas at TU-Graz and by Dr. Pe-ter Gorm Larsen at IFAD.

v

Page 8: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

vi

Page 9: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Acknowledgments

I would like to express my gratitude to all those people who have supported me throughoutmy stay in Denmark. I know that I cannot mention all the people who helped me troughthese six months, but I will give it a try.

First of all, I would like to thank Benny Graff Mortensen for giving me this wonderfulopportunity to work at IFAD. Secondly, I would like to thank my supervisor Peter GormLarsen for both, giving me an insight into his way of performing scientific work, and forthe guidance in the project. I would also like to thank my office colleague Sten Agerholm,who has provided considerable input on the directions of the work reported in this thesis.I would like to thank my professor, Peter Lucas, who made my stay possible. He intro-duced me to formal methods and taught me formal specifications, proofs and compilerconstruction. I’m grateful for the support of the Austrian Federal Ministry of Science andResearch (Kurt Godel Scholarship) for my stay.

Next, I would also like to thank all the people at IFAD for making me feel at home.Special thanks go to Anne Berit Malmborg Nielsen for arranging housing for my stay, andHenrik for answering my technical questions.

I would also like to thank all the students at the students residence where I lived duringmy stay in Denmark. They made me feel at home and were always there for me in caseof problems.

And finally I would like to thank all the people back in Austria who have supportedme morally by sending emails and cards. Special thanks to my parents for letting me goto Denmark. Thanks,

Bernhard Klaus Aichernig

vii

Page 10: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

viii

Page 11: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Contents

1 Introduction 11.1 Nature of this Thesis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Formal Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.3 VDM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.4 The IFAD VDM-SL Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . 51.5 The TIAPS Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.6 Relation to Previous Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.7 Aims . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2 Why Proof Obligations? 92.1 Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2.1.1 Dynamic Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.1.2 Static Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.2 Consistency in VDM-SL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.2.1 Types in VDM-SL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.2.2 Undecidability of Type Checking . . . . . . . . . . . . . . . . . . . . 132.2.3 The Strategy of Consistency Checks in VDM . . . . . . . . . . . . . 14

2.3 The Present Static Semantics of the VDM-SL Toolbox . . . . . . . . . . . . 152.4 The New Approach — Proof Obligations . . . . . . . . . . . . . . . . . . . . 20

3 Generating Proof Obligations 233.1 The Proof Obligation Generator . . . . . . . . . . . . . . . . . . . . . . . . 23

3.1.1 Proof Obligations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243.1.2 Context Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3.2 A Guided Tour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263.2.1 A Trusted Gateway . . . . . . . . . . . . . . . . . . . . . . . . . . . 263.2.2 The Gateway Specification . . . . . . . . . . . . . . . . . . . . . . . 273.2.3 The Synthesis of Proof Obligations . . . . . . . . . . . . . . . . . . . 30

3.3 The Satisfiability Proof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333.3.1 Step One . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333.3.2 Step Two . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343.3.3 Step Three . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.3.4 Step Four . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

ix

Page 12: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

x CONTENTS

3.3.5 Step Five . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373.3.6 The Complete Proof . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

4 Consistent Expressions 414.1 From Type Checking to Proof Obligations . . . . . . . . . . . . . . . . . . . 41

4.1.1 Well-formedness of Expressions . . . . . . . . . . . . . . . . . . . . . 414.1.2 Extended Well-formedness . . . . . . . . . . . . . . . . . . . . . . . . 42

4.2 Type Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434.3 Domain Checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

4.3.1 Functions with Pre-conditions . . . . . . . . . . . . . . . . . . . . . . 454.3.2 Partial Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

5 Consistent Pattern Matching 535.1 Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535.2 Type Checking Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545.3 Let expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565.4 Don’t Care Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

5.4.1 Unique Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575.4.2 Type Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585.4.3 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

5.5 Cases Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

6 Operations 636.1 Generating Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636.2 Expressions in Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

7 Concluding Remarks 677.1 Assessment of the Project Results . . . . . . . . . . . . . . . . . . . . . . . 677.2 Personal Experiences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687.3 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

Bibliography 71

A More Examples 79A.1 Alarm System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

A.1.1 Proof Obligations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81A.2 Traffic Light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

A.2.1 Proof Obligations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

Index 88

Page 13: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Chapter 1

Introduction

1.1 Nature of this Thesis

The subject of this thesis is the generation of proof obligations for consistency of VDM-SL specifications. More precisely, a proof obligation generator (POG) has been specifiedextending the existing type checker of the IFAD VDM-SL Toolbox.

In the development of a proof obligation generator for consistency several elementsmust be considered: the specification language itself, in our case VDM-SL with its syntaxand semantics, the existing tool to which the POG must be added, the logic, here the Logicof Partial Functions (LPF) [46, 47], and the proof system that will prove the obligations.All these aspects can be found in our work, although in this thesis special attention isgiven to the language and the consistency of specifications written in it.

Due to the fact that the IFAD VDM-SL Toolbox is a commercial CASE Tool the fullexecutable VDM-SL specification is confidential. All the ideas, principles and conceptswhich were necessary for the formal specification of the proof obligation generator arepresented in this thesis. The thesis is designed in a way that the reader will understandthe whole subject without knowing the full specification, which means that parts of theconfidential specification are taken in where it is necessary.

We give a short indication of the contents of each of the chapters. The rest of Chapter1 is devoted to a short introduction into the subject of this thesis. Furthermore, the aimsof this thesis and of the approach taken are presented. Chapter 2 discusses the problemof static consistency check and answers the question why this thesis and its subject areneeded. Chapter 3 explains and illustrates the generation of proof obligations by anexample and shows how a generated proof obligation can be proved. Chapter 4 focuses onthe consistency of expressions and gives an overview of the partial operators in VDM-SLand their proof obligations. Chapter 5 gives a short introduction to pattern matching, anadvanced feature of VDM-SL, and presents the approach taken for it. Chapter 6 coversthe operational part of VDM-SL, statements and states and Chapter 7 finally contains theconclusions of our work and lists some suggestions for further extensions.

1

Page 14: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

2 CHAPTER 1. INTRODUCTION

1.2 Formal Methods

Software is increasingly being used in situations where failure could be life threatening,such as aircraft, nuclear power plants, weapon systems, and medical instrumentation.Formal methods are a promising approach for increasing our confidence in these safety-critical systems.

Formal Methods refers to the use of techniques from mathematical logic and discretemathematics in the development of computer based systems. “Formal” is derived fromformal logic, where it means to use methods of reasoning that are sound by virtue of theirform and independent of their content.

In many existing documents [19, 24, 43, 53] formal methods have been described andexplained very well. Therefore, there is no need to rewrite these definitions. However,a summary of statements and quotes is presented which serves as an introduction to theaims and motivations of formal methods.

The UK Military of Defence Interim defence Standard on the procurement of Safety-Critical Software [89] defines a formal method as:

A software specification and production method, based on a mathematicalsystem, that comprises: a collection of mathematical notations addressingthe specification, design and development phases of software production; awell-founded logical system in which formal verification and proofs of otherproperties can be formulated; and methodological framework within whichsoftware may be verified from the specification in a formally verifiable manner.

Of course many other definitions exists and one has to be aware that most of these “formalmethods” do not provide guidelines about the order in which development steps shouldbe undertaken. Formal methods are usually simply a set of formal techniques and toolswithout this kind of precise guidelines and in some cases formal methods are identical toa formal specification language. The overall goal of formal methods is described in [15]:

People today use an enormous number of “systems” ranging in complexityfrom washing machines to international airline reservation systems. Comput-ers are used in nearly all such systems: accuracy and security are becomingincreasingly essential. The design of such computer systems should employdevelopment methods as systematic as those used in other engineering disci-plines.

The benefits from effective applications of formal methods are taken out of [48]:

• Formal methods help find defects that went undetected during extensive testing [63].

Page 15: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

1.2. FORMAL METHODS 3

• Formal specifications allow defects in requirements and designs to be detected earlierand greatly reduce the incidence of mistakes in interpreting and implementing correctrequirements and designs.

• Formalized statements can be analysed and their consequences calculated in a re-peatable manner. The risks of drawing conclusions about a system’s behavior byextrapolating from a finite number of tests often can be avoided by using proof meth-ods based on mathematics. Such methods allow large (potentially infinite) classesof test cases to be fully covered in a finite proof, and they support reasoning thatcan be checked by colleagues or by machine, with minimal dependence on subjectivereasoning.

• Use of formal methods causes more defects to be detected than would otherwise bethe case and in certain circumstances guarantees the absence of certain defects.

In [26] the importance of combining formal methods with traditional approaches is em-phasized:

The general point to note is that formal methods are not meant to replaceexisting good software engineering practices, but, rather, to complement andenhance such practices! Formal methods cannot be effectively used in theabsence of good software engineering practice and, I venture to add, I do notthink that software engineering can long continue to ignore the benefits thatcan accrue from the careful insertion of formal methods.

The problem of today’s software engineering is brought to the point in [27]:

Most software engineering claims are based on dubious scientific grounds. Thisis not to say the claims are necessarily false, only that they are scientificallyunproven.

Finally, in combination with the last quote, the words of David Hilbert in his presentationat the second world congress of mathematics in Paris, 1900, express the need of formalapproaches in software engineering [23]:

The uniform character of mathematics is founded in the innermost entity ofthis science; since mathematics is the base of all exact scientific knowledge.

Page 16: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

4 CHAPTER 1. INTRODUCTION

1.3 VDM

In this section, the Vienna Development Method (VDM) and its specification language(VDM-SL) is described. The contents is based on [74, 76, 8, 53].

VDM is a formal method for the description and development of computer basedsystems. It is a model-oriented method, i.e. its formal descriptions (VDM specifications)consists of an explicit model of the system being constructed. A system design is generatedthrough a series of specifications, where each specification is more concrete and closer tothe implementation than the previous one [14]. Each of these development steps introducesproof obligations1 which, when appropriately discharged, ensure the (relative) correctnessof the implemented system.

VDM is one of the most widely used formal methods and has been applied to theconstruction of a large variety of software systems [32, 12, 18, 20, 25, 39, 44, 50, 67, 69, 82,88]. Its history starts in 1969, when, in the IBM laboratory in Vienna, a group of people,managed by Heinz Zemanek, worked on formal language definition and compiler design.The goal was to create an operational semantics for the programming language PL/I [61,62]. By outsiders the used meta-language was dubbed the “Vienna Definition Language”or VDL. Due to the complicated formal reasoning about the operational semantics, anew approach , using denotational semantics, was taken in 1972 with the meta-languageMeta-IV . In the past, Meta-IV has been used in many different variants. First of all,these variants reflect several different styles in the use of VDM: the Danish, Irish andthe English school. The difference between the schools is primarily caused by differentapplication areas. The Danish school focused on modeling large software systems, andthus used VDM to abstract from complex systems for better understanding, whereas theEnglish school has focused more on the correctness of smaller systems and used a moreimplicit style in order to ease the verification of the systems.

In the mid-eighties the British Standards Institution (BSI) started to harmonize thedifferent variants producing a standard for Meta-IV [84, 5, 75, 71]. In the nineties thiswas taken up by the International Organization for Standardization (ISO) [7] and Meta-IVbecame VDM-SL.

VDM consists of two major components:

• The VDM Specification Language, VDM-SL. The language describes a notation inwhich VDM specifications can be expressed.

• A method describing the development from a specification to an implementation in acertain programming language. The method part of VDM is not as precisely definedas the VDM-SL notation.

The VDM bibliography [52] contains more than 500 references including tutorial textbooks [46, 6, 45], a reference manual of VDM-SL [31] and a book about proof in VDM[10].

1Don‘t mix these proof obligations, which ensures that a concrete specification satisfies the same prop-erties than an abstract one (see [46]), with those of our proof obligation generator. The proof obligationsinvestigated in this thesis ensure the internal consistency of a single specification according to the dynamicsemantics of the language.

Page 17: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

1.4. THE IFAD VDM-SL TOOLBOX 5

1.4 The IFAD VDM-SL Toolbox

The IFAD VDM-SL Toolbox plays a twofold role in this work. First, the thesis describesand specifies an extension of the type checker of the IFAD VDM-SL Toolbox. Second,the Toolbox itself is used to develop the specification of the proof obligation generator.Therefore, a short description of the IFAD VDM-SL Toolbox is provided, mainly basedon [37].

The IFAD VDM-SL Toolbox is a set of tools to support the development of VDM-SLspecifications. The Toolbox supports the VDM-SL standard, extended with a structuringmechanism based on the concept of modules [36]. The following facilities of the IFADVDM-SL Toolbox have been used during this project:

Syntax checking of VDM-SL specifications. To provide a literate programming style[Knuth84] for specifications, the VDM-SL source code may include LATEX [51] typesettext.

Static semantic checking. The subject of this thesis is an improvement of this part ofthe tool.

Pretty printing. The VDM source code in ASCII format is converted into the mathe-matical notation for VDM-SL by generating a LATEX document.

Execution. Specification interpretation is provided for all executable constructs in VDM-SL. The specified proof obligation generator is fully executable.

Test coverage analysis. Test coverage information can be automatically recorded dur-ing the evaluation of a test-suite. The specifier can at any point check which partsof the specification are most frequently evaluated and which parts have not beencovered at all.

Source-level debugging. The debug mode is used to interpret the specification. Thismode provides an overview of break points, function trace, and definitions availablein the specification.

Specification management maintains a project by keeping track of the status of mod-ules and remembering this status from session to session. Furthermore, all thefunctionalities are accessible through a graphical user interface.

Furthermore, the Toolbox includes a C++ code generator and a dynamic link facility tocombine VDM-SL specifications with C++ code [33]. Finally, we want to point out that,like the new proof obligation generator, almost every component of the Toolbox itself isspecified in VDM-SL.

1.5 The TIAPS Project

As mentioned in Section 1.1 the subject of generating proof obligations is strongly in-fluenced by the proof tool for which the proof obligations are designed. The Towards

Page 18: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

6 CHAPTER 1. INTRODUCTION

Industrially Applicable Proof Support for VDM-SL (TIAPS) project concerns prototypedevelopment of an industrially applicable proof support system. TIAPS is a joint projectof IFAD and the Technical University of Denmark (DTU), Lyngby. The aims are the com-bination and interaction of the IFAD VDM-SL Toolbox and the general-purpose theoremprover Isabelle [73, 72]. The proof theory with which Isabelle is instantiated is taken from[10].

The overall idea in connection with this thesis is that the user writes his VDM-SLspecifications using the IFAD VDM-SL Toolbox. When the user wants to prove a proofobligation generated by the type checker, he can start the Proof Support Tool (PST),generate axioms from the specification and load these together with the proof obligationsinto the VDM-SL instantiation of Isabelle. There, proofs can be conducted and managedthrough a graphical user interface, through which underlying Isabelle is completely hiddento the user [2].

On the 28th and 29th of November 1996 the first TIAPS Workshop took place, wherethe central ideas in this thesis were presented to an audience of experts in formal methodsand theorem proving.

1.6 Relation to Previous Work

Some similar work has been done before, but the specified proof obligation generatoris the first one for VDM-SL covering the advanced topics of pattern matching and thenon-functional part (operations and states). The central idea influencing this work comesfrom Flemming M. Damm, Hans Bruun, and Bo Stig Hansen [29, 30]. But also some othertools (methods) already generating proof obligations motivated this extension of the IFADVDM-SL Toolbox with a proof obligation generator.

RAISE: In the RAISE Specification Language [35, 77] an expressive notion of types isalso used for type checking. As a separate facility, not part of type checking, proofobligations called “confidence conditions” may be generated. These rule out, e.g.,dynamic type errors.

PVS: PVS (Prototype Verification System) [70, 85] is an environment for specificationand verification consisting of a specification language, a parser, a type checker, andan interactive theorem prover. The type checker in PVS generates proof obligationscalled TCCs (Type Correctness Condition). However, PVS only supports (tagged)disjoint union types, which do not cause undecidability like the non-disjoint unionsin VDM-SL. The TCCs relate to subtypes, partial operators and the termination ofrecursive functions.

B-Method: The B-Toolkit [40, 56] has a proof obligation generator, that can be invokedfrom the “Main Environment”. The POs are generated according to the correctnesscriteria which are required to hold within the B-Method [1]. Thus, for examplethe criteria requiring that an Abstract Machine initialisation must establish theinvariant, and that each operation re-establishes the invariant. A comparison ofVDM and B can be found in [11]

Page 19: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

1.7. AIMS 7

Z/EVES: The Z/EVES system [80, 81], a Z front-end to the theorem prover EVES[28] provides domain checking for Z specifications, which is the generation of proofobligations for ensuring that all functions and operators are applied with parametersinside their domain. The same is done in our work, but Z does not have a type systemas rich as VDM [41]. Our work covers a wider area, e.g. union types and patterns.Thus, domain checking is a subset of our consistency checks.

SPARK: SPARK is an annotated subset of Ada, designed to eliminate ambiguities andinsecurities of the full Ada language [22]. The SPARK Examiner, a tool which checksconformance of a program to the rules of SPARK, also generate POs called “verifi-cation conditions”. Mandatory annotations in a program are used to generate thesePOs. However, SPARK does not allow exceptions and overloading and has simplifiedscope and visibility rules. Unlike in our approach to operations, where annotations(assertions) are generated as proof obligations, in SPARK the annotations are addedby the programmer in order to be able to generate POs [34].

1.7 Aims

The overall aim of formal methods is the development of correct programs. Formulatingthe specification in a formal language like VDM-SL is one step towards this goal (seeSection 1.2). However, this statement only holds if our specifications are correct. It isclear that we can not prove the correctness of the initial specification, therefore a number oftechniques have been proposed which allow us to increase our confidence in the correctnessof a specification. The IFAD VDM-SL Toolbox provides validation techniques like syntaxand type checking. Unlike syntax checking, static type checking in VDM-SL is undecidableand therefore static type and related consistency checks are necessarily incomplete.

The aim of this thesis is to improve the existing type checking process by linking itto a theorem prover. The link is performed by generating proof obligations during typechecking for those parts of a specification which cannot be checked automatically. Theseproof obligations for consistency are unproven theorems stating that a certain conditionmust hold in order to ensure that a specification is consistent. The proof obligations aredesigned to be incorporated into the proof support tool currently under development atIFAD. In this thesis we will explain why this is necessary and how we reached this aim.

It is the aim of this project to specify a proof obligation generator in addition tothe existing static semantics. Thus, the goal is a new static semantics including thefeature of generating proof obligations. The resulting specification will be written inan executable subset of VDM-SL. Therefore, the specification can be developed usingprototyping strategies and testing.

As seen in the previous section, this project is not the first one concerning proof obli-gations for consistency of specifications. However, the aim of this thesis is the specificationof the first proof obligation generator for VDM-SL covering the whole language includingpattern matching and the operational (imperative) part of VDM-SL.

Page 20: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

8 CHAPTER 1. INTRODUCTION

Page 21: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Chapter 2

Why Proof Obligations?

The aim of this chapter is to give an introduction to the challenge posed for this thesisproject and to answer the question why a proof obligation generator for VDM-SL is needed.Due to the fact that the static semantics has to be extended in this project, some importantdefinitions and explanations concerning semantics are given first. Next, consistency ofVDM-SL specifications is discussed. Then, an overview of the present static semantics ofthe VDM-SL Toolbox is given. Finally, our approach of generating proof obligations ispresented.

2.1 Semantics

The goal of formal methods like VDM is to write down the properties and requirementsof a system in a formal way. In the introduction we explained the advantages of suchan approach. The result of describing a system with VDM is a document written in theformal language VDM-SL — the specification.

This thesis describes an extension of a VDM-SL type checker, and is therefore stronglyrelated to VDM-SL and the meaning (interpretation) of its constructs. Dealing withlanguages, the meanings of their syntactical constructs are called the semantics. Thedictionary [57] gives a general definition:

Semantics: The study of the meaning of words and other parts of a language.

In [13] the following definition can be found:

A language is a system of signs. Semantics deals with the signification (i.e.meaning) of signs in all modes of signifying, or: semantics is the study of therelations of signs to the objects to which the signs are applicable.

In general, the term semantics is used for the meaning of any description technique. How-ever, often the semantics of graphical description techniques are rather intuitive thanformal, which causes ambiguities. Therefore, the first task for formal methods was theformal specification of the semantics of new computer languages(see [59, 58, 61]), encour-aged by the success of formal syntax descriptions using the Backus-Naur form BNF (see[3]) and their extensions.

9

Page 22: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

10 CHAPTER 2. WHY PROOF OBLIGATIONS?

A single mathematical definition for the term “semantics” cannot be given, becauseseveral methods were introduced by different research groups all related to this term. Allof these methods wanted to answer the question, “How can we write down the meaning ofcomputer languages such that we can analyze properties of pieces of text written in thatlanguage?”

However, it is possible to distinguish two different kinds of semantics:

• Dynamic Semantics

• Static Semantics

Note, that this distinction is not undisputed. The MetaSoft group [16] did not want tosee this difference [17]. In fact the static semantics is a part of the dynamic semantics andthe distinction should be seen more as a matter of structuring than of dividing. Belowthese concepts are defined in more detail.

2.1.1 Dynamic Semantics

Definition: A syntacticly valid construct is given a meaning by defining the evaluationof that construct.

The three main paradigms of defining dynamic semantics of a system are operationalsemantics, denotational semantics and axiomatic semantics. We will give a short descrip-tion and point out the differences (see also [68, 90, 23]).

Operational Semantics

Operational semantics was the first attempt to define the dynamic semantics using ma-chines and their states. The history of state changes and of returned values, when evalu-ating a construct (expression), defines the dynamic semantics. The dynamic semantics ofthe IPTES Meta-IV language was designed in the operational style (see [55]) and the firstapproach in the early history of VDM was operational (see [7, 58, 59, 60]).

Denotational Semantics

Denotational semantics describes the meaning of a program by explicitly stating the math-ematical value denoted for each construct. Language constructs and their meaning areconnected by a valuation function. The valuation function is actually a collection offunctions, one for each syntactic construct. The principle of denotational semantics isto compose these basic functions in order to define the meaning of composed constructs[83, 86]. This is a more abstract view on the semantics, because it is not the internalactions that are of interest, but the values produced. This method is used in VDM. Ashort overview of the principles can be found in [62]. The dynamic semantics of VDM-SLitself is defined in the ISO-standard [7] using this approach.

The dynamic semantics of VDM-SL is defined as a total function D, which for eachspecification yields the set of models satisfying the specification. If a specification is

Page 23: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

2.1. SEMANTICS 11

inconsistent D yields the empty set. We will clarify the term “inconsistency” in Section2.2.

Axiomatic Semantics

In axiomatic semantics the meaning of a system is described by, as the name says, a setof axioms. These axioms define the properties of a system. If the axioms are expressed asequalities the axiomatic semantics is also called algebraic semantics.

The specification language VDM-SL provides a denotational style, but can be used foroperational semantics as well (using states). It does not support axiomatic semantics, likeRAISE [35] does.

2.1.2 Static Semantics

Definition: Static semantics specify whether or not a syntactically valid construct iswell-formed given a set of context conditions for a language.

“Static” refers to those properties of a specification or program which can be inferredwithout executing it. Consequently, static semantics analysis ensures that certain errorsin the program (specification) will be detected or possible errors will raise a warning.

[3] gives examples of such static checks:

Type checks: Check whether or not operators are applied to type incompatible operands.For example adding a truth value to a numerical value is not allowed.

Flow-of-control checks: Statements that cause flow-of-control to leave a construct musthave some place to which to transfer this flow-of-control . For example in the Clanguage [49], a “break” statement is only allowed in the body of a “while” or a“switch” statement.

Uniqueness checks: There are situations in which an object must be defined exactlyonce. For example in the Pascal language, an identifier must be declared uniquelyand labels in a “case” statement must be distinct.

Name related checks: Sometimes the same name must appear two (or more) times.For example in the Ada language, a block statement may have a name which shouldappear both at the beginning and the end of the construct.

A traditional approach, when defining the semantics of a programming language, is todefine the static semantics first and then define the dynamic semantics to work only onobjects fulfilling the predicates of the static semantics, i.e. the dynamic semantics isdefined under the assumption that the objects are well-formed with respect to the staticsemantics. For VDM-SL the approach is somewhat different as the dynamic semantics

Page 24: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

12 CHAPTER 2. WHY PROOF OBLIGATIONS?

has been defined before the static semantics. It is defined to work on all objects of thecore abstract syntax, which means that the traditional static semantics is included in thedynamic semantics.

Therefore, the task of the static semantics can be seen from two different points of view(see [38]): First, it should be used by tool builders who want to check the consistency ofa specification. This is our usage of the static semantics, since we extend the existingspecification of the static semantics to improve the type checking algorithm.

Second, the static semantics could be used if it is too hard to understand the dynamicsemantics directly.

The static semantics of IFAD VDM-SL, which has extensions for structuring specifi-cations using modules, is fully specified in the confidential report [54]. The work in thisthesis will extend and improve the existing static semantics in a way that is described inthe following sections.

2.2 Consistency in VDM-SL

The matter of consistency of VDM-SL specifications can be explained by the dynamicsemantics.

Since the dynamic semantics D is defined as a total function mapping specificationsto the set of models fulfilling the specification, a specification is inconsistent if the resultof D is the empty set. Trivially, a specification is consistent if it is not inconsistent.

The static semantics defines the consistency for all language constructs. Implementingthe static semantics results in a type checker, which checks the consistency of a spec-ification, or in other words it checks the well-formedness of all syntactical constructs.Examples of different kind of consistencies are type consistency and the termination ofrecursive functions.

The most important and difficult consistency check in VDM-SL specified in the staticsemantics is type checking. Before explaining type checking we have to understand theVDM-SL type system and the differences to traditional types.

2.2.1 Types in VDM-SL

The purpose of types in a programming or specification language is twofold. First, typesare an important tool for modeling. Second, types are an important instrument for au-tomatic consistency checking. Traditional programming languages tend to emphasize thesecond point, and therefore, restrict the type system to build fast and reliable compilers.

Because VDM-SL is a specification language, modeling is in the foreground, which hada major impact on designing the type system. One of the main features of VDM is therich type system of VDM-SL. Examples of this richness are:

Type relation. In VDM-SL the sets of values denoted by different type expressions neednot to be disjoint. For example, consider the natural numbers (nat) that are a subsetof the integers (int). Therefore, it is possible to define a function:

Page 25: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

2.2. CONSISTENCY IN VDM-SL 13

f: nat -> intf(n) == n

Union types. The union type corresponds to a set-theoretic union, i.e the type definedby means of a union type will contain all the elements from each of the componentsof the union type. For example consider the union type of real numbers and Booleanvalues real | bool. A function for safety division can be specified as follows.

Div: int * int -> real | boolDiv(n1, n2) == if n2 <> 0

then n1 / n2else false

The specification might be unusual for readers used to traditional programminglanguages.

Invariant types. It is possible to define subtypes by restricting the values in a type bymeans of an invariant. The result is that the type is restricted to a subset of its

original values, also called a subtype. Thus, the acceptable values of the definedtype are limited to those where a predicate (the invariant) evaluates to true. Anexample of a type denoting the natural numbers greater than 4 is given:

Nat5 = natinv n == n > 4

For further syntactical details of the language see [31, 36]. The demonstrated power of theVDM-SL type system in modeling causes difficulties in type checking. The main problemis discussed below.

2.2.2 Undecidability of Type Checking

The main reason for this work is the fact that static type checking in VDM-SL is unde-cidable in general, which means that type checking must be necessarily incomplete. InVDM-SL the undecidability is introduced by the rich type system and partiality.

• One of the reasons for the undecidability is the union type. A simple example makesthe problem obvious: The consistency check of simple expressions like

x + 1

where x is of the union type nat | bool is not statically decidable, because if x isa natural number, the expression is type consistent, or if x is a Boolean value, thenthe expression is type inconsistent. Therefore, the well-formedness depends on thecontext of the expression. In some trivial cases expressions of some special form, forinstance

Page 26: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

14 CHAPTER 2. WHY PROOF OBLIGATIONS?

if is_nat(x) then x + 1 else ...

might be recognized and the knowledge that x is of type nat could then be exploitedwhen checking the “then” branch of the conditional. However, in general this isnot possible, because the test expression in the conditional can be an arbitraryexpression.

• Another kind of type construction introducing undecidability are subtypes definedby invariants. To check automatically that an invariant holds the evaluation of theinvariant would be necessary, which would not be a static check anymore.

• Partial operators must only be applied to their defined operands, e.g. the hd operatortaking the first element of a sequence is not defined for an empty sequence. Ingeneral these domain checks are not statically decidable. The same holds for partialfunctions, defined by pre-conditions.

Traditional programming languages get rid of some undecidable checks by restricting thelanguage facilities, for example by having strict type systems without subtypes. However,the problem of partial operators remains: It is impossible to prevent reading the head of anempty list or to prevent over-running the boundaries of an array at compile time. The run-time type check has to cover these cases. Therefore, extensive testing has to be performedto raise the confidence in the consistency of a program. The term confidence is used,because even after testing the specification could be inconsistent. However, this traditionalapproach is not viable for specifications, since VDM-SL specifications are usually notexecuted. Here it should be mentioned that the IFAD VDM-SL Toolbox provides a testfacility for specifications, but not all specifications are executable. Therefore, in VDM-SLa special strategy for type checking is applied, which is described in the following section.

2.2.3 The Strategy of Consistency Checks in VDM

We have seen that static type checking in VDM-SL is undecidable in general. Therefore,to guarantee termination, an applicable type checking algorithm must be incomplete. Tocover an as large as possible set of specifications, the strategy of the static semantics istwofold:

• Acceptance of specifications, which are definitely consistent.

• Rejection of specifications, that are definitely inconsistent.

Rejection is a well known strategy in traditional type checking of programming languages.We call this the possible type check, because we infer in this algorithm whether it ispossible that a specification is consistent or not. If it is not, it is rejected.

Classical type checking allows rejection of some kinds of inconsistencies but acceptanceis not directly supported. However, in type checking specifications, acceptance of definitelyconsistent ones is an important supplement, because of non-executability. Although, the

Page 27: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

2.3. THE PRESENT STATIC SEMANTICS OF THE VDM-SL TOOLBOX 15

Extended acceptance

Basic rejection Basic acceptance

Extended rejection

Inconsistent specifications Consistent specifications

Figure 2.1: Rejected and accepted subsets of specifications.

specification is executable the acceptance algorithm ensures that a specification is def-initely type consistent, and therefore testing for type consistency is not needed. Thisalgorithm is called the definite type checker [29].

Figure 2.1 (taken out of [21]) illustrates the relationship between acceptance and re-jection. The outer oval represents the set of all specifications that can be written. Thethick line indicates the border between consistent and inconsistent specifications. Thefilled areas to the right and left are the subsets of specifications that can be rejected oraccepted by the static semantics algorithm. Following the approach in [29], we can furtherdivide the two strategies into basic rejection/acceptance and into a number of extensions.The set of possible extensions is open to future additions. The white area is the set ofundecidable specifications, which are possibly consistent but not definitely. These speci-fications, are left to the user for checking the consistency. Our approach will cover theseundecidable specifications, or more precisely the parts introducing the undecidability.

Basic acceptance and rejection is the basic level of type checking achieved by checkingsynthesized expression types against the type constraints imposed by the context of theexpression. In the following section we will see how these type rules are implemented inthe existing type checker in the static semantics of the IFAD VDM-SL Toolbox.

2.3 The Present Static Semantics of the VDM-SL Toolbox

This section is an overview of the existing type checker focusing on the parts which areessential for this work. The existing static semantics is fully specified in the confidentialdocument [54]. It is an executable specification based on the ISO standard [7] and im-plemented in the Toolbox. The static semantics is designed using so-called well-formedpredicates which check the consistency for every syntactical construct. The checks startat module level (if there are modules specified) and recursively go down to, e.g., the

Page 28: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

16 CHAPTER 2. WHY PROOF OBLIGATIONS?

well-formedness of a binary operator and its operands. The specification document ofthe existing type checker (static semantics) contains more than 250 pages organised in 12different modules.

According to the twofold strategy in the static semantics the type checker runs in twomodes:

1. possible mode (POS): error messages indicate definitely inconsistent parts in thespecification; the specification is rejected. For example, the type checker will raisean error message if a specification contains the expression 1 + true. This kind ofrejection approach is usually used for traditional programming languages.

2. definite mode (DEF): the absence of error messages indicates the acceptance ofthe specification. The specification is definitely consistent. For example, 1 + 2 isdefinitely consistent. However, for many VDM-SL constructs it cannot be decidedif they are definitely consistent, although they are possibly consistent. These arethe “difficult parts” introducing the undecidability. Therefore now, for nearly allVDM-SL specifications this automatic definite consistency check fails, because eachundecidable construct in a specification causes an error message or warning.

In the graphical interface of the IFAD VDM-SL Toolbox the user can set an option tochoose which kind of type checking he wants to perform [37].

The central task of the type checker is to check if two types, an expected and an actualtype, are compatible. Due to the rich type system of VDM-SL, a simple comparison isnot possible in general. Furthermore, the task is statically undecidable in general, becauseof non-disjoint unions and subtypes [29]. Thus, reflecting our strategy of acceptance andrejection, the compatibility is checked in two modes.

The operation1 performing the compatibility check IsCompatible2 takes three argu-ments. The first argument specifies the kind of type checking that should be performed(POS or DEF). The next two arguments (TpR1, TpR2) are the types that must be checked.From the signature it can be seen that TpR1 and TpR2 are of type TypeRep the internaltype representation of the static semantics. POS and DEF are quote types which, aspart of an union type (POS | DEF), correspond to enumerated types in a programminglanguage.

1An operation is used, because the auxiliary operations IsOverlapping and IsSubType refer to theenvironment state containing type names and their type binding.

2In order to distinguish between example specifications (object-level) and the specification of the staticsemantics (meta-level), the first is printed in ASCII form, the latter is pretty printed.

Page 29: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

2.3. THE PRESENT STATIC SEMANTICS OF THE VDM-SL TOOLBOX 17

BA B A

possible definite

Figure 2.2: The sets of values denoted by two compatible types.

IsCompatible : POS | DEF× TypeRep × TypeRep o→ BIsCompatible (i ,TpR1,TpR2) 4

if TpR1 = TpR2then return true

else cases i :POS → IsOverlapping(TpR1,TpR2) ,DEF → IsSubType(TpR1,TpR2)

end;

In the trivial case that the two types are the same, true is returned. Otherwise, de-pending on the kind of typechecking (possible or definite), the function checks whetherthe types are overlapping or whether one is a subtype of the other. Below the two modesare explained.

Possible Compatibility

The task of this algorithm is to check, whether it is possible that two types are compatibleor not. Two types are possibly compatible if they are overlapping, which means thatthe sets of values they denote are non-disjoint. In VDM-SL two different basic types areoverlapping if both of them are numeric types. If two types are not overlapping, theycannot possibly be consistent and therefore can be rejected.

In the previous example x + 1, where x is a union type of natural numbers and Booleanvalues, the type of x is overlapping with the general expected numeric type of the plusoperator (real), and therefore, the binary expression is possible type consistent. In Figure2.2 the relation of the two sets of values denoted by their type is shown. The possiblycompatible values are within the overlapping area.

For basic types, sets, sequences, products, and union types the specification of theoverlapping relation is given below:

Page 30: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

18 CHAPTER 2. WHY PROOF OBLIGATIONS?

IsOverlapping : TypeRep × TypeRep o→ BIsOverlapping (TpR1,TpR2) 4

cases mk- (TpR1,TpR2):mk- (t , t) →

return true,mk- (mk-BasicTypeRep (BTp1), mk-BasicTypeRep (BTp2)) →

let NumericTypes = {NATONE, NAT, INTEGER, RAT, REAL} in

return BTp1 ∈ NumericTypes ∧BTp2 ∈ NumericTypes,

mk- (mk-SetTypeRep (STp1), mk-SetTypeRep (STp2)) →return IsOverlapping (STp1,STp2),

mk- (mk-SeqTypeRep (STp1), mk-SeqTypeRep (STp2)) →return IsOverlapping (STp1,STp2),

mk- (mk-ProductTypeRep (PTp1), mk-ProductTypeRep (PTp2)) →if len PTp1 = len PTp2then return ∀ i ∈ inds PTp1 ·

IsOverlapping (PTp1 (i),PTp2 (i))else return false ,

mk- (t , mk-UnionTypeRep (s)),mk- (mk-UnionTypeRep (s), t) →

return ∃ tp ∈ s · IsOverlapping (tp, t),others → return false

end;

The body of the function is a cases expression with each of its branches covering oneof the following type categories:

Basic types are overlapping if both of them are numeric types. For example, the set ofinteger numbers is a subset of the set of real numbers. (BasicTypeRep).

Set types are overlapping if the types of their elements are overlapping (SetTypeRep).

Sequence types are overlapping if the element types of the sequences are overlapping(SeqTypeRep).

Product types must have the same number of element types (the same length) and eachelement type of the tuple must overlap with the corresponding element type of theother tuple (ProductTypeRep).

Union types are the most interesting, because they cause decidability difficulties intype checking. Two union types are represented by a set of types and are over-lapping if there exist one element type which is overlapping with the second typet (UnionTypRep). In the description of the definite compatibility below, it can beseen that here is a difference between possible and definite type compatibility.

Further explanations can be found in [90].

Page 31: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

2.3. THE PRESENT STATIC SEMANTICS OF THE VDM-SL TOOLBOX 19

Definite Compatibility

In definite mode all values denoted by an actual type must be compatible with an expectedtype. Therefore, the algorithm has to check that the set of values denoted by the actualtype is a subset of the set of values denoted by the expected type. In short, the actualtype must be a subtype of the expected type. In Figure 2.2 this relation is shown as Abeing a subtype of B . For example, every numeric type is a subtype of the type realdenoting the real numbers.

In the previous expression x + 1, where x is of type nat | bool the subtype relationdoes not hold, because of the Boolean type which is not part of the expected real type.Although the expression is possible type consistent the type checker cannot accept itas definitely consistent. This is an undecidable case, where the user has to justify theconsistency by using the context.

The structure of the subtype operation is similar to IsOverlapping:

IsSubType : TypeRep × TypeRep o→ BIsSubType (TpR1,TpR2) 4

cases mk- (TpR1,TpR2):mk- (tp, tp) →

return true,mk- (mk-BasicTypeRep (BTp1), mk-BasicTypeRep (BTp2)) →

cases mk- (BTp1,BTp2):mk- (-, REAL),mk- (-, RAT) →

let AllowedNumTypes = {NATONE, NAT, INTEGER, RAT} in

return BTp1 ∈ AllowedNumTypes,mk- (-, INTEGER) →

let AllowedNumTypes = {NATONE, NAT} in

return BTp1 ∈ AllowedNumTypes,mk- (-, NAT) →

return BTp1 = NATONE,others → return false

end,mk- (mk-SetTypeRep (STp1), mk-SetTypeRep (STp2)) →

return IsSubType (STp1,STp2),mk- (mk-SeqTypeRep (STp1), mk-SeqTypeRep (STp2)) →

return IsSubType (STp1,STp2),mk- (mk-ProductTypeRep (PTp1), mk-ProductTypeRep (PTp2)) →

if len PTp1 = len PTp2then return ∀ i ∈ inds PTp1 ·

IsSubType (PTp1 (i),PTp2 (i))else return false ,

Page 32: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

20 CHAPTER 2. WHY PROOF OBLIGATIONS?

mk- (mk-UnionTypeRep (Lhs), -) →return ∀ tp ∈ Lhs ·

IsSubType (tp,TpR2, assump),mk- (-, mk-UnionTypeRep (Rhs)) →

return ∃ tp ∈ Rhs · IsSubType (TpR1, tp, assump),others → return false

end

The first type argument is checked to be a subtype of the second.

Basic types are now explicitly checked for the subtype relation. All numeric types denotesubsets of the reals type, following the order of numeric types. The expected typedefines the different cases. The first pattern in the branches of the cases expression(“-”) is a “don‘t care” pattern which here represents any basic type.

Set types are treated as in possible mode by checking their element types recursively.

Sequence types are treated as in possible mode by checking the types of the sequenceelements.

Product types are treated in the same way as in possible mode.

Union types However, the union type check is different. Two cases are distinguished,because of the non-commutativity of the subtype relation.

1. The actual type is a union type. For all element types of the union type itis checked, whether they are subtypes of the expected type or not. Note thatwhen checking for overlapping types just one type has to fulfill the overlappingcriteria, here every type in the set must be a subtype of the second.

2. The expected type is a union type. There must exist one type in the set oftypes of the union type such that the subtype relation holds.

Note that the two algorithms are simplified and reduced. To illustrate the principles wehave selected a subset of types for which the compatibility check is shown. For instance,the specifications above do not cover invariants, composites, functions, maps, and typenames. However, in the full specification all types are covered.

2.4 The New Approach — Proof Obligations

As we have already shown, the type check for VDM-SL is incomplete, because of the un-decidability. In Figure 2.1 the white area indicates the specifications not covered . Theirconsistency check is left to the user. We know these specifications are possibly, but notdefinitely, consistent. The error messages produced by the definite type checker are usedby the user to check these points in the specification that caused the difficulties.

In our approach the central idea (proposed in [29, 30]) is to obtain decidability of typechecking by generating proof obligations for the “difficult” parts causing the undecidability.

Page 33: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

2.4. THE NEW APPROACH — PROOF OBLIGATIONS 21

It is the task of this thesis to specify such a proof obligation generator for type con-sistency. Proof obligations (PO) should replace the error messages, raised by the definitetype checker.

A proof obligation for type consistency is an unproven theorem that must be proved inorder to ensure type consistency. Therefore, the present definite type checker becomes aconditional type checker which returns true under the assumption that the POs generatedduring the type check can be proved. This process is called conditional type checking.

To be able to prove POs, they contain context information. The general form of aproof obligation is that of a proof rule, where the assumptions are generated out of thecontext and the conclusion is the property that must hold. In the literature this is writtenlike3:

context informationpredicate

From another point of view we can see the conditional type checking as an automaticproof of type consistency where the difficult parts are left to the user by generating sideconditions (here POs).

The most natural application of the approach of generating proof obligations is informal verification of type consistency. Therefore, the POs are designated to be directlyimported into the proof tool for the IFAD VDM-SL Toolbox that is under development inthe TIAPS project (Chapter 1).

However, POs may also be used as pointers to dangerous places in a specification, likethe currently used error messages. But POs provide more information about the reasonfor difficulties and so they are an improvement, although the possibility of proof is notused.

In Chapter 3 the role of the proof obligation generator is shown, proof obligations areformally defined, and this approach is illustrated by a guided tour of the generation ofproof obligations using an example inspired by industry.

3Sometimes the equivalent form using a turnstile can be found: context information ` predicate.

Page 34: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

22 CHAPTER 2. WHY PROOF OBLIGATIONS?

Page 35: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Chapter 3

Generating Proof Obligations

This chapter explains and illustrates the approach of generating proof obligations. We startby giving an overview of the proof obligation generator and the interaction with the outsideworld. Then, proof obligations are formally defined and the concept of context generationis explained. To understand the approach the chapter provides a guided tour through aspecification and the process of generating proof obligations for the specification. For thisguided tour a specification of a trusted gateway, an example inspired from an industrialproject, has been chosen. This VDM-SL specification is investigated according to itsundecidable parts and the properties that must hold to ensure the definite consistency.Furthermore, the proof obligations for the example specification are given. Finally, aproof of one of the proof obligations is stepwise constructed in order to show the readerunfamiliar with formal methods how proofs are made.

3.1 The Proof Obligation Generator

The existing type checker specification document was extended by one extra module andthe total size increased to approximately 300 pages. Naturally, the test cases and the testenvironment were also adapted to take these changes into account.

The central idea underlying the approach presented here (proposed in [29, 30]) is toextend type checking by generating proof obligations for the “difficult” parts which causethe undecidability. In this section we will describe how the existing type checker has beenextended and modified to perform this task. The proof obligations (PO) should replacethe error messages, raised by the definite type checker.

Figure 3.1 provides an overview of the data flow to and from the type checker. AVDM-SL specification is syntax checked by the parser, which produces an abstract syntaxtree of the specification. The abstract syntax tree is the input for the type checker (staticsemantics). If type checking in possible mode fails, a list of error messages is generated.In definite mode the type checker becomes the proof obligation generator. These proofobligations can be inspected through the graphical user interface (GUI) and/or they canbe loaded into the proof tool.

The main advantage of this approach is the combination of a type checker and a proof

23

Page 36: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

24 CHAPTER 3. GENERATING PROOF OBLIGATIONS

abstract proof obligations

errors,warnings

proofobligations

parser

errors, warnings

syntax tree

typechecker

prooftool

GUI

Figure 3.1: Interaction of the new type checker.

tool. In the cases where the type checker is not able to check the consistency, the prooftheory in the proof tool can be applied to prove the consistency. The link between thetwo components are the proof obligations generated. Minor simplifications and proofsof trivial proof obligations could be made directly by the POG. However, in the presentapproach the decision has been made to forward these tasks to the proof tool, which isdesigned for these purposes.

3.1.1 Proof Obligations

A proof obligation for type consistency is a statement that must be proved in order toensure type consistency. Therefore, the POG is a conditional type checker which returnstrue under the assumption that the POs generated during the type check can be proved.This process is called conditional type checking. In order to be able to prove POs, theycontain context information. The general form of a proof obligation is that of a proof rule,where the assumptions are generated out of the context and the conclusion is the propertythat must hold. Thus, the general form of a PO is

context informationpredicate

In the examples below, the proof obligations will be given in an ASCII representationwhich is:

PO: context information ==> predicate

Page 37: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

3.1. THE PROOF OBLIGATION GENERATOR 25

A proof obligation is modeled as a proof (inference) rule consisting of a list of hypothesesand a conclusion. The rule states that the conclusion holds whenever the hypotheses hold[10, 24]. The abstract syntax for a proof rule is:

PrfRule : : hyp : Sequent∗

con : AllExpr ;

To be compatible with the proof theory a hypothesis is defined as a sequent P ` R.Its meaning is that the local conclusion R is derivable from the local assumptions Pin a subproof. Formally, a sequent is composed of local variables, a sequence of localassumptions, and a local conclusion:

Sequent : : vars : Name∗

lhyp : AllExpr∗

lcon : AllExpr ;

However, it turned out that for formulating the proof obligations the use of localassumptions is not needed. Therefore, the hypotheses are sequents without local assump-tions (` R). In the following, we skip the turnstile in the hypotheses, when we present aproof obligation.

AllExpr is a syntactic extension of VDM-SL expressions with type judgements (e.g.,3 : N). This extension is necessary to reason over types.

AllExpr = Expr | TypeJudgement ;

TypeJudgement : : expr : Exprtype : TypeRep

3.1.2 Context Generation

Context information forms the hypothesis of a proof obligation. Therefore, the existingspecification of the type checker has been extended in order to generate the context. Thecontext of a certain location in a specification is the conjunction of logical conditionsthat must hold in order to reach this location during evaluation. The following exampleillustrates the notion of context:

if is-nat(x) then x + 1 else 1

To reach x + 1 during the evaluation, the condition is-nat(x) must be true. Therefore,the context of x + 1 is is-nat(x). Obviously, the context of 1 in the else branch is notis-nat(x).

For generating proof obligations we distinguish two kinds of context:

Type judgements of the form identifier :Type are used to record membership of a type.This may be read as “identifier is of type Type”. They are provided as contextinformation to infer over types in the typed logic of partial functions and to providethe proof tool with the needed type information. The type information is stored inthe environment of the type checker.

Page 38: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

26 CHAPTER 3. GENERATING PROOF OBLIGATIONS

MessagesHigh

LowGatewayTrusted

Figure 3.2: A trusted gateway.

Boolean expressions like is-nat(x) in our example above are stored in a context stack,while performing the consistency check. When checking the then-branch of an if-expression the test expression (above: is-nat(x)) is pushed onto the stack. Check-ing the else branch, we first remove the test expression from the stack (pop), thenthe negated test expression (above: not is-nat(x)) is pushed onto the stack.

3.2 A Guided Tour

In this section we make a guided tour through the specification of a trusted gatewayand investigate it according to its undecidable parts and the properties that must holdto ensure the definite consistency. Furthermore, the predicate expressions which can beused as context information are pointed out. The synthesis of the proof obligations isstraightforward from analysing the two major items in the PO generation process, theconsistency properties and the context. However, first the example has to be specified.

3.2.1 A Trusted Gateway

A major requirement on a secure system is that of preventing accidental disclosure ofclassified or sensitive information to third parties. When two systems are connected, theinformation flow between them must be controlled and information in certain categoriesprevented from being transferred. A trusted gateway1 is a device designed to perform thistask.

The trusted gateway works on streams of messages. The gateway has a single inputport and two output ports. The input port is connected to another high-security systemwhich provides a stream of incoming messages. One output port is connected to a high-security system, while the other output port is connected to a low-security system (Fig.3.2).

Each incoming message is read from the input port and loaded into a block of internalmemory. There the message’s content (a string of characters) is analyzed to see if anyspecial strings are present. Special strings are stored in two internal collections called”categories”. There is a “high-classification” category and a low-classification “category”.If the message contains low-classification strings, but no high-classification strings, then it

1This example has been provided by John Fitzgerald, email: [email protected].

Page 39: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

3.2. A GUIDED TOUR 27

is output through the low-security output port. Otherwise, the message is output to thehigh-security output port.

3.2.2 The Gateway Specification

Types

The gateway receives and delivers messages. A message is defined as a non-empty stringof a certain maximal length:

types

Message = Stringinv m == len m >= 1 and len m <= 100;

A string is a sequence of characters. Formally:

String = seq of char;

Categories are used to define the security-level of an message. A category is a collectionof strings to be searched for in incoming messages and can be modelled as a set of strings.The requirement for a category should be that there is a minimum number of one stringand maximum number of 20 strings in it. Furthermore, the strings must not be longerthan 15 characters:

Category = set of Stringinv c ==

card c <= 20 and card c >= 1 andforall str in set c & len str <= 15;

The last type to define the gateway is a port which is modelled as a sequence of messages:

Port = seq of Message

Auxilliary Functions

For the trusted gateway a function to determine the security classification (high or low)of a given string is needed. The function takes string, and the high and low securitycategories as arguments and checks the argument string for the presence of key characterstrings in the two categories. If a string in both categories is present or no string fromeither category is present, the message shall be written to the high-security output port.Formally:

functions

classification: String * Category * Category -> (<HIGH> | <LOW>)classification(s,high,low) ==

if contains_category(s,high)

Page 40: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

28 CHAPTER 3. GENERATING PROOF OBLIGATIONS

then <HIGH>elseif contains_category(s,low)then <LOW>else <HIGH>;

The function uses contains category, which returns true if and only if a string containsa substring which is present in the category:

contains_category: String * Category -> boolcontains_category(s,c) ==exists sub in set c & isSubstring(sub,s);

The auxilliary function isSubstring returns true if and only if the first argument is asubstring of the second, which we formulate as:

isSubstring: String * String -> boolisSubstring(s1,s2) ==exists i,j in set inds s2 & [ s2(n) | n in set {i,...,j}] = s1;

The sequence is modelled as a sequence comprehension with the elements of s2 betweenthe indices i and j. Instead of the comprehension we could simply write s2(i,...,j).However, the chosen more complicated form serves later as a good example for context gen-eration. The bold letters above and in the following specifications are points of referencesfor the discussion in the next section.

The Gateway

The gateway is composed out of an input port and two output ports, the high- and thelow-security categories and a block. The block serves as a buffer to analyze the incomingmessages. The security requires that all the messages at the high security output portare indeed high-classification messages with respect to the two categories and that allthe messages at the low security output port are indeed low-classification messages withrespect to the two categories:

typesGateway:: input: Port

highOutput: PortlowOutput: Porthigh: Categorylow: Categoryblock: seq of char

inv g == (forall msg in set elems g.highOutput &classification(msg,g.high,g.low) = <HIGH>) and

(forall msg in set elems g.lowOutput &classification(msg,g.high,g.low) = <LOW>) and

g.high inter g.low = {}

Page 41: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

3.2. A GUIDED TOUR 29

Functionality

The following functions define the functionality of the trusted gateway: Load takes themessage off the head of the input port and moves it into the block. To ensure that messagesare processed one at a time, the function should have a pre-condition which says that theblock is empty:

Load: Gateway -> GatewayLoad(g) ==

mk_Gateway( tl g.input,g.highOutput,g.lowOutput,g.high,g.low,hd g.input)

pre g.input <> [];

Analyse reads the message in the block and writes it out to the tail end of the appropriateport. If in the block is a high-classification message, then it should be appended to thehigh security output port. Otherwise it should be appended to the low-security outputport:

Analyse: Gateway -> GatewayAnalyse(g) ==

if classification(g.block,g.high,g.low) = <HIGH>then mk_Gateway(g.input,

g.highOutput ^ [g.block],g.lowOutput,g.high,g.low,g.block)

else mk_Gateway(g.input,g.highOutput,g.lowOutput ^ [g.block],g.high,g.low,g.block);

Purge empties the block. The function is specified in an implicit style using a post condi-tion. The input and output is of type gateway. In general a post condition of an implicitfunction is a predicate that must hold for the output of a function. Here, the post con-dition states that the output gateway should be the input gateway with an empty block(i.e. the block field should be the empty sequence):

Purge(g:Gateway) r:Gatewaypost r = mk_Gateway(g.input,

g.highOutput,g.lowOutput,g.high,g.low,[])

Page 42: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

30 CHAPTER 3. GENERATING PROOF OBLIGATIONS

3.2.3 The Synthesis of Proof Obligations

The presented trusted gateway specification is syntax checked and possibly consistent.However, the definite consistency cannot be determined automatically, because of thefollowing constructs, which introduce the undecidability:

• the partial operator hd

• the partial operator tl

• subtypes defined by invariants

• a sequence application s(n)

• an implicit function

The “difficult parts” are printed bold in the specification above.

The Partial Operators Head and Tail

Partial operators are operators, which are not defined over the whole domain of theiroperands. For example the operators hd and tl, used in the function Load, are not definedfor empty sequences. hd s is the first element of a sequence s. tl s is the sequence swith its head removed. In general it is impossible to check statically if the sequence isempty, therefore these operators, like all partial operators, introduce undecidability intype checking. In our approach the property, that s is unequal to the empty sequencemust be proved (s <> []). Consequently, the head and tail operators in function Loadraise two equal proof obligations:

PO:[| g : Gateway;

g.input <> [] |]==>g.input <> []

The pre-condition in Load is taken as context information. Also the type of g is provided.One may read the proof obligation as follows: “Assuming g is of type Gateway and g.input<> [] one can infer g.input <> [].” This statement is trivially true, because one of theassumptions is equal to the conclusion. Notice that the absence of the pre-condition wouldmake the proof obligation unprovable, because the single assumption of type g is to weakfor inferring the conclusion. Therefore, to be consistent and to be able to prove the proofobligation, the pre-condition must be present.

Sequence Application

A component of a sequence s can be accessed by a sequence application of the form s(n),where n must be a positive integer within the index range of the sequence s. The problemfor static type checking is that it cannot be guaranteed that n is a valid index, without

Page 43: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

3.2. A GUIDED TOUR 31

evaluation. This is well known from traditional programming languages, where the accessto an array by its indices raises the equivalent problem. Thus, the second kind of propertyto be proved is: n in set inds s.

In the trusted gateway the function isSubstring contains a sequence application ina sequence comprehension expression. It also serves as a good example for demonstratingthe context generation. The sequence application in the auxiliary function isSubstringgenerates the proof obligation:

PO:[| i : nat1;

j : nat1;n : nat1;s2 : String;i in set inds s2;j in set inds s2;n in set {i, ..., j} |]

==>n in set inds s2

In the exists quantifier expression, i and j are bound to an element of the set of indices ofsequence s2, which is taken as context information in the “such that” part. The sequencecomprehension expression defines a sequence consisting of those elements of s2, that aredefined by the binding of n. This binding is also taken as a context. Finally, the types ofall identifiers become part of the assumptions.

Invariants

It is possible to restrict the values in a type by means of an invariant. The result is asubtype, which means that the type is restricted to a subset of its original values. In ourexample the type Gateway is defined using an invariant to express the restriction that allmessages of high priority should be sent over port g.highOutput and all messages of lowpriority should be sent over port g.lowOutput. Additionally, the two sets of keywordsdefining the categories must be disjoint.

If an invariant is defined, a new (total) function is implicitly created. This invariantfunction takes as its argument an expression of the unrestricted type and returns true ifthe invariant holds, otherwise false. The signature of the gateway invariant function is:

Gateway0 +> bool

The postfix 0 denotes the unrestricted (super)type. However, in the IFAD Toolbox thisname style is not used, which leads to some confusion which version of a type is meant.

In definite type checking it must be ensured that invariants are satisfied. By definitionthis is not possible by static type checking, because it would be necessary to evaluate theinvariant function. Therefore, the third kind of property which must be proved is theevaluation of invariant functions to true: inv-Type( expression)

Page 44: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

32 CHAPTER 3. GENERATING PROOF OBLIGATIONS

For all functions yielding a result of the invariant type Gateway, a proof obligationhas to be generated. The proof obligation for Load stating that the invariant function ofGateway holds for the function body of Load is:

PO:[| g : Gateway;

g.input <> [] |]==>inv_Gateway(mk_Gateway(tl g.input,

g.highOutput,g.lowOutput,g.high, g.low,hd g.input))

Here the previously mentioned type confusion might occur and one may ask why theinvariant function of Gateway is applied to a value of type Gateway. The explanation isthat the make constructor mk yields the unrestricted type (Gateway0).

The invariant proof obligation for the function Analyse is

PO:[| g : Gateway |]==>inv_Gateway(if classification(g.block, g.high, g.low) = <HIGH>

then mk_Gateway(g.input,g.highOutput ^ [g.block],g.lowOutput,g.high,g.low,g.block)

else mk_Gateway(g.input,g.highOutput,g.lowOutput ^ [g.block],g.high,g.low,g.block))

Implicit Functions

The function purge is defined as an implicit function by means of a post-condition. A post-condition is a truth valued expression which specifies what must hold after the functionis evaluated. A post condition can refer to the result identifier and the parameter values.Usually, an implicit function also contains a pre-condition, which specifies what must holdbefore the function is evaluated.

For an implicit function definition to be consistent, there must exist a return valuesatisfying the post-condition. This property is called the satisfiability of implicit func-

Page 45: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

3.3. THE SATISFIABILITY PROOF 33

tions. The general form is exists result: Type & post-f(...). The satisfiabilityproof obligation for the implicit function purge is

PO:[| g : Gateway |]==>exists r: Gateway &r = mk_Gateway(g.input, g.highOutput, g.lowOutput,

g.high, g.low, [])

As an example the proof of this proof obligation is developed in the next section.

3.3 The Satisfiability Proof

Now the reader should be familiar with the concept of proof obligations for the consistencyof a specification. However, the central term “proof” has not been treated so far and mightbe fairly unclear, depending on the prerequisites of the reader. Therefore, at the end ofthis chapter the proof of the satisfiability proof obligation in Subsection 3.2.3 is presented.The proof is formally developed in a natural deduction style (NDS) using the notationand proof rules (inference rules) given in [10]. The proof is developed step by step andproof rules are presented as they are needed.

In NDS the satisfiability proof obligation of the trusted gateway written as a theoremlooks like:

from g : Gateway...

infer ∃ r : Gateway · r = mk -Gateway(g .input , g .highOutput , g .lowOutput , g .high, g .low , [])

The dots indicate where the missing parts of the proof has to be inserted. The typeGateway is an invariant type. To get rid of the confusion between the unrestricted typeand the subtype we translate the invariant type to the subtype notation used in [10]:A subtype of A inhabited by only those elements satisfying a predicate P is written¿ x : A | P(x ) À. Gateway0 is the unrestricted type, with a restriction predicate, whichis in this case the invariant function inv -Gateway .Therefore, our rewritten theorem is:

from g : ¿ x : Gateway0 | inv -Gateway(x ) À...

infer ∃ r : ¿ x : Gateway0 | inv -Gateway(x ) À ·r = mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , [])

In the following proof steps only the new added and backwards justified lines are shown.The line numbers keep the same throughout the proof.

3.3.1 Step One

In the first step of the proof three proof rules are applied. Two proof rules are applied byforward reasoning and one by backwards reasoning, one in backwards reasoning:

Page 46: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

34 CHAPTER 3. GENERATING PROOF OBLIGATIONS

The first rule returns a value of a subtype to its supertype:

supertypea: ¿ x : A | P(x ) À

a : AAx

The elimination axiom allows the instantiation of the predicate of the subtype on anyvalue of the subtype:

subtype-Ea: ¿ x : A | P(x ) À

P(a)Ax

To get rid of the existential quantifier in the conclusion, the exists introduction rule isused in backwards reasoning. The rule states that if a predicate P is known to be true atsome value a of some type A, then one may conclude that there does indeed exist a valueof type A such that P holds. The axiom is

∃ -Ia : A;P(a)∃ r : A · P(r)

Ax

from g : ¿ x : Gateway0 | inv -Gateway(x ) À1 g: Gateway0 supertype (h1)2 inv -Gateway(g) subtype-E (h1)

...19 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []):

¿ x : Gateway0 | inv -Gateway(x ) À (justify ?)20 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) =

mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) (justify ?)infer ∃ r : ¿ x : Gateway0 | inv -Gateway(x ) À ·

r = mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) ∃ -I (19,20)

Each new line contains a reference number, an expression representing the assertion thatthe line purports to establish, and the rule name with the lines to which it has been appliedto justify the assertion. The non-justified lines added in backwards reasoning are markedby “(justify ?)”.

3.3.2 Step Two

In step 2 the axioms defined by the composite type Gateway0 are used. The neededformation rules for the named selector functions (selectors) are derived from the gatewayspecification:

import-formg : Gateway0

g .import : PortAx

highOutput-formg : Gateway0

g .highOutput : PortAx

lowOutput-formg : Gateway0

g .lowOutput : PortAx

Page 47: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

3.3. THE SATISFIABILITY PROOF 35

high-formg : Gateway0

g .high : CategoryAx

low -formg : Gateway0

g .low : CategoryAx

Using the simple rule that equality is reflexive in backwards reasoning we get rid of theequality expression.

=-self-Ia : Aa = a

Ax

The subtype introduction axiom asserts that a value of the supertype satisfying the pred-icate inhabits the subtype:

subtype-Ia : A;P(a)

a: ¿ x : A | P(x ) À Ax

from g : ¿ x : Gateway0 | inv -Gateway(x ) À:3 g .import : Port import-form (1)4 g .highOutput : Port highOutput-form (1)5 g .lowOutput : Port lowOutput-form (1)6 g .high : Category high-form (1)7 g .low : Category low -form (1)

...17 inv -Gateway(mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) (justify ?)18 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) : Gateway0 (justify ?)19 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []):

¿ x : Gateway0 | inv -Gateway(x ) À subtype-I (17,18)20 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) =

mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) =-self-I(19)infer ∃ r : ¿ x : Gateway0 | inv -Gateway(x ) À ·

r = mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) ∃ -I (19,20)

3.3.3 Step Three

In step 3 the formation rule for the constructor of Gateway0 is applied:

mk -Gateway0-forms1, s2, s3 : Port ; s4, s5 : Category ; s6 : char∗

mk -Gateway0(s1, s2, s3, s4, s5, s6) : Gateway0Ax

Page 48: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

36 CHAPTER 3. GENERATING PROOF OBLIGATIONS

from g : ¿ x : Gateway0 | inv -Gateway(x ) À:7 g .low : Category low -form (1)

...16 [] : char∗ (justify ?)17 inv -Gateway(mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) (justify ?)18 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) : Gateway0

mk-Gateway0-form (3,4,5,6,7,16):infer ∃ r : ¿ x : Gateway0 | inv -Gateway(x ) À ·

r = mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) ∃ -I (19,20)

3.3.4 Step Four

In step 4, first, the type of the empty sequence is justified by the formation rule of emptysequences. The empty sequence is polymorphic and therefore of any sequence type A∗.

[]-form[] : A∗ Ax

Then, in backwards reasoning the invariant function of Gateway is folded, which is a purerewriting. Notice that folding in backwards reasoning is equivalent to unfolding a function:

from g : ¿ x : Gateway0 | inv -Gateway(x ) À:7 g .low : Category low -form (1)

...15 (∀msg ∈ elems

mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).highOutput ·classification(msg ,mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).high,mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).low) =< HIGH >)∧(∀msg ∈ elemsmk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).lowOutput ·classification(msg ,mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).high,mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).low) =< LOW >)∧mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).high∩mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).low =

(justify ?)16 [] : char∗ []-form17 inv -Gateway(mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , [])

fold inv-Gateway (15):infer ∃ r : ¿ x : Gateway0 | inv -Gateway(x ) À ·

r = mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) ∃ -I (19,20)

Page 49: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

3.3. THE SATISFIABILITY PROOF 37

3.3.5 Step Five

In step 5 four times the substitution rule is applied backwards. The rule permits sub-stitution of the expression on the left of an equality by the expression on the right in apredicate P :

=-subs-right(a)a : A; a = b;P(a)

P(b)Ax

from g : ¿ x : Gateway0 | inv -Gateway(x ) À:7 g .low : Category low -form (1)

...10 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).highOutput =

g .highOutput (justify ?)11 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).high =

g .high (justify ?)12 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).low =

g .low (justify ?)13 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).lowOutput =

g .lowOutput (justify ?)14 (∀msg ∈ elems highOutput · classification(msg , g .high,

g .low) =< HIGH >)∧(∀msg ∈ elems g .lowOutput · classification(msg , g .high,g .low) =< LOW >)∧g .high ∩ g .low = {} (justify ?)

15 (∀msg ∈ elemsmk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).highOutput ·classification(msg ,mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).high,mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).low) =< HIGH >)∧(∀msg ∈ elemsmk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).lowOutput ·classification(msg ,mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).high,mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).low) =< LOW >)∧mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).high∩mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).low =

=-subs-right(g.highOutput) (4,10,14),=-subs-right(g.high) (6,11,14),

=-subs-right(g.lowOutput)(5,12,14),=-subs-right(g.low)(7,13,14)

:infer ∃ r : ¿ x : Gateway0 | inv -Gateway(x ) À ·

r = mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) ∃ -I (19,20)

Page 50: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

38 CHAPTER 3. GENERATING PROOF OBLIGATIONS

3.3.6 The Complete Proof

The proof is completed by unfolding the invariant function for g and by applying theaxioms of the selector functions, which extract the relevant components of a Gateway0:

highOutput-defn0

mk -Gateway0(s1, s2, s3, s4, s5, s6) : Gateway0mk -Gateway0(s1, s2, s3, s4, s5, s6).highOutput = s2

Ax

lowOutput-defn0

mk -Gateway0(s1, s2, s3, s4, s5, s6) : Gateway0mk -Gateway0(s1, s2, s3, s4, s5, s6).lowOutput = s3

Ax

high-defn0

mk -Gateway0(s1, s2, s3, s4, s5, s6) : Gateway0mk -Gateway0(s1, s2, s3, s4, s5, s6).high = s4

Ax

low -defn0

mk -Gateway0(s1, s2, s3, s4, s5, s6) : Gateway0mk -Gateway0(s1, s2, s3, s4, s5, s6).low = s5

Ax

To justify these rules, the type of the constructor must be justified again, due to the factthat in a NDS proof the rules must always refer to previous lines.

Page 51: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

3.3. THE SATISFIABILITY PROOF 39

from g : ¿ x : Gateway0 | inv -Gateway(x ) À1 g: Gateway0 supertype (h1)2 inv -Gateway(g) subtype-E (h1)3 g .import : Port import-form (1)4 g .highOutput : Port highOutput-form (1)5 g .lowOutput : Port lowOutput-form (1)6 g .high : Category high-form (1)7 g .low : Category low -form (1)8 [] : char∗ []-form9 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) : Gateway0

mk-Gateway0-form (3,4,5,6,7,8)10 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).highOutput =

g .highOutput highOutput-defn0 (9)11 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).high =

g .high high-defn0 (9)12 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).low =

g .low low -defn0 (9)13 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).lowOutput =

g .lowOutput lowOutput-defn0 (9)14 (∀msg ∈ elems highOutput · classification(msg , g .high,

g .low) =< HIGH >)∧(∀msg ∈ elems g .lowOutput · classification(msg , g .high,g .low) =< LOW >)∧g .high ∩ g .low = {} unfold inv-Gateway (2)

15 (∀msg ∈ elemsmk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).highOutput ·classification(msg ,mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).high,mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).low) =< HIGH >)∧(∀msg ∈ elemsmk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).lowOutput ·classification(msg ,mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).high,mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).low) =< LOW >)∧mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).high∩mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []).low =

=-subs-right(g.highOutput) (4,10,14),=-subs-right(g.high) (6,11,14),

=-subs-right(g.lowOutput)(5,12,14),=-subs-right(g.low)(7,13,14)

16 [] : char∗ []-form17 inv -Gateway(mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , [])

fold inv-Gateway (15)18 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) : Gateway0

mk-Gateway0-form (3,4,5,6,7,16)19 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []):

¿ x : Gateway0 | inv -Gateway(x ) À subtype-I (17,18)20 mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) =

mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) =-self-I(19)infer ∃ r : ¿ x : Gateway0 | inv -Gateway(x ) À ·

r = mk -Gateway0(g .input , g .highOutput , g .lowOutput , g .high, g .low , []) ∃ -I (19,20)

Page 52: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

40 CHAPTER 3. GENERATING PROOF OBLIGATIONS

Page 53: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Chapter 4

Consistent Expressions

In this chapter we focus on the consistency of VDM-SL expressions. In the in the previouschapter, the general idea of generating proof obligations has been introduced. Here, partsof the formal specification of the proof obligation generator (POG) are presented. First weexplain how the existing type checker (static semantics) specification has been extended inorder to generate POs for definite type checking. Then, we concentrate on proof obligationsfor expressions. Type checking VDM-SL expressions, two categories of consistency checkscan be distinguished: (1) Type compatibility and (2) domain checking, which checkswhether functions and operators are applied to their defined domains. Both may beundecidable. The first because of union and subtypes, the second because of partialoperators and functions with pre-conditions. In the section about domain checking anoverview of the partial operators and their resulting POs is given. We also present theformal approach for ensuring consistent implicit functions.

4.1 From Type Checking to Proof Obligations

In the previous chapter different kinds of proof obligations have been illustrated usingthe trusted gateway example. Now the extension of the existing type checker to generatethese POs is illustrated. Therefore first, the specification of the existing type checker isexplained. A binary expression with the partial division operator serves as the demon-strating part of the specification. Then, the extended specification of the well-formednesscheck for this expression is given.

4.1.1 Well-formedness of Expressions

According to the strategy of rejection and acceptance explained in Chapter 2, the staticsemantics defines two kinds of predicates in order to check whether an expression is well-formed. These predicates denote the possible and definite well-formedness of an expression[29, 7].

If the existing type checker of the IFAD VDM-SL Toolbox performs possible typechecking (POS mode) an expression is rejected if it is not possibly well-formed. In definite

41

Page 54: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

42 CHAPTER 4. CONSISTENT EXPRESSIONS

mode (DEF) the type checker only accepts expressions if they are definitely well-formed,which means that an error message is raised if the definite well-formedness cannot bestatically checked. As an example the specification of the well-formedness predicate for adivision expression is given below:

wf -NUMDIV : (POS | DEF)× BinaryExpr o→ B× TypeRep

wf -NUMDIV (i , mk-BinaryExpr (lhs, -, rhs)) 4let mk- (wf -lhs, lhstype) = wf -Expr (i , lhs),

mk- (wf -rhs, rhstype) = wf -Expr (i , rhs),ExpectedLhsAndRhsType = mk-BasicTypeRep (REAL) in

let lhscomp = IsCompatible (i , lhstype,ExpectedLhsAndRhsType),rhscomp = IsCompatible (i , rhstype,ExpectedLhsAndRhsType) in

(if ¬ lhscompthen GenErr("Lhs of ′/′ is not a numeric type") ;if ¬ rhscompthen GenErr("Rhs of ′/′ is not a numeric type")elseif i = DEF ∧ rhstype 6= mk-BasicTypeRep (NATONE)then (GenErr("Rhs of ′/′ must be non zero") ;

return mk- (false,ExpectedLhsAndRhsType) );return mk- (wf -lhs ∧ wf -rhs ∧ lhscomp ∧ rhscomp,

ExpectedLhsAndRhsType) )

The choice of possible and definite well-formedness is conveyed to the well-formednessoperation via the first parameter i . The second parameter is the expression to be checked,which in this case is a binary expression with the binary operator ‘/’. The signature showsthat in addition to the well-formedness of subexpressions, the type of the expression isreturned. Analysing the body, four parts can be distinguished: (1) The well-formednessand the types of the left- and right-hand side (lhs and rhs) are determined. (2) The checkwhether the left- and right-hand side are compatible to the expected type. IsCompatible isthe compatibility check introduced in Chapter 2. (3) Error Messages are raised. Note theadditional error message in definite mode: To be accepted, rhs must be of type N1, whichdenotes the natural numbers excluding zero. This type is needed for static acceptance,because no other basic numeric type in VDM-SL excludes zero. (4) The well-formednessand type of the division expression are returned. It is the goal of this work to generate proofobligations instead of error messages in definite mode. In the following this modificationof the type checker is explained.

4.1.2 Extended Well-formedness

Here the extension of the existing type checker to generate the POs is illustrated. Again,the well-formedness operation of a division expression serves as the demonstrating part ofthe specification. To see the modifications compare the following with the specificationabove:

Page 55: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

4.2. TYPE COMPATIBILITY 43

wf -NUMDIV -POG : (POS | DEF)× BinaryExpr o→ B× TypeRep

wf -NUMDIV -POG (i , mk-BinaryExpr (lhs, -, rhs)) 4let mk- (wf -lhs, lhstype) = wf -Expr (i , lhs),

mk- (wf -rhs, rhstype) = wf -Expr (i , rhs),ExpectedLhsAndRhsType = mk-BasicTypeRep (REAL) in

let lhscomp = IsCompatible (i , lhstype,ExpectedLhsAndRhsType),rhscomp = IsCompatible (i , rhstype,ExpectedLhsAndRhsType) in

(if ¬ lhscompthen if i = DEF

then GenPO(mk-TypeJudgement (lhs,ExpectedLhsAndRhsType))else GenErr("Lhs of ′/′ is not a numeric type") ;

if ¬ rhscompthen if i = DEF

then GenPO(mk-TypeJudgement (rhs,ExpectedLhsAndRhsType))else GenErr("Rhs of ′/′ is not a numeric type") ;

if i = DEF ∧ rhstype 6= mk-REP ‘BasicTypeRep (NATONE)then GenPO(mk-BinaryExpr (rhs, NE, mk-RealLit (0))) ;if i = DEFthen return mk- (wf -lhs ∧ wf -rhs,ExpectedLhsAndRhsType)else return mk- (wf -lhs ∧ wf -rhs ∧ lhscomp ∧ rhscomp,

ExpectedLhsAndRhsType) )

The main difference compared to the previous specification is the generation of proofobligations in DEF mode, instead of error messages: If the compatibility check is notsuccessful a PO is generated (GenPO) stating that the expression (rhs or lhs) is of theexpected type. This is done using a type judgement. For domain checking a PO statingthat the right-hand side is not equal (NE) to zero is generated. In definite mode only thewell-formedness of the left- and right-hand side is returned, because the compatibility andthe domain constraint are assumed to be true. This assumption is verified later using theproof tool by proving the generated proof obligations. The operation GenPO takes theconclusion of the PO as an argument. During type checking the context is collected fromthe abstract syntax tree and is separately stored and updated in a context stack. Thiscontext together with the conclusion argument is used by GenPO to synthesise a proofobligation. Note that even in definite inconsistent cases (unprovable) proof obligations aregenerated. The reason is that assumption has been made that specifications are possibletype checked first to catch the definite inconsistencies.

4.2 Type Compatibility

As explained in Chapter 2, a compatibility check is undecidable if the actual type andan expected type are overlapping, but the first is not a subtype of the second. This caseoccurs if the expected type is a subtype of the actual type.

Consider the new specification of the well-formedness check of a division expression

Page 56: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

44 CHAPTER 4. CONSISTENT EXPRESSIONS

above. The expected type of the left- and right-hand side is a numeric one. The mostgeneral numeric type in VDM-SL is the real type R. All other numeric types are subtypesof R. The compatibility check itself has not been modified, but the consequences of itsresult for definite type checking (DEF mode) changed. If the definite compatibility checkfails, a PO is raised stating that the actual expression is in fact of the expected type. Thisformulation is called a type judgement and has the form expression : Type. Note that thistype judgement expresses a subtype relation, which means that e.g., 1 :R is equal to true.

In all VDM-SL expressions these basic type compatibility checks can be found. Con-sider the function f, which increases its argument if it is a natural number, otherwise 1 isreturned.

N1 = natinv n == n <> 0

f: bool | nat -> N1f(x) == if is-nat(x)

then x + 1else 1

The returned value is restricted by an invariant to the natural numbers unequal tozero. The function is consistent, which means it will not cause a run-time error. However,the existing type checker fails to accept it, because: (1) the plus operator in x + 1 expectsnumeric types and therefore x must be compatible to (here: a subtype of) real. However,the actual type of x is the union type bool | nat which only overlaps the type real, butis not a subtype of it. (2) To check the consistency of the return value the type checkerwould have to statically determine, whether the invariant function is true or false, whichis is not possible.

Therefore the extended type checker raises two proof obligations stating the neededproperties that in cases: (1) x is of type real and (2) the invariant holds:

PO1: is-nat(x) ==> x:realPO2: x:bool | nat ==> inv-N1( if is-nat(x) then x + 1 else 1 )

PO1 trivially states that if x is a natural number then it is a real number. Note thatthis theorem is only valid for VDM-SL, with non-disjoint types. This PO can be provedautomatically by the proof tool. PO2 states that for the function body the implicitlydefined invariant function for N1 holds.

The example above shows that if an invariant causes the undecidability of a type com-patibility check, then the generated PO is formulated by means of the invariant functioninstead of a type judgement. PO2 could also be formulated by a type judgement:

PO2: x:bool | nat ==> if is-nat(x) then x + 1 else 1:N1

Note, the two versions of PO2 are not equivalent. In order to prove the type judgementversion, both the invariant proof and the proof that the if expression is a natural numbernat is needed. However, the last is checked by possible type checking which is intendedto be performed before definite type checking.

Page 57: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

4.3. DOMAIN CHECKING 45

4.3 Domain Checking

Domain checking is the check if a function is applied with parameters in its defined domain.In VDM-SL expressions, two kinds of constructs causes the undecidability of domainchecking:

• applications of functions defined by pre-conditions

• partial operators

Thus, for domain checking proof obligations are generated for both. In the following anoverview of the generated proof obligations for domain checking is given. Furthermore,parts of the formal specification of the synthesis process is provided.

4.3.1 Functions with Pre-conditions

A pre-condition p is a predicate, which restricts the domain of a function f . Nothing isguaranteed for a function outside its pre-condition. It may yield undefined or a propervalue of the right type. Ensuring the consistency of function application expressions, likef (x ), it is necessary that the pre-condition holds. Therefore, a proof obligation stating thepre-condition has to be generated. A VDM-SL function definition with a pre-condition,defines implicitly a Boolean pre-condition function, denoted with the prefix “pre-” and thefunction name, e.g. pre-f . This pre-condition function takes the same arguments as thereferring function and evaluates to true if the pre-condition holds, otherwise to false. Thisfunction is used to formulate a PO, always generated when a function with a pre-conditionis applied.

In the gateway example of the previous chapter, we have already introduced a functiondefined with a pre-condition. However, this function Load has not been applied (used) inother parts of the trusted gateway specification:

Load: Gateway -> GatewayLoad(g) ==

mk_Gateway(tl g.input,g.highOutput,g.lowOutput,g.high,g.low,hd g.input)

pre g.input <> []

Here the pre-condition ensures that the head hd and tail tl operators are not appliedto the empty list. Consider a function to send an interrupt call over the trusted gateway:

Send_INT: Gateway -> GatewaySend_INT(g) ==

Analyse( Load( mk_Gateway(["INT"] ^ g.input,

Page 58: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

46 CHAPTER 4. CONSISTENT EXPRESSIONS

g.highOutput,g.lowOutput,g.high,g.low,g.block) ) )

The function inserts the message ”INT” as the next input message, loads and analysesit, and put the message on one of the output ports. Besides two other proof obligationscaused by the invariants of Gateway and Port (see Chapter 3), domain checking raises athird proof obligation for the pre-condition:

PO:g:Gateway==>pre-Load( mk_Gateway(["INT"] ^ g.input,

g.highOutput,g.lowOutput,g.high,g.low,g.block) )

The proof obligation simply states that the pre-condition function must evaluate totrue for the actual parameter, under the assumption that g is of type Gateway.

Checking Function Applications

For function applications1 type checking is defined as:

CheckBasicApply : (POS | DEF)× TypeRep × TypeRep∗ × Expr × Expr∗o→ B× TypeRep

CheckBasicApply (i , tp1, tp-l , fct , argl) 4(dcl reswf : B := true,

iscomp : B := true;cases tp1:

mk-FnTypeRep (Dom,Rng) →if len Dom = len tp-lthen (if i = DEF ∧HasPrec (fct)

then let precfnctnm = mk-Name ("pre "y hd fct .ids) in

GenPO(mk-AS ‘ApplyExpr (precfnctnm, argl)) ;for index = 1 to len Dom

1In order to simplify, the treatment of higher order functions is not shown here.

Page 59: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

4.3. DOMAIN CHECKING 47

do (iscomp := IsCompatible (i , tp-l (index ),Dom (index ));if ¬ iscomp ∧ i = DEFthen (GenPO(mk-TypeJudgement (argl (index ),Dom (index )));

iscomp := true);reswf := reswf ∧ iscomp);

if reswfthen return mk- (true,Rng)else (GenErr(ERROR,

"Actual parameters to function of incorrect type") ;return mk- (false,Rng) ))

else (GenErr(ERROR, "Function applied with wrong number"y" of arguments") ;

return mk- (false,Rng) )end )

In CheckBasicApply the choice of possible and definite consistency checks is conveyedto the operation via the first argument i . The second argument is the type of the applyconstruct, which can be a function, a map or a sequence. Here, only the check of afunction application is shown. The next argument tp-l is the sequence of actual argumenttypes. Finally, two arguments (fct and argl) provide the function expression and itsactual argument sequence in order to generate proof obligations. In the operation an errormessage is first raised if the function is applied with the wrong number of arguments. Fordefinite consistency the proof obligation for domain checking is generated, if the functionhas a pre-condition (HasPrec(fct)). Then, all actual argument types are checked, whetherthey are compatible with the function definition. As explained in Section 4.2 a typejudgement PO is generated if the definite compatibility check fails. Note that in the caseof a PO generation, the compatibility value is changed to true. This demonstrates the ideaof conditional type checking, which means that the type is compatible under the conditionthat the generated PO can be proved. Finally, the well-formedness and type (the range)of the apply expression is returned.

4.3.2 Partial Operators

In the following an overview of the partial operators in VDM-SL is given. For each operatorthe dynamic semantics is explained and a small example serves to demonstrate the kindof proof obligations generated for domain checking.

Head and Tail

The head and sequence operators have already been explained in the gateway example.However, to be complete we show the generated PO for the expressions hd s and tl s.Both operators are undefined for the empty sequence:

PO: context ==> s <> []

Page 60: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

48 CHAPTER 4. CONSISTENT EXPRESSIONS

Map Merge

The merge operator munion merges two maps such that the resulting map maps theelements of both domains as does the two maps. The partiality is introduced by therestriction that both maps must be compatible. Two maps are compatible, if any commonelement of their domains is mapped to the same value by the two maps. The PO ensuringthe compatibility of a merge expression m1 munion m2 looks like:

PO:[| context;

e1 in set dom m1;e2 in set dom m2 |]

==>e1 = e2 => m1(e1) = m2(e2)

Consider a function to add an entry in a simple map based telephone register:

typesName: seq of charRegister: map Name to nat

functionsAdd: Name * nat * Register -> RegisterAdd(nm, phone, reg) ==if nm not in set dom regthen

reg munion {nm |-> phone}else

reg

To prevent conflicts Add adds only new names to the register. The PO to ensure thecompatibility of the example is:

PO:[| nm: Name;

phone: nat;reg: Register;nm not in set dom reg;e1 in set dom reg;e2 in set dom {nm |-> phone} |]

==>e1 = e2 => reg(e1) = reg(e2)

The additional context that nm is not in the domain of the register causes the left handside of the implication in the conclusion (e1 = e2) to evaluate always to false. Thus, thisPO is provable. The same kind of proof obligation is generated for a map enumeration,to ensure the internal compatibility of the map.

Page 61: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

4.3. DOMAIN CHECKING 49

1

3

2 b

c

a

c

1

2

3

a

(a) (b)

Figure 4.1: Pointer diagram of a general map (a) and an injective map (b).

Distributed Map Merge

The distributed merge operator merge merges a set of maps. As for the binary merge allsets must be compatible. The proof obligation to ensure the consistency (compatibility)of a distributed merge expression merge ms is formulated as follows:

PO:[| context;

m1 in set ms;m2 in set ms;e1 in set dom m1;e2 in set dom m2 |]

==>e1 = e2 => m1(e1) = m2(e2)

The proof oblgation is an extension of the binary merge version above. Here the first twoassumptions express that the map compatibility must hold for all pairs of maps in the setof maps.

Inverse Maps

The next partial map operator is the map inverse operator, which yields the inverse map.As for functions the inverse map only exists for injective maps. An injective map is onefor which no element of the range is associated with more than one element of the domain.Figure 4.1 shows the pointer diagram of a general map {1 |-> a, 2 |-> a, 3 |-> b}(a), for which no inverse map exists and injective map {1 |-> a, 2 |-> b, 3 |-> c}(b). Inversing map (a) would not yield a map anymore, since one domain element wouldhave to map to two different range elements. Therefore, a proof obligation stating theinjective property of the map is generated for a map inverse expression inverse m:

PO:[| context;

e1 in set dom m;

Page 62: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

50 CHAPTER 4. CONSISTENT EXPRESSIONS

e2 in set dom m |]==>m(e1) = m(e2) => e1 = e2

The proof obligation states that equal range elements must be associated to equal domainelements, which holds for map (b), but not for map (a) in Fig. 4.1.

Map Iteration

A map iteration has the form m ** n and yields the map where a map m is composedwith itself n times. n equal to zero yields the identity map where each element of dom mis mapped into itself. For n equal to one the expression evaluates to m itself. Consider theexample

{1 |-> 2, 2 |-> 3, 3 |-> 4, 4 |-> 1} ** 3

which evaluates to

{1 |-> 4, 2 |-> 1, 3 |-> 2, 4 |-> 3}For n > 1, the range must be a subset of the domain. Therefore, the proof obligation

PO:[| context;

n > 1 |]==>rng m subset dom m

is generated.

Division by Zero

Besides the already explained numeric division, three other operators are based on division.

• Numeric division has been already explained.

• Integer division yields the integer result of a division a div b. The signature of theoperator is int * int -> int. For example, 7 div 3 equals 2.

• Modulo is based on a division and is therefore partial, too. a mod b is defined onintegers and takes the sign of b, if the signs are different.

• Remainder is the same as modulo if the two signs of the operands are the same.Otherwise, unlike modulo, a rem b takes the sign of a.

For all four operators the same kind of proof obligation

PO: context ==> b <> 0

is generated.

Page 63: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

4.3. DOMAIN CHECKING 51

Sequence Modification

A sequence modification l ++ m modifies the elements of a sequence l whose indexes arein the domain of the map m to the range value that the index maps into. For example,[9, 7, 9, 1] ++ { 2 |-> 9, 4 |-> 5} evaluates to [9, 9, 9, 5]. The domain of themap must be a subset of the indices of the sequence, which is guaranteed by the PO:

PO: context ==> dom m subset inds l

Iota Expressions

An iota expression has the form iota bd & e where bd is either a set bind (x in set s) or atype bind (x: Type), and e is a Boolean expression. The semantics of the iota expression issuch that it returns the unique value which satisfies the body expression e. Some exampleswill explain the semantics:

iota x in set {1,2,3} & x mod 3 = 0 ≡ 3

iota x: nat & x ** 2 = 9 ≡ 3

The iota operator can only be used if a unique value exists which matches the bindand makes the body expression e yield true. For example, iota x:int & x ** 2 = 9 isundefined because two possible values (-3, 3) exist. Proving the raised proof obligation

PO: context ==> exists1 bd & e

guarantees the uniqueness of the iota expression.

Apply Expressions

The PO for map and sequence applications have been extensively shown in the previouschapter.

Page 64: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

52 CHAPTER 4. CONSISTENT EXPRESSIONS

Page 65: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Chapter 5

Consistent Pattern Matching

Pattern matching is one of the advanced features of VDM-SL. All constructs containingpatterns are powerful tools in specifying. However, patterns raise some difficulties in typechecking that are worth investigating. The use of patterns depends on the expressionscontaining them. In this chapter let and cases expressions will serve as example con-structs. However, first patterns and their type checking is explained. Then, the approachof generating proof obligations is extended to pattern matching.

5.1 Patterns

A pattern is a template for a value of a particular class of type. It is always used in acontext where it is matched to a value of a certain type. Consider the set enumerationpattern {a, 2}. This pattern matches only set values with two elements, where one ofthe elements is 2. The identifier a is called a pattern identifier and matches any value, ofany type. The match value 2 can only be matched against the value itself. Possible valuesmatching the set enumeration pattern are {1, 2} or {true, 2}. Like the pattern {a, 2},which contains an identifier (a) and a value (2), patterns can be constructed by nestingthe different kinds of patterns. Consequently, pattern matching is defined recursively bydistinguishing the different patterns:

• A pattern identifier matches any value, of any type. The identifier is bound to thevalue and can be used in its scope.

• The don‘t care pattern ‘-‘ is like a pattern identifier, but no binding occurs. Forexample, the pattern {-, 2} matches the same values as {a, 2}. The “don’t care”pattern serves as a pattern constructor, where its matched value is not used andtherefore, no binding to a name (identifier) is needed.

• A match value can only be matched against the value of itself; no binding occurs. Inthe pattern {a, 2}, the match value is used to reduce the matching values to setscontaining a certain value 2.

53

Page 66: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

54 CHAPTER 5. CONSISTENT PATTERN MATCHING

• A set enumeration pattern matches only set values with all elements matching. Forexample, {a, b, c} matches all set values with the cardinality of three.

• A set union pattern s1 union s2 matches only set values with the partition of twosubsets, matching s1 and s2. A set union pattern s union {1, 2} with a patternidentifier and a match value {1, 2} will match any set which has the set {1, 2} asa subset.

• A sequence enumeration pattern matches only sequence values with each patternmatching the corresponding element in the sequence value. Consequently, the lengthof the sequence value and the number of patterns must be equal. A pattern [1, b,c] matches all sequences with three elements and the head equal to 1.

• A sequence concatenation pattern matches only sequence values. The two patternsare matched against two subsequences which together can be concatenated to formthe original sequence value. For example the pattern a ^ [’B’, ’e’, ’r’, ’n’,’i’, ’e’] ^ b matches all sequences containing the string (sequence of characters)”Bernie”.

• A tuple pattern matches only tuples with the same number of elements, at whicheach of the elements matches the corresponding in the tuple value. A tuple patternmk (1, -, -), matches triples where the first component is equal to 1.

• A record pattern matches record values with the same tag and each of the patternsmatching the corresponding field of the record value. A tag is the unique identifierof the record type. Consider the record type mk Complex(x, y) to model complexnumbers by their real and complex parts. Then a record pattern mk Complex(x, 0)can be defined, which matches all Complex values on the real axis of the complexnumber plane.

The usage of patterns depends on the expressions containing them. In let-expressionsa pattern is used to improve the readability or to decompose complex structures intotheir components. In cases expressions the pattern matching property controls the logicalflow. These different applications of pattern matching makes it necessary to look on theexpressions containing the patterns to explain the type checking mechanisms and theprocess of proof generation.

5.2 Type Checking Patterns

In general, type checking patterns can be seen as checking if the patterns can matchassociated values. If they cannot, the specification has to be rejected. A pattern identifier,for example, is compatible to all types, but a set enumeration pattern expects a set type.

Let us have a closer look on a let-expression to explain the type checking process. Inlet expressions patterns are used to improve the readability of complicated expressions orto decompose complex structures. The general form of a simple let expression is:

Page 67: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

5.2. TYPE CHECKING PATTERNS 55

let pattern = expr in ...

To be consistent, which means the pattern matches the values of the expression (expr),the type of the expression must be compatible to the set of values the pattern matches.Again, a possible and definite well-formedness of patterns can be distinguished. In thefollowing the difference of the two kinds of type checking for patterns will be explained.Below, the operation wf Pattern defines the possible and definite (POS | DEF ) well-formedness (consistency) of a given pattern (Pattern) in relation to the type (TypeRep)of an expression.operations

wf -Pattern : (POS | DEF)× Pattern × TypeRep o→B×Name m-→ TypeRep

wf -Pattern (i , pat , tp) 4cases pat :

mk-PatternId (-, -) → wf -PatternId(i , pat , tp) ,mk-MatchVal (-) → wf -MatchVal(i , pat , tp) ,mk-SetEnumPattern (-, -) → wf -SetEnumPattern(i , pat , tp) ,mk-SetUnionPattern (-, -) → wf -SetUnionPattern(i , pat , tp) ,mk-SeqEnumPattern (-, -) → wf -SeqEnumPattern(i , pat , tp) ,mk-SeqConcPattern (-, -) → wf -SeqConcPattern(i , pat , tp) ,mk-RecordPattern (-, -, -) → wf -RecordPattern(i , pat , tp) ,mk-TuplePattern (-, -) → wf -TuplePattern(i , pat , tp)

end;

The different kinds of patterns are distinguished in a cases expression and forwarded tothe associated sub-checks. The operation returns the well-formedness as a boolean valueand a map containing the binding of pattern identifiers to their types.

As explained, a pattern identifier matches every (type of) value and is therefore alwayswell-formed. The resulting new binding is the pattern name bound to the value type.

wf -PatternName : (POS | DEF)× PatternId × TypeRep o→B×Name m-→ TypeRep

wf -PatternName (-, mk-PatternId (nm, -), tp) 4let bd = if nm = nil

then {7→}else {nm 7→ tp} in

return mk- (true, bd);

Note the use of patterns in the specification itself. In the argument list “don’t care”patterns indicate that argument or parts of them are not used in the operation body.The let expression defines the binding using a pattern identifier bd . In the type checker a“don’t care” pattern is modeled by a pattern identifier with a name nm equal to nil. Inthis case no binding occurs and the empty map is returned.

Page 68: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

56 CHAPTER 5. CONSISTENT PATTERN MATCHING

A more interesting pattern is the set enumeration pattern. The specification for check-ing the well-formedness of this pattern is given below:

wf -SetEnumPattern : (POS | DEF)× Pattern × TypeRep o→B×Name m-→ TypeRep

wf -SetEnumPattern (i , mk-SetEnumPattern (els, -), tp) 4let stp = ExtractSetType (tp) in

let elemtp = UnmaskSetType (stp) in

if elemtp = nil

then return mk- (false, merge {ExtractBindings (p) |p ∈ elems els})

else let res = {wf -Pattern (i , e, elemtp) | e ∈ elems els} in

let wf = {wf -p | mk- (wf -p, -) ∈ res} in

let b-s = {bd | mk- (-, bd) ∈ res} in

let bind = MergeBindings (b-s) in

return mk- (∀wf -p ∈ wf · wf -p ∧(i = DEF ⇒ stp = tp),

bind)

In the first let expression the set type is extracted from the value type tp. That meansthat if the type tp is a union type nat | set of nat, the type representation (TypeRep)of set of nat is returned. The second let expression unmasks the element type (elemtp)of the set type. If stp was no set type or the empty set [], the element type cannot bedetermined and becomes nil . In this case false is returned, because a set enumerationpattern cannot match another type than a set. If stp is a sequence type, the compatibilityof every pattern forming the enumeration, and the element type is checked recursively.The boolean result is constructed as well as the returned bindings are merged.

The interesting part, from the type checking point of view, is the implication in thereturn value. It states that for definite type consistency the extracted sequence type stpmust be equal to the value type tp. This is easy to understand. In definite mode everypossible value must be able to match the pattern, therefore only set values are excepted.But in possible mode a possible match is required, which means that a set could beextracted out of tp. In the following section the approach of generating proof obligations,if the definite checks fails is demonstrated.

5.3 Let expressions

We consider the following example in order to investigate the behaviour of the type checker:

let {a,b} = if true then {1,2} else 0 in a + b

In practice the example would be useless and of poor quality, because the else branch is infact “dead code”. However, the expression is consistent and serves to look into the edgesof type checking pattern expressions. The expression evaluates to 3. The if expression is

Page 69: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

5.4. DON’T CARE PATTERNS 57

of the union type set of nat | nat. As explained, the set enumeration pattern matchesonly with set values. In possible mode the type checker checks if the pattern possiblymatches the value, i.e. if the set of values the pattern denotes overlaps the values denotedby the expression. In the example above this is the case. To be definite consistent thetype checker has to guarantee the match. This is not possible, without evaluating theexpression. A check of this kind is undecidable in general and therefore a proof obligationstating that the pattern matches the expression/value is needed. Using an existentialquantification we are able to formulate a predicate “pattern matches value”. The matchproof obligation for the example above looks like:

PO: exists a, b:nat & {a,b} = if true then {1,2} else 0

Verifying this PO ensures formally that the pattern matches the value. During the processof generating a proof obligation, the pattern {a,b} is turned into an expression. Note thatfor patterns containing a match value in any case a proof obligation has to be generatedto ensure the definite consistency. The following example makes this obvious:

let {a,2} = {1,2} in a

The let expression above evaluates to 1. The match value 2 restricts the matching property:The pattern matches only sets of two elements where 2 is one of the elements. This is notdecidable in general. Therefore the PO

PO: exists a:nat & {a,2} = {1,2}

is generated. To use the pattern on the left-hand side of the equality a function Pattern2Exprhas been defined, which converts a pattern to an equivalent expression. In the followingsection parts of Pattern2Expr will be shown.

5.4 Don’t Care Patterns

To construct the existence quantifier expression a type binding, like e.g. a : Type isneeded for every pattern identifier. A “don’t care” pattern has to be transformed into apattern identifier and a type binding has to be determined. Consequently, a new uniquename (identifier) has to be generated. This name is used as a bounded variable in the PO.Therefore additionally, the type binding for this new identifier must be added to the typebinding returned by the pattern check wf Pattern.

5.4.1 Unique Names

A unique name is generated by concatenating a certain prefix with a unique number:functions

Page 70: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

58 CHAPTER 5. CONSISTENT PATTERN MATCHING

GenName : [char∗] → Name

GenName (prefix ) 4let v = if prefix = nil

then Defaultprefixelse prefix ,

n = GetUniqueNum () in

let name = mk-Name ([v yNumToString (n)]) in

if LookUpName (name) 6= nil

then GenName (v)else name;

GenName takes an optional prefix and returns a unique name in the abstract syntaxrepresentation. If no prefix is specified a default prefix is chosen. Next, a unique number,converted to a string, is concatenated. Then, the name is searched in the Environmentand if it is not present, which means it is not used, it is returned. Otherwise, the functionis called recursively, which means that the unique number is increased by 1.

5.4.2 Type Binding

To get the new type binding we use the type of the whole pattern the type of the expressionagainst the pattern should match. We have to analyze the structure of the pattern to getthe right type for the new identifier. This is the reason why the name generation for don‘tcare patterns takes place in the pattern to expression conversion function Pattern2Expr .Both, the name and the type binding for “don‘t care” patterns are generated, and thepatterns are translated into expressions in one walk through the abstract syntax tree ofthe pattern.

The function Pattern2Expr returns the pattern converted to an expression and a typebinding of detected “don’t care” patterns. The don‘t care pattern is represented in theabstract syntax tree by a pattern name, whose name field is equal to nil . In this casea unique name is generated and bound to the expected type. However, it could happenthat the expected type of a pattern identifier (name) is unknown and therefore nil . Thissituation (expected type is nil ) could occur, if the possible type check is not done before,and an impossible consistent pattern match generates a proof obligation. The approachis taken that a don‘t care pattern could be of any type, and a new type variable rangingover types is generated. The proof tool, that will be used to prove the POs is implementedwith the generic theorem prover Isabelle [72]. In Isabelle new type variables (not explicitlydefined) are of any type. Thus, every type can be assigned to them. The unique nameprefix chosen for such type variables is “ty”. Below this specification of the translation forpattern identifiers and set enumeration patterns to expressions is given:

Page 71: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

5.4. DON’T CARE PATTERNS 59

Pattern2Expr : Pattern × [TypeRep] → Expr ×Name m-→ TypeRep

Pattern2Expr (pat , tp) 4cases pat :

mk-PatternId (nm, -) →if nm = nil

then let dontcare = GenName ("tmp"),nonniltp = if tp = nil

then mk-TypeVarRep (GenName ("ty"))else tp in

mk- (dontcare, {dontcare 7→ nonniltp})else mk- (nm, {7→}),

mk-SetEnumPattern (patl , -) →let stp = ExtractSetType (tp) in

let elemtp = UnmaskSetType (stp) in

let list = [Pattern2Expr (patl (i), elemtp) | i ∈ inds patl ] in

let b-s = {bd | mk- (-, bd) ∈ elems list},exprl = [let mk- (expr , -) = list (i) in

expr | i ∈ inds patl ] in

let mk- (-, dontcarebind) = MergeBindings (b-s) in

mk- (mk-SetEnumerationExpr (exprl), dontcarebind)end

For converting a set enumeration pattern into an expression, first a set type is extractedout of the expected type tp. The element type is the new expected type for the recursivecall of the converting function, where each element of the enumeration is converted. Afterconverting the elements, the expression list for the elements and the new dontcarebind ingare constructed.

5.4.3 Example

Consider the slightly modified let expression from before:

let {a,-} = if true then {1,2} else 0 in a

For this let expression containing a “don’t care” pattern, the generated PO is:

PO: exists a, tmp1: nat & {a,tmp1} = if true then {1,2} else 0

During converting the pattern to an expression the identifier tmp1 has been generatedfor the “don’t care” pattern. Additionally, the extracted element type of {1,2} has beenbound to tmp1. If this type cannot be detected, because of an impossible consistent valueexpression, a type variable is generated. Impossible in our sense means that the typedomains are not overlapping or in other words, the possible type check fails. This is thecase in the let expression below:

let {a,-} = 1 in a

Page 72: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

60 CHAPTER 5. CONSISTENT PATTERN MATCHING

Even in such pathological cases the proof obligation generator works and generates theunprovable PO:

PO: exists a: ty1, tmp1: ty2 & {a,tmp1} = 1

To be able to formulate the proof obligation unique type names are generated for a andthe don‘t care identifier.

5.5 Cases Expressions

The use of patterns in cases expressions is very different from what was presented above.Cases expressions allow the choice of one from a number of expressions on the basis of thevalue of a particular expression. Consider the following cases expression:

let a in set {1, 2, {1,0}, {2,0}} incases a:1,{1,b} -> DoThis(1),2,{2} union b -> DoThat(2),others -> 0

end

The possible values of a are defined by a let be-such-that expression. Here patterns areused to define the branches of a cases expression. The expression which is going to beevaluated is selected by pattern matching, where several patterns can be used to defineone branch.

Cases expressions need special treatment in definite type checking. The existing typechecker had to be improved, because errors were returned in almost all cases. Type check-ing the example above produced several error messages “Pattern cannot match”. However,the expression is in fact type consistent. The reason for the overly strict behaviour of thetype checker was, like for let expressions above, that every pattern was checked for itswell-formedness in definite mode.

However, the semantics of pattern matching used this way is different from that in let-expressions. Type checking a pattern in definite mode assures that it will match definitely.This approach is not feasible in a cases expression, where pattern matching serves to select,not to define a value. The patterns in the cases expression above have to be able to matchto a, which means that the sets of values they denote must overlap the value domain ofthe expression a. Therefore, patterns in cases expressions only need to be possibly well-formed (consistent). If the possible well-formedness check fails for a pattern, this patterncan never match and the corresponding expression will become “dead code” (holds for asingle pattern). Figure 5.1 shows the type relations for cases expressions. The grey areasindicate the set of values to which the patterns in the cases expression match. The whitearea (expr .a) is the set of values denoted by the type of a. The different possibilities forthe pattern types are: (1) The pattern is overlapping expr . a (p1 to p3). (2) The pattern

Page 73: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

5.5. CASES EXPRESSIONS 61

Selector

A1

A2

A3A4

A5

Figure 5.1: The sets of values which match the patterns in a cases expression.

does not overlap expr .a (p4) and therefore cannot match. (3) The pattern is a subtype ofexpr .a (p5). (4) The type of expr .a is a subtype of the pattern. (5) A pattern identifier,which matches with every value, occurs. It covers the whole type universe of VDM-SL.(6) The others alternative is present. It covers the white area of the domain of expr .a,which is not covered (overlapped) by the alternative patterns.

In VDM-SL the others alternative is not mandatory, if the expression to which thealternative patterns are matched (expr .a) is fully covered (overlapped) by these patterns.Thus, the others construct can be skipped, if one of the alternatives will match the ex-pression definitely. In the example above the others construct can be omitted, because theother alternatives fully cover the possible values. To ensure the coverage of the expressionby the patterns in a cases expression without an others branch or a pattern identifier aproof obligation has to be generated. The coverage PO for the above cases expressionwithout an others construct would be:

PO:a in set {1, 2, {1,0}, {2,0}}==>exists b: nat | set of nat &a in set {1,2} or{1,b} = a or{2} union b = a

The proof obligation states that for all a in the set, a match must be possible. The matchvalues are summarised in a value set. The provability of this proof obligation shows thedefinite consistency of the example even without the others branch.

Page 74: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

62 CHAPTER 5. CONSISTENT PATTERN MATCHING

Page 75: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Chapter 6

Operations

In VDM-SL one can specify both functions and operations. What distinguishes opera-tions from functions is the use of states (variables in traditional programming languages).Operations can manipulate local and global states and are therefore imperative. Like func-tions they can be defined either implicitly or explicitly. An explicit operation definitioncontains a sequence of statements, which are very similar to statements found in ordinaryprogramming languages.

The main problem concerning our work is that no proof theory covering the full imper-ative part of VDM-SL exists. Also the proof tool, which is currently under development,does not yet deal with operations and statements. The main reason for this lack is thetotally different way of proving in the imperative world: Due to side effects [87], the wholehistory of state changes has to be considered.

Traditional proof systems for statements use a pre-post strategy where a pre-conditiondescribe what is assumed to hold before execution of a specific statement and post-condition describes what will hold after executing the statement [42, 9]. A few proofrules for VDM-SL statements, which are adapted for exception handling, can be found in[53].

Implicit operations can be treated as implicit functions, which means a satisfiabilityproof obligation is generated to ensure consistency. However, explicit operation definitionsneed another approach.

6.1 Generating Assertions

The central idea in the POG to ensure the definite consistency of VDM-SL operationsis to generate assertions and include them into the specification. An assertion is a pre-predicate stating the property which must hold before a statement. Thus, in type checkingoperations the generated proof obligations are not proof rules but assertions. The abstractsyntax for an assertion is:

Assertion : : loc : Locationprd : Sequent ;

63

Page 76: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

64 CHAPTER 6. OPERATIONS

The assertion is composed of a sequent and a location. As in a PO above, a sequentstates the needed property. The need for a sequent will be explained later. The locationis needed, due to the fact that an assertion is always related to a certain location in thespecification.

Location : : oper : Namestmt : N1

The Location is defined by the operation name and the nth statement for which theassertion represents a pre-predicate. Nested statements are counted in the order of theirappearance in the specification. Consider the following specification to calculate the av-erage of a set of numbers:

SmallNat = natinv s == s < 256

Average: set of SmallNat ==> realAverage (s) ==( dcl sum : SmallNat := 0;

for all e in set s do( if sum > 255 - e then exit <ToLarge>;sum := sum + e );

return sum / card s )

As in traditional programming languages the numbers are restricted to a certain size(SmallNat). The operation takes the set of numbers as an argument and uses the localstate sum and a loop to compute the result. In the loop an exception <ToLarge> is raisedif the sum is going to exceed its maximum.

The loop statement is a good example for a construct, for which it is impossible togenerate a context as in the sections above. Therefore the POG generates and inserts thefollowing assertions to ensure definite consistency:

Average: set of SmallNat ==> realAverage (s) ==( --PO1: inv-SmallNat(0)

dcl sum : SmallNat := 0;for all e in set s do( if sum > 255 - e then exit <ToLarge>;--PO2: inv-SmallNat(sum + e)sum := sum + e );

--PO3: card s <> 0return sum / card s )

PO1 must hold before the first declaration statement to ensure that the initialisation ofsum will not violate the invariant. PO2 will be inserted before the assignment statement.It must be proved in order to ensure that the assignment will not exceed the maximum of

Page 77: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

6.2. EXPRESSIONS IN STATEMENTS 65

sum. Finally, PO3 has to be included before the return statement. It can be seen as theobligatory pre-condition of the division expression. The return statement is definitely notconsistent, because PO3 is not provable.

In the following we will change the specification to be consistent and will explain howwe treat expressions in statements.

6.2 Expressions in Statements

Like the return statement above, statements may include of expressions. Therefore unde-cidability could occur in an expression. Consider the consistent version of the specification:

Average2: set of SmallNat ==> realAverage2 (s) ==

( dcl sum : SmallNat := 0;for all e in set s do( if sum > 255 - e then exit <ToLarge>;sum := sum + e );

return if s <> {}then sum / card selse 0 )

Average2 returns zero if the set of numbers is the empty set by using an if expression. Tobe able to use the context in the expression the POG collects the context in expressionsas in functions. The difference from functions is that the POG type checking an operationgenerates a sequent assertion. The sequent notation is used to express the context ofan expression as local context. The generated assertions for Average2 demonstrate thisapproach:

Average2: set of SmallNat ==> realAverage2 (s) ==

( --PO1: inv-SmallNat(0)dcl sum : SmallNat := 0;for all e in set s do( if sum > 255 - e then exit <ToLarge>;--PO2: inv-SmallNat(sum)sum := sum + e );

--PO3: s <> {} ==> card s <> 0return if s <> {}

then sum / 0else 0 )

Now PO3 states that under the assumption that s is unequal to the empty set, the car-dinality of s is unequal to zero. Which is by definition of cardinality true ( ==> is theturnstile `).

Page 78: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

66 CHAPTER 6. OPERATIONS

Page 79: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Chapter 7

Concluding Remarks

In this thesis we have presented an approach for automatic generation of proof obligationsfor consistency of VDM-SL specifications. We have shown the general strategy and pre-sented more details about the kinds of constructs to which this kind of proof obligationgeneration has not been done before. The approach presented has also been formalised interms of a VDM-SL specification for which a few extracts have been shown. A paper giv-ing an overview of this work has been submitted to the FME’97 (Formal Methods Europe1997) symposium [4]. Additionally, the central ideas of this thesis have been presentedat the TIAPS (Towards Industrially Applicable Proof Support for VDM-SL) workshop,which took place at IFAD on the 28th and 29th of November 1996. From a tool point ofview this work is an improvement of the existing VDM-SL Toolbox and this improvementwill be demonstrated at the FME97 symposium.

7.1 Assessment of the Project Results

The proof obligation generation approach presented here has several advantages:

1. A larger subset of specifications can be formally checked according to their internalconsistency. This leads to a greater confidence in specifications. Especially, forvalidating the top level specification, where no formal proof of the correct relationto the informal description is possible, the extension of (formal) type checking is amajor advantage.

2. Using a proof tool many simple proof obligations can be proved automatically. Thus,the link of automatic type checking and theorem proving extends the set of speci-fications that can be checked automatically. Trivially, automation is important ingeneral, because it simplifies the work of the user. However, especially in formalmethods automation plays an important role, because it ensures the formality andcorrectness of a process.

3. The mechanical support of the generation and proof of proof obligations increasesthe level of formality, since it is extremely difficult to be truly formal manually as,e.g. with pencil and paper [79].

67

Page 80: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

68 CHAPTER 7. CONCLUDING REMARKS

4. Proof obligations provide more information than an error message. The user who isfamiliar with the basics of logic reasoning, will often detect the missing parts in aspecification by inspection. It needs only little experience and/or knowledge on howthe POG collects the context in order to interpret an unprovable proof obligation tofind, e.g. a missing pre-condition in a function. Therefore, the approach raises theconfidence in a specification even if the user has chosen a lower level of formalitywithout formal proofs.

5. Feeding the type errors as proof obligations into a theorem prover, leaves less forhuman examination, which reduces the possibility of errors being disregarded bythe user. In [66] it is shown that the former error messages raised by definite typechecking are often disregarded or neglected.

Due to the fact that the proof obligation generator has been specified in an executablesubset of VDM-SL, the specification serves as a prototype of the later implementation.The advantages stated above has been either obtained or could be justified by using theprototype on the examples in this thesis as well as during the test phase.

7.2 Personal Experiences

At the start of the project, a development plan was made for the complete six month theproject would last. In this plan, a time schedule was drawn up for each of the sub-tasks,which mainly reflected the structure of this thesis. This plan served to control the progressand to check the time estimates. This plan was very valuable as I was unexperienced intime estimations for VDM-SL specifications and projects over a half year.

It was a very valuable decision to go abroad to join the IFAD team. Besides the positivesocial experiences, I am convinced that the stay at this scientific institute raised the qualityof this work as well as my productivity. The main reason for this is the intensive contactwith the team members working in the same field and the possibility to discuss new ideasdirectly.

Before I started to work on this project, I had only a general knowledge of VDM-SL. However, I had some background in the similar formal method RAISE [77], where Idid specifications and proofs [64]. It was easy for me to switch to VDM-SL. After oneweek I was able to read and understand the specification of the existing type checker.Furthermore, my experience with the RAISE proof tool was necessary to design the proofobligations.

The experiences with the IFAD VDM-SL language and Toolbox can be summarizedas:

• VDM-SL is a powerful specification language, which is easy to learn. Very importantfor the project described in this thesis was the formal definition of the semantics inthe ISO-standard. Building a type checker one has to look into the edges of alanguage and general reference manuals or informal descriptions do not provide theneeded precision.

Page 81: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

7.3. FUTURE WORK 69

• The interpreter of the Toolbox allows the specifier to validate the functionality of thespecification in an early phase of the design process. During this work, interpretingwas very helpful in understanding the details and dependencies of the existing staticsemantics specification.

• As stated above the existing definite type checker is of less help. It is too tediousand less motivating to inspect error messages if the specification is in fact consis-tent. From a psychological point of view, it is more encouraging to observe proofobligations to ensure the consistency, than to inspect error messages, where in factno errors occur. It was the aim of this thesis to improve the definite type checkerand make it to a real useful tool. I feel that this goal has been reached.

7.3 Future Work

We feel that the combination of a proof obligation generator as presented here and a proofsupport tool currently being developed will be a powerful combination. However, morework is needed to make a tighter integration between such tools. Below possible directionsof future work are summarized:

• At present no work have been done on generating proof obligations for terminationof recursive functions.

• In this work the decision has been made to convey the task of simplifying to the prooftool. One could investigate if it is more efficient to perform minor simplificationsdirectly at the proof obligation generator.

• This work could also be extended by a closer integration with the proof tool beingdeveloped. In particular we envisage a possibility for the proof tool to automate theproof of type judgements by sending it to the POG.

• Due to the large number of proof obligations generated for large specifications, aproof obligation management tool (POMT) must be developed. This tool shouldcontrol and show which POs has been already proved and update POs after changesin the specification [78]. Furthermore, the POMT should be able to display onlychosen classes of POs, e.g., if a user want to inspect only domain checking POs of acertain module.

• During the TIAPS workshop, the question has been raised if it is possible to switchfrom the three valued logic of partial functions LPF to classical logic, if proof obli-gations ensure the definedness (consistency) of a specification. This subject needsfurther investigations. LPF causes difficulties in the proof tool development: A fewpowerful features of Isabelle for automating proofs only work for classical logic. Ingeneral, it is considerably more difficult to automate proof for three valued logicsthan for classical logics.

Page 82: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

70 CHAPTER 7. CONCLUDING REMARKS

• The solution of generating assertions for operations and states has to be adapted,when a proof theory for the imperative part of VDM-SL is available.

• In the long term one could investigate, if the use of state transformer monads [65, 91]to hide the state representation could result in the same kind of proof obligationsas for the functional part. In [66] it is shown how VDM-SL states are treated asmonads.

Page 83: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Bibliography

[1] J.-R. Abrial. The B Book – Assigning Programs to Meanings. Cambridge UniversityPress, August 1996.

[2] S. Agerholm and J. Frost. Towards an integrated CASE and theorem proving toolfor VDM-SL. Submitted to FME’97, January 1997.

[3] Alfred V. Aho, Ravi Sethi, and Jeffrey D. Ullman. Compiler: Principles, Techniquesand Tools. Addison-Wesley, 1986.

[4] Bernhard K. Aichernig and Peter Gorm Larsen. A Proof Obligation Generator forVDM-SL. Submitted to FME’97, January 1997.

[5] Derek Andrews, Anjula Garg, S.P.A. Lau, and J.R. Pitchers. The Formal Definition ofModula-2 and Its Associated Interpreter. In L. Marshall R. Bloomfield and R. Jones,editors, VDM ’88 VDM – The Way Ahead, pages 167–177. VDM-Europe, Springer-Verlag, September 1988.

[6] Derek Andrews and Darrel Ince. Practical Formal Methods with VDM. McGraw Hill,September 1991. ISBN 0-07-707214-6.

[7] D.J. Andrews, H. Bruun, B.S. Hansen, P.G. Larsen, N. Plat, et al. InformationTechnology Programming Languages – VDM-SL. Technical report, First CommitteeDraft Standard: CD 13817-1, November 1993. ISO/IEC JTC1/SC22/WG19 N-20.

[8] D.J. Andrews, H. Bruun, B.S. Hansen, P.G. Larsen, N. Plat, et al. Information Tech-nology — Programming Languages, their environments and system software interfaces— Vienna Development Method-Specification Language Part 1: Base language. ISO,1995. Draft International Standard: 13817–1.

[9] K. Apt. Ten Years of Hoare’s Logic: A survey - Part I. ACM-TOPLAS, 3(4):431–483,Oct 1981.

[10] Juan Bicarregui, John Fitzgerald, Peter Lindsay, Richard Moore, and Brian Ritchie.Proof in VDM: A Practitioner’s Guide. FACIT. Springer-Verlag, 1994. ISBN 3-540-19813-X.

71

Page 84: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

72 BIBLIOGRAPHY

[11] Juan Bicarregui and Brian Ritchie. Invariant, Frames and Postconditions: a Com-parison of the VDM and B Notations. In J.C.P. Woodcock and P.G. Larsen, editors,FME’93: Industrial-Strength Formal Methods, pages 162–182. Formal Methods Eu-rope, Springer-Verlag, April 1993. Lecture Notes in Computer Science 670.

[12] D. Bjørner and O. Oest (eds.). Towards a Formal Description of Ada, volume 98 ofLecture Notes in Computer Science. Springer-Verlag, 1980.

[13] Dines Bjørner. Software Architectures and Programming Systems Design. Educa-tional material of the Technical University of Denmark.

[14] Dines Bjørner. Specification and Transformation, Towards a Meaning of ‘M’ in VDM.Lecture notes to IFIP TC2/WG2.2 South America Tutorial: Formal Description ofProgramming Concepts, April 1989, February 1989. A revised and expanded versionof a TAPSOFT article.

[15] Dines Bjørner and Cliff B. Jones. Formal Specification and Software Development.Prentice-Hall, Stuttgart, Leipzig, 1982. p. ix.

[16] A. Blikle. A Guided Tour of the Mathematics of MetaSoft. Information ProcessingLetters, (29):81–86, 1988.

[17] Andrzej Blikle. A reply to B. Monahan remarks of April 30th 1989, May 1989.Warsaw.

[18] Grahan Boddy. The use of VDM within the Alvey Flagship Project. In L. MarshallR. Bloomfield and R. Jones, editors, VDM ’88 VDM – The Way Ahead, pages 153–166. VDM-Europe, Springer-Verlag, September 1988.

[19] Ed Brinksma. On the Design of Extended LOTOS. PhD thesis, University of Twente,November 1988. ISBN 90-9002545-6.

[20] T.M. Brookes, J.S. Fitzgerald, and P.G. Larsen. Formal and Informal Specificationsof a secure System Component: Final Results in a Comparative Study. In Marie-Claude Gaudel and Jim Woodcock, editors, FME’96: Industrial Benefit and Advancesin Formal Methods, pages 214–227. Springer-Verlag, March 1996.

[21] Hans Bruun, Flemming Damm, and Bo Stig Hansen. An Approach to the StaticSemantics of VDM-SL. In VDM ’91: Formal Software Development Methods, pages220–253. VDM Europe, Springer-Verlag, October 1991.

[22] Bernard Carre, William Marsh, and Jon Garnsworthy. SPARK: A Safety-Related AdaSubset. In Ada UK Conference, pages 1–19, Program Validation LTD. 26 Queen’sTerrace, Southampton, SO1 1BQ England, August 22 1992.

[23] V. Claus, G. Dewess, E. Zeidler, et al. Teubner-Taschenbuch der Mathematik Teil II.B.G. Teubner, Stuttgart, Leipzig, 1995. ISBN 3-8154-2100-4.

Page 85: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

BIBLIOGRAPHY 73

[24] Peter Linsay Cliff Jones, Kevin Jones and Richard Moore, editors. mural: A FormalDevelopment Support System. Springer-Verlag, 1991. ISBN 3-540-19651-X.

[25] I.D. Cottam. The Rigorous Development of a System Version Control Program. IEEEToSE, 10(2):143–154, March 1984.

[26] Dan Craigen. Formal Methods, EVES, and Safety Critical Systems. Technical report,ORA Canada, May 1994. p. 21.

[27] Dan Craigen, Susan Gerhart, and Ted Ralston. Formal Methods Technology Transfer:Impediments and Innovation. In J.P.Bowen M.G. Hinchey, editor, Applications ofFormal Methods. Prentice-Hall International, September 1995. p. 407.

[28] Dan Craigen, Sentot Kromodimoeljo, Irwin Meisels, Bill Pase, and Mark Saaltink.EVES: An Overview. In S. Prehn and W.J. Toetenel, editors, VDM’91 – FormalSoftware Development Methods, pages 389–405. Springer-Verlag, October 1991.

[29] Flemming Damm, Hans Bruun, and Bo Stig Hansen. On Type Checking in VDMand Related Consistency Issues. In VDM ’91: Formal Software Development Methods,pages 45–62. VDM Europe, Springer-Verlag, October 1991.

[30] Flemming M. Damm and Bo Stig Hansen. Generation of Proof Obligations for TypeConsistency. Technical Report 1993-123, Department of Computer Science, TechnicalUniversity of Denmark, December 1993.

[31] John Dawes. The VDM-SL Reference Guide. Pitman, 1991. ISBN 0-273-03151-1.

[32] D. Beech (ed.). Concepts in User Interfaces: A (VDM) Reference Model for Commandand Response Languages, volume 234 of Lecture Notes in Computer Science. Springer-Verlag, 1986.

[33] Brigitte Frohlich and Peter Gorm Larsen. Combining VDM-SL Specifications withC++ Code. In Marie-Claude Gaudel and Jim Woodcock, editors, FME’96: IndustrialBenefit and Advances in Formal Methods, pages 179–194. Springer-Verlag, March1996.

[34] Jon Garnsworthy, Ian O‘Neill, and Bernhard Carre. Automatic Proof of Absence ofRun-time Errors. In Ada UK Conference. London Docklands, October 1993.

[35] The RAISE Language Group. The RAISE Specification Language. The BCS Practi-tioners Series. Prentice-Hall, 1992.

[36] The VDM-SL Tool Group. The IFAD VDM-SL Language. Technical report, IFAD,May 1996. IFAD-VDM-1.

[37] The VDM-SL Tool Group. User Manual for the IFAD VDM-SL Toolbox. Technicalreport, IFAD, May 1996. IFAD-VDM-4.

Page 86: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

74 BIBLIOGRAPHY

[38] Jesper Kjaer Hansen and Henrik Nellager. Static Semantics and Tools for BSI/VDMSL. Master’s thesis, Technical University of Denmark, Department of ComputerScience, DK-2800 Lyngby, January 1991.

[39] Kirsten Mark Hansen. Formalising Railway Interlocking Systems. In Nordic Seminaron Dependable Computing Systems, pages 83–94, Technical University of Denmark,August 1994. Department of Computer Science.

[40] Howard Haughton. Specification in B: An Introduction Using the B Toolkit. WorldScientific Publishing, 1996.

[41] I.J. Hayes, C.B. Jones, and J.E. Nicholls. Understanding the Differences BetweenVDM and Z. FACS Europe, pages 7–30, Autumn 1993.

[42] C.A.R. Hoare. An Axiomatic Basis for Computer Programming. Communications ofthe ACM, 12(10):576–581, October 1969.

[43] Michael Jackson. Description is Our Business. In VDM ’91: Formal Software Devel-opment Methods, pages 1–8. Springer-Verlag, October 1991.

[44] P.S. Jackson and P.A. Stokes. Formal Specification and Animation of a Water LevelMonitoring System. Technical Report INFO-0428, Atomic Energy Control Board,Ottawa, Canada, March 1993.

[45] Vicky J. Bush John T. Latham and Ian D. Cottam. The Programming Process. AnIntroduction Using VDM and Pascal. Addison Wesley, 1990.

[46] Cliff B. Jones. Systematic Software Development Using VDM. Prentice-Hall Interna-tional, Englewood Cliffs, New Jersey, second edition, 1990. ISBN 0-13-880733-7.

[47] Cliff B. Jones and Kees Middelburg. A Typed Logic of Partial Functions Recon-structed Classically. Technical Report 89, Department of Philosophy, Utrecht Uni-versity, April 1993.

[48] John C. Kelly and Kathryn Kemp. Formal Methods, Specification and VerificationGuidebook for Software and Computer Systems – Planning and Technology Insertion.Technical Report NASA-GB-002-95 (Release 1.0), NASA, Washington, DC 20546,USA, July 1995.

[49] Brian W. Kernighan and Dennis M. Ritchie. The C Programming Language (secondEdition). Prentice-Hall International, Englewood Cliffs, New Jersey 07632, 1988.

[50] Richard Lampard. Specification of the Two-way Handshake in VDM. Report 188/91,National Physical Laboratory, Queen’s Road, Teddington, Middelsex TW11 0LW,UK, September 1991.

[51] Leslie Lamport. LaTeX: A Document Preparation System. Addison-Wesley Publish-ing Company, 1986.

Page 87: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

BIBLIOGRAPHY 75

[52] Peter Gorm Larsen. The VDM Bibliography. Technical report, The Institute ofApplied Computer Science, Forskerparken 10, DK-5230 Odense M, Denmark, January1994.

[53] Peter Gorm Larsen. Towards Proof Rules for VDM-SL. PhD thesis, Technical Uni-versity of Denmark, Department of Computer Science, March 1995. ID-TR:1995-160.

[54] Peter Gorm Larsen, Poul Bøgh Lassen, and Marcel Verhoef. Specification of theVDM-SL Static Semantics Checker. Technical Report IFAD-VDM-5, The Institute ofApplied Computer Science, Forskerparken 10, 5250 Odense SV, Denmark, November1993.

[55] Poul Bøgh Lassen and Peter Gorm Larsen. An Abstract State Machine Semanticsfor the IPTES Meta-IV Subset. IPTES Doc.id : IPTES-IFAD-12-V2.0, May 1991.

[56] M.K.O. Lee. The B Formal Software Engineering Technology and Its TechnologyTransfer into Industry. In K.R. Seumahu E.S. Subramanian, editor, Computer, Com-munication and Networking Systems: An Integrated Perspective. Proceedings of theInternational Conference on Information Engineering – ICIE 91, volume 1, pages332–340. Springer-Verlag, December 1991.

[57] Longman Dictionary of Contemporary English. Longman Group UK Ltd., new edi-tion, 1987.

[58] P. Lucas. On the Formalization of Programming Languages: Early History and MainApproaches. In The Systematic Development of Compiling Algorithm. INRIA Publ.Paris, 1978.

[59] P. Lucas. Formal Semantics of Programming Languages: VDL. IBM Journal of Devt.and Res., 25(5):549–561, 1981.

[60] P. Lucas. Main approaches to formal specification. In Formal Specification andSoftware Development, chapter 1, pages 3–24. Prentice-Hall, 1982.

[61] P. Lucas and K. Walk. On the Formal Description of PL/I. Annual Review AutomaticProgramming Part 3, 6(3), 1969.

[62] Peter Lucas. VDM: Origins, Hopes, and Achievements. In Airchinnigh Bjørner,Jones and Neuhold, editors, VDM ’87 VDM – A Formal Method at Work, pages1–18. VDM-Europe, Springer-Verlag LNCS 252, 1987.

[63] S.P. Miller and M. Srivas. Formal Verification of the AAMP5 Microprocessor – A CaseStudy in the Industrial Use of Formal Methods. In Proceedings of the 1995 Workshopon Industrial-Strength Formal Specification Techniques (WIFT’95), page 15. IEEEComputer Society, April 1995.

[64] Robert Milne. The Proof Theory for the RAISE Specification Language. TechnicalReport RAISE/STC/REM/12/V3, November 1990.

Page 88: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

76 BIBLIOGRAPHY

[65] E. Moggi. Computational lambda-calculus and monads. In Symposium on Logic inComputer Science, January 1989.

[66] Paul Mukherjee. Automatic Translation of VDM-SL Specifications into Gofer. Sub-mitted to FME’97, January 1997.

[67] Paul Mukherjee and Victoria Stavridou. The Formal Specification of Safety Require-ments for Storing Explosives. Formal Aspects of Computing, 5(4):299–336, 1993.

[68] Hanne Riis Nielson and Flemming Nielson. Semantics With Applications – A FormalIntroduction. John Wiley & Sons Ltd, 1992.

[69] Takahiko Ogino and Yuji Hirao. Formal Methods and their Applications to Safety-Critical Systems of Railways. QR of RTRI, 36(4):198–203, December 1995.

[70] Sam Owre, John Rushby, Natarajan Shankar, and Friedrich von Henke. Formal Ver-ification for Fault-Tolerant Architectures: Some Lessons Learned. In J.C.P. Wood-cock and P.G. Larsen, editors, FME’93: Industrial-Strength Formal Methods, pages482–501. Formal Methods Europe, Springer-Verlag, April 1993. Lecture Notes inComputer Science 670.

[71] Graeme I. Parkin. Vienna Development Method Specification Language (VDM-SL).Computer Standard & Interfaces, 16:527–530, 1994. Special issue with the generaltitle: The Programming Language Standards Scene, Ten Years On.

[72] L. C. Paulson. Isabelle: A Generic Theorem Prover, volume 828 of Lecture Notes inComputer Science. Springer-Verlag, 1994.

[73] Lawrence C. Paulson. Introduction to Isabelle. Technical Report 280, University ofCambridge, Computer Laboratory, 1993.

[74] Nico Plat and Hans Toetenel. Tool support for VDM. Technical Report 89-81, DelftUniversity of Technology, November 1989.

[75] Nico Plat and Hans Toetenel. A Formal Transformation from the BSI/VDM-SL Con-crete Syntax to the Core Abstract Syntax. Technical Report 92-07, Delft University,March 1992.

[76] Nico Plat, Jan van Katwijk, and Hans Toetenel. Applications and Benefits of For-mal Methods in Software Development. Technical Report 91-33, Delft University ofTechnology, Faculty of Technical Mathematics and Informatics, April 1991.

[77] The RAISE Method Group. The RAISE Development Method. The BCS PractitionersSeries. Prentice-Hall International, 1995.

[78] Kelvin J. Ross and Peter A. Lindsay. Maintaining Consistency under Changes to For-mal Specifications. In J.C.P. Woodcock and P.G. Larsen, editors, FME’93: Industrial-Strength Formal Methods, pages 558–577. Formal Methods Europe, Springer-Verlag,April 1993. Lecture Notes in Computer Science 670.

Page 89: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

BIBLIOGRAPHY 77

[79] John Rushby and Friedrich von Henke. Formal verification of algorithms for criticalsystems. IEEE Transactions on Software Engineering, 19(1):13–23, January 1993.

[80] Mark Saaltink. Z and EVES. In J.E. Nicholls, editor, Z User Workshop, York 1991,pages 223–242. Springer-Verlag, 1992. Workshops in Computing.

[81] Mark Saaltink. The Z/EVES system. Technical report, ORA Canada, September1995.

[82] S.J. Sadler. Nuclear Reactor Protection Software. An Application of VDM. Appendixto: VDM ’88. VDM - The Way Ahead. Springer-Verlag, 1988. From: Rolls-Royceand Associates Limited.

[83] David A. Schmidt. Denotational Semantics. A Methodology for Language Develop-ment. Allyn and Bacon, Inc., 1986.

[84] Dev Sen. Objectives of the British Standardization of a Language to Support theVDM. In Airchinnigh Bjørner, Jones and Neuhold, editors, VDM ’87 VDM – AFormal Method at Work, pages 321–323. VDM-Europe, Springer-Verlag LNCS 252,1987.

[85] Natarajan Shankar, Sam Owre, and John Rushby. A Tutorial on Specification andVerification Using PVS. In Peter Gorm Larsen, editor, Tutorial Material – FormalMethods Europe ’93, pages 357–406, April 1993.

[86] Joseph E. Stoy. Denotational Semantics: The Scott-Strachey Approach to Program-ming Language Theory. The MIT Press Series in Computer Science. The MIT Press,1977.

[87] R.D. Tennent. Principles of Programming Languages. Prentice-Hall International,Englewood Cliffs, New Jersey 07632, 1981.

[88] G.S. Teo and M. Mac an Airchinnigh. The Use of VDM in the Specification of ChineseCharacters. In VDM ’88 VDM – The Way Ahead, pages 476–499, September 1988.

[89] The UK Ministry of Defence. Defence Standard for Military Safety-Critical Software– 00-55, 1989. draft.

[90] Marcel Verhoef. A constructive static semantics for the IPTES Meta-IV specificationlanguage. Master’s thesis, Delft University of Technology, September 1992.

[91] Philip Wadler. Comprehending Monads. In Proceedings of the 1990 ACM Conferenceon LISP and Functional Programming, pages 61–78. ACM, 1990.

Page 90: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

78 BIBLIOGRAPHY

Page 91: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Appendix A

More Examples

Below we consider two further example specifications and their generated proof obligations.The POs have been generated by the executable VDM-SL specification of the POG wehave described in this thesis. The first example is the specification of an alarm system,the second is the specification of a traffic light system.1

A.1 Alarm System

In this example basic requirements and functions for an alarm system in a plant arespecified. In order to formulate the system a reduced model of a plant is used. A plantconsists of a plan, when experts are on duty and a set of possible alarms. The safetyrequirement formulated by an invariant of the type Plant states that for all possiblealarms and for all periods in the plan an expert with the needed qualification is available:

types

Plant :: plan : Planalarms : set of Alarm

inv mk_Plant(plan,alarms) ==forall a in set alarms &

forall per in set dom plan &QualificationOK(plan(per),a.quali);

A plan is specified by a map from periods to the sets of Experts on duty. Furthermore, inall time periods a minimum of one expert must be available. A period is identified by acertain token and an expert has an identification and set of qualifications:

Plan = map Period to set of Expertinv plan == forall exs in set rng plan & exs <> {};

Period = token;

1Both VDM-SL specifications have been provided by Peter Gorm Larsen.

79

Page 92: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

80 APPENDIX A. MORE EXAMPLES

Expert :: expertid : ExpertIdquali : set of Qualification

inv mk_Expert(-,q) == q <> {};

ExpertId = token;

Qualification = <Elec> | <Mech> | <Bio> | <Chem>;

Alarm :: alarmtext : seq of charquali : Qualification

The different kinds of qualifications are electrical, mechanical, biological and chemicalqualifications. Furthermore, and alarm provides an alarm text and the needed expertqualification to handle the alarm.

The functionality of the system is defined as follows: The function OnDuty determineswhether an expert is on duty in a certain period of time:

functionsOnDuty: Expert * Period * Plant -> boolOnDuty(ex,per,plant) ==ex in set plant.plan(per)

pre per in set dom plant.plan;

The function NoOfExperts returns the number of experts in a certain period of time:

NoOfExperts: Period * Plant -> natNoOfExperts(per,mk_Plant(plan,-)) ==if per in set dom planthen card plan(per)else 0;

The implicit function Page calls the appropriate expert for a given alarm in a certainperiod of time:

Page(a:Alarm,per:Period,plant:Plant) r: Expertpre per in set dom plant.planpost r in set plant.plan(per) and

a.quali in set r.quali;

The post condition states the properties a called expert has to fulfill: The expert mustbe on duty and must posses the demanded qualification. Finally, the auxilliary functionQualificationOK used in the invariant checks if there is an expert with the requiredqualification.

QualificationOK: set of Expert * Qualification -> boolQualificationOK(exs,reqquali) ==exists ex in set exs & reqquali in set ex.quali

Page 93: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

A.1. ALARM SYSTEM 81

A.1.1 Proof Obligations

The specification only uses simple language elements, therefore, the generated proof obli-gations are rather simple. However, traditional type checking fails even for such simpleexamples due to partial operators.

PO1:[| per : Period;

plant : Plant;per in set dom plant.plan |]

==>per in set dom plant.plan

PO1 is generated due to the partial map application in the function OnDuty. The contextinformation of the pre-condition is trivially equivalent to the demanded property. If oneof the assumptions is equivalent to the conclusion then the proof obligation is proven.

PO2:[| per : Period;

plan : Plan;per in set dom plan |]

==>per in set dom plan

PO2 is generated because of the map application in the function NoOfExperts. Again, anassumption and the conclusion are equivalent.

PO3:[| a : Alarm;

per : Period;plant : Plant;per in set dom plant.plan |]

==>exists r: Expert &r in set plant.plan(per) and a.quali in set r.quali

PO3 is the satisfiability proof obligation for the implicit Page function. It states that for allvalues and under the assumption the pre-condition holds, there exists a result satisfyingthe post-condition. Furthermore, PO4 is raised because of the map application in Page.

PO4:[| per : Period;

plant : Plant;per in set dom plant.plan |]

==>per in set dom plant.plan

Page 94: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

82 APPENDIX A. MORE EXAMPLES

Finally, PO5 is caused by the map application in the invariant definition of plant. Herethe set bindings of the two all quantifier expressions form the context:

PO5:[| a : Alarm;

per : Period;plan : Plan;alarms : set of Alarm;a in set alarms;per in set dom plan |]==>

per in set dom plan

Except PO3, all proof obligations can be proven trivially, which means automatically.This demonstrates the advantage of taking the context into account and generate proofobligations.

A.2 Traffic Light

Modelling a traffic light system we define a light as an enumeration type. The traffic lightruns in normal or flashing mode.

types

Light = [<Red> | <Amber> | <Green>];

Mode = <Normal> | <Flashing>;

The time is modelled as a positive real number unequal to zero. Furthermore, a directionis needed, in order to model conflicts of two directions.

Time = realinv t == t > 0;

Direction = token;

Conflict :: dir1: Directiondir2: Direction;

With these type definitions the traffic light can be composed out of lights, a mode, a setof conflicts and a field containing the information, when a direction changed the last time:

TrafficLight :: lights : map Direction to Lightmode : Modeconflicts : set of Conflict

lastchanged: map Direction to Time

Page 95: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

A.2. TRAFFIC LIGHT 83

inv mk_TrafficLight(ls,mode,cs,lc) ==dom ls = dom lc andforall c in set cs & ls(c.dir1) = <Red> or

ls(c.dir2) = <Red>

Then, the three timing variables are defined:

values

RedClearance : Time = 2;

MinimumGreen : Time = 1;

AmberChange : Time = 2

The functionality of a traffic light system is specified by the functions to switch to thethree lights of a given direction. In the function body the given direction is switched tothe light by overriding the lights map. The pre-conditions define the safety requirementsfor switching a direction to a certain colour:

functions

ToGreen: Direction * TrafficLight * Time -> TrafficLightToGreen(d,mk_TrafficLight(lights,mode,conflicts,lastc),clock) ==

mk_TrafficLight(lights ++ {d |-> <Green>},mode,conflicts,lastc)

pre mode = <Normal> andd in set dom lights andlights(d) = <Red> andforall mk_Conflict((d),d2) in set conflicts &

lights(d2) = <Red> andRedClearance < clock - lastc(d);

ToRed: Direction * TrafficLight * Time -> TrafficLightToRed(d,traffic,clock) ==

mk_TrafficLight(traffic.lights ++ {d |-> <Red>},traffic.mode,traffic.conflicts,traffic.lastchanged)

pre traffic.mode = <Normal> andd in set dom traffic.lights andtraffic.lights(d) = <Amber> andAmberChange < clock - traffic.lastchanged(d);

Page 96: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

84 APPENDIX A. MORE EXAMPLES

ToAmber: Direction * TrafficLight * Time -> TrafficLightToAmber(d,traffic,-) ==mk_TrafficLight(traffic.lights ++ {d |-> <Amber>},

traffic.mode,traffic.conflicts,traffic.lastchanged)

pre traffic.mode = <Normal> andd in set dom traffic.lights andtraffic.lights(d) = <Green>

A.2.1 Proof Obligations

The first three POs ensure that the value definitions satisfy the Time invariant.

PO1:inv_Time(2)

PO2:inv_Time(1)

PO3:inv_Time(2)

Proof obligation PO4 is caused by the switching function ToRed, which expects a returnvalue of the invariant type TrafficLight. Therefore, the function body must satisfy theinvariant:

PO4:[| d : Direction;

clock : Time;traffic : TrafficLight;traffic.mode = <Normal> andd in set dom traffic.lights andtraffic.lights(d) = <Amber> andAmberChange < clock-traffic.lastchanged(d) |]==>inv_TrafficLight(mk_TrafficLight(traffic.lights ++ {d |-> <Red>},

traffic.mode,traffic.conflicts,traffic.lastchanged))

Furthermore, a map application is used in the pre-condition of ToRed, which raises PO5.Note, how the other conjuncts form the assumptions of this proof obligation.

PO5:

Page 97: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

A.2. TRAFFIC LIGHT 85

[| d : Direction;traffic : TrafficLight;traffic.mode = <Normal> and d in set dom traffic.lights |]

==>d in set dom traffic.lights

PO6:[| d : Direction;

traffic : TrafficLight;traffic.mode = <Normal> andd in set dom traffic.lights andtraffic.lights(d) = <Amber> |]

==>d in set dom traffic.lastchanged

PO6 is generated due to the map application in the pre-condition in ToRed. PO7 is theinvariant proof obligation for the function body of ToAmber and PO8 is the belongingpre-condition proof obligation.

PO7:[| d : Direction;

traffic : TrafficLight;traffic.mode = <Normal> andd in set dom traffic.lights andtraffic.lights(d) = <Green> |]

==>inv_TrafficLight(mk_TrafficLight(traffic.lights ++ {d |-> <Amber>},

traffic.mode,traffic.conflicts,traffic.lastchanged))

PO8:[| d : Direction;

traffic : TrafficLight;traffic.mode = <Normal> and d in set dom traffic.lights |] ==>

d in set dom traffic.lights

PO9 is the proof obligation belonging to the function body of ToGreen. Furthermore, PO10is caused by the map application lights(d) in the pre-condition of ToGreen.

PO9:[| d : Direction;

mode : Mode;clock : Time;lastc : map Direction to Time;

Page 98: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

86 APPENDIX A. MORE EXAMPLES

lights : map Direction to Light;conflicts : set of Conflict;mode = <Normal> and d in set dom lights and lights(d) = <Red> andforall mk_Conflict((d), d2) in set conflicts &lights(d2) = <Red> and RedClearance < clock-lastc(d) |]

==>inv_TrafficLight(mk_TrafficLight(lights ++ {d |-> <Green>},

mode,conflicts,lastc))

PO10:[| d : Direction;

mode : Mode;lights : map Direction to Light;mode = <Normal> and d in set dom lights |]

==>d in set dom lights

PO11 ensures that the pattern can match in the all quantifier expression in ToGreen.Furthermore, the two map application in this quantifier expression cause PO12 and PO13.

PO11:[| d : Direction;

mode : Mode;lights : map Direction to Light;conflicts : set of Conflict;mode = <Normal> andd in set dom lights andlights(d) = <Red> |]

==>exists d2: Direction & mk_Conflict(d, d2) in set conflicts

PO12:[| d : Direction;

d2 : Direction;mode : Mode;lights : map Direction to Light;conflicts : set of Conflict;mode = <Normal> and d in set dom lights and lights(d) = <Red>;mk_Conflict(d, d2) in set conflicts |]

==>d2 in set dom lights

PO13:

Page 99: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

A.2. TRAFFIC LIGHT 87

[| d : Direction;d2 : Direction;mode : Mode;lastc : map Direction to Time;lights : map Direction to Light;conflicts : set of Conflict;mode = <Normal> and d in set dom lights and lights(d) = <Red>;mk_Conflict(d, d2) in set conflicts;lights(d2) = <Red> |]

==>d in set dom lastc

The two last proof obligations are generated because of the two map applications in theinvariant definition of TrafficLight. Due to the logical approach of asymmetric LPF,PO15 has the negated disjunct as context information, but not PO14.

PO14:[| c : Conflict;

cs : set of Conflict;lc : map Direction to Time;ls : map Direction to Light;dom ls = dom lc;c in set cs |]

==>c.dir1 in set dom ls

PO15:[| c : Conflict;

cs : set of Conflict;lc : map Direction to Time;ls : map Direction to Light;dom ls = dom lc;c in set cs;not ls(c.dir1) = <Red> |]

==>c.dir2 in set dom ls

Page 100: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

Index

Assertion, 63Location, 64

acceptance, 14, 41Ada, 7, 11AllExpr, 25assertion, 63average, 64

B, 6Backus-Naur form, 9BNF, 9

cases expressions, 60CheckBasicApply, 46compatibility

definite, 19possible, 17

conclusion, 24conditional type checking, 24consistency, 12, 69context, 13, 21, 24, 31, 64

generation, 25kinds, 25local, 65

definedness, 69definite mode, 16division, 44, 50domain checking, 45

environment, 16, 25EVES, 7expressions, 41

in statements, 65

formal method, 2formal methods

benefits, 2definition, 2goal, 2

functionapplication, 46implicit, 32

gateway, 26proof obligations, 30specification, 27

GenName, 58guided tour, 23

head, 30, 47hypothesis, 25

IFAD VDM-SL Toolbox, 5invariants, 31iota, 51Isabelle, 6, 58IsCompatible, 17ISO, 4IsOverlapping, 18IsSubType, 19

let expression, 56LPF, 69

mapapplication, 51distributed merge, 49inverse, 49iteration, 50merge, 48

modulo, 50monads, 70

natural deduction, 33

88

Page 101: A Proof Obligation Generator for the IFAD VDM-SL · PDF fileA Proof Obligation Generator for the IFAD ... in this thesis have also been presented at the TIAPS Workshop held at IFAD

INDEX 89

NDS, 33

operation, 63operations

implicit, 63overlapping, 16, 17, 43

partial operator, 30, 45pattern, 53

don’t care, 57to expression, 58type checking, 54

Pattern2Expr, 59POG

interaction, 24possible mode, 16pre-condition, 45PrfRule, 25Proof, 33proof

rules, 33proof obligations, 20, 24PVS, 6

RAISE, 6reasoning

backwards, 34forward, 34

rejection, 14, 41remainder, 50

satisfiability, 33semantics, 9

axiomatic, 11denotational, 10dynamic, 10operational, 10static, 10

sequenceapplication, 30modification, 51

Sequent, 25sequent, 25, 65SPARK, 7statements, 65

strategy, 14subtype, 13, 31

tail, 30, 47termination, 6, 12, 69theorem

prover, 6, 58unproven, 7, 21

TIAPS, 5toolbox, 5turnstile, 25, 65type

invariant, 13type binding, 57, 58type compatibility, 43type judgement, 25, 43, 44TypeJudgement, 25types, 12

invariants, 31

undecidability, 13unique names, 57

validation, 7VDM, 4VDM-SL, 4verification, 2, 4, 21

well-formedness, 41wf-NUMDIV, 42wf-NUMDIV-POG, 43wf-Pattern, 55wf-PatternName, 55wf-SetEnumPattern, 56

Z/EVES, 7