Politecnico di Milano Advanced Topics in Software Engineering JML in a Nutshell Domenico Bianculli & Alessandro Monguzzi {bianculli,

Slides:



Advertisements
Similar presentations
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 18 Program Correctness To treat programming.
Advertisements

Automated Theorem Proving Lecture 1. Program verification is undecidable! Given program P and specification S, does P satisfy S?
Rigorous Software Development CSCI-GA Instructor: Thomas Wies Spring 2012 Lecture 6 Disclaimer. These notes are derived from notes originally.
Rigorous Software Development CSCI-GA Instructor: Thomas Wies Spring 2012 Lecture 8.
By Karen Richart. The Object Constraint Language (OCL)  Formal specification language that could be used for constraining the model elements that occur.
Verifying Executable Object-Oriented Specifications with Separation Logic Stephan van Staden, Cristiano Calcagno, Bertrand Meyer.
The Java Modeling Language JML Erik Poll Digital Security Radboud University Nijmegen.
Data Abstraction II SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
Copyright © 2006 Addison-Wesley. All rights reserved.1-1 ICS 410: Programming Languages Chapter 3 : Describing Syntax and Semantics Axiomatic Semantics.
ISBN Chapter 3 Describing Syntax and Semantics.
Dept. of Computer Science A Runtime Assertion Checker for the Java Modeling Language (JML) Yoonsik Cheon and Gary T. Leavens SERP 2002, June 24-27, 2002.
1 Design by Contract with JML CS 3331 Fall 2009 Gary T. Leavens and Yoonsik Cheon. Design by Contract with JML. Available from
Formal Methods of Systems Specification Logical Specification of Hard- and Software Prof. Dr. Holger Schlingloff Institut für Informatik der.
Formal Methods of Systems Specification Logical Specification of Hard- and Software Prof. Dr. Holger Schlingloff Institut für Informatik der Humboldt.
Object Oriented Design An object combines data and operations on that data (object is an instance of class) data: class variables operations: methods Three.
An overview of JML tools and applications Lilian Burdy Gemplus Yoonsik Cheon, Gary Leavens Iowa Univ. David Cok Kodak Michael Ernst MIT Rustan Leino Microsoft.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 18 Program Correctness To treat programming.
1 Specifying Object Interfaces. 2 Major tasks in this stage: --are there any missing attributes or operations? --how can we reduce coupling, make interface.
JML and Class Specifications Class invariant JML definitions Queue example Running JML in Eclipse.
OOP #10: Correctness Fritz Henglein. Wrap-up: Types A type is a collection of objects with common behavior (operations and properties). (Abstract) types.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 18 Program Correctness To treat programming.
Describing Syntax and Semantics
Subclasses and Subtypes CMPS Subclasses and Subtypes A class is a subclass if it has been built using inheritance. ▫ It says nothing about the meaning.
Ranga Rodrigo. Class is central to object oriented programming.
Software Engineering Prof. Dr. Bertrand Meyer March 2007 – June 2007 Chair of Software Engineering Static program checking and verification Slides: Based.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
111 The Java Modeling Language Based on: Gary T. Leavens, et al., JML Tutorial at OOPSLA Gary. T Leavens, et al., Preliminary Design of JML: A Behavioral.
Computer Science and Engineering College of Engineering The Ohio State University Interfaces The credit for these slides goes to Professor Paul Sivilotti.
EECE 310: Software Engineering Iteration Abstraction.
Design by Contract in Java Concept and Comparison.
Low-Level Detailed Design SAD (Soft Arch Design) Mid-level Detailed Design Low-Level Detailed Design Design Finalization Design Document.
ISBN Chapter 3 Describing Semantics -Attribute Grammars -Dynamic Semantics.
CS 363 Comparative Programming Languages Semantics.
Today’s Agenda  Quick Review  Continue on JML Formal Methods in Software Engineering1.
A Survey on Java Modeling Languages Gergely Kovásznai,Eszterházy Károly College Wolfgang Schreiner,Johannes Kepler University Gábor Kusper,Eszterházy Károly.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Chapter 3 Part II Describing Syntax and Semantics.
Semantics In Text: Chapter 3.
Type Abstraction Liskov, Chapter 7. 2 Liskov Substitution Principle In any client code, if the supertype object is substituted by a subtype object, the.
Type Abstraction SWE Spring October 05Kaushik, Ammann Substitution Principle “In any client code, if supertype object is substituted.
Spec# Andreas Vida. Motivation Correct and maintainable software Correct and maintainable software Cost effective software production Cost effective software.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
L13: Design by Contract Definition Reliability Correctness Pre- and post-condition Asserts and Exceptions Weak & Strong Conditions Class invariants Conditions.
1 Assertions. 2 A boolean expression or predicate that evaluates to true or false in every state In a program they express constraints on the state that.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Faithful mapping of model classes to mathematical structures Ádám Darvas ETH Zürich Switzerland Peter Müller Microsoft Research Redmond, WA, USA SAVCBS.
DBC NOTES. Design By Contract l A contract carries mutual obligations and benefits. l The client should only call a routine when the routine’s pre-condition.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
© Bertrand Meyer and Yishai Feldman Notice Some of the material is taken from Object-Oriented Software Construction, 2nd edition, by Bertrand Meyer (Prentice.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 17 – Specifications, error checking & assert.
SWEN421 – Lecture 3 Building High Integrity Software with SPARK Ada
EECE 310: Software Engineering
Design by Contract Jim Fawcett CSE784 – Software Studio
Design by Contract Jim Fawcett CSE784 – Software Studio
Accessible Formal Methods A Study of the Java Modeling Language
Type Abstraction SWE Spring 2009.
Design by Contract Fall 2016 Version.
Specifying Object Interfaces
Programming Languages 2nd edition Tucker and Noonan
Hoare-style program verification
Semantics In Text: Chapter 3.
SWE 619 Software Construction Last Modified, Fall 2015 Paul Ammann
Java Modeling Language (JML)
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
Type Abstraction SWE Spring 2013.
Programming Languages 2nd edition Tucker and Noonan
Programming Languages 2nd edition Tucker and Noonan
Presentation transcript:

Politecnico di Milano Advanced Topics in Software Engineering JML in a Nutshell Domenico Bianculli & Alessandro Monguzzi {bianculli, June 16th, 2005 Rev. 1.3

JML in a Nutshell 2 Outline What is JML? Syntax Specification cases Advanced topics Running example Tools Related works

JML in a Nutshell 3 What is JML? Java Modeling Language A behavior interface specification language (BISL) describes: –modules interface –modules behaviour evolution of Hoare-style specification based on Design by Contract

JML in a Nutshell 4 Syntax Annotations Expressions Quantification

JML in a Nutshell 5 Syntax: annotations Specification written as annotation comments Single line: … specification … Multiline: … Informal: informal description *)

JML in a Nutshell 6 Syntax: expressions Expression used in JML annotations cannot have side effects. –No use of =, +=, ++, -- … –Can only call pure methods Extended version of Java expressions ExpressionMeaning a ==> ba implies b a <== ba follows from b a ba if and only if b a b not ( a if and only if b ) \old(E) value of E in pre-state \result result of method call

JML in a Nutshell 7 universal & existential ( \forall, \exists ) \forall int x >= 0 && x < a[x-1] <= general quantifiers ( \sum, \product, \min, \max ) numeric quantifier ( \num_of ) Syntax: quantification declaration range body

JML in a Nutshell 8 Preconditions Say what must be true when calling a method Introduced by requires clause public double sqrt(double x);

JML in a Nutshell 9 Normal postconditions Say what must be true when a method returns normally (i.e. without throwing exceptions) Introduced by ensures clause requires x>= ensures x - \result * \result <= public double sqrt(double x); Input parameters in postconditions are always evaluated in pre-state x ≡ \old(x)

JML in a Nutshell 10 Exceptional postconditions Say what must be true when a method throws an exception of type T Introduced by signals clause requires x>= ensures x - \result * \result <= signals (IllegalArgumentException ex.getMessage() != null && !(x public double sqrt(double x);

JML in a Nutshell 11 More on exceptional postconditions (1) Note that signal clause does not say which exceptions must be thrown It just only says “… if an exception of (sub)type T is thrown, then its predicate must hold” and not viceversa. The signals_only clause specifies what exceptions may be thrown, and implicitly the ones which cannot be thrown.

JML in a Nutshell 12 More on exceptional postconditions (2) To say that an exception must be thrown in some situations, exclude that situations from other signals clauses and from all ensures clauses requires ensures x>=0 signals (Exception x<0 && public int foo(int x) throws Exceptions; More on this topic later…

JML in a Nutshell 13 Semantics Meaning of JML method specification –A method is called in a state (pre-state) where the precondition is satisfied; otherwise, nothing is guaranteed, including the termination of the call –If a method is called in a proper pre- state, then there are two possible outcomes (post-state) of method’s execution: normal and exceptional

JML in a Nutshell 14 Kinds of specification & specification cases Specification cases –Lightweight –Heavyweight Behaviour Normal Behaviour Exceptional Behaviour

JML in a Nutshell 15 Heavyweight vs lightweight specs Heavyweight Assumes users giving full specification Omitted clauses are abbreviations Useful for formal verification Lightweight Don’t assume user is giving full specification Minimize annotation burden Omitted clauses are \not_specified Useful for RAC and docs

JML in a Nutshell 16 Additional Clauses diverge says that a method may not return to its caller when allows concurrency aspects of a method assignable lists non local variables that can be assigned in the method body; limits methods possible side effects capture lists object refs that can be retained after the method return duration specifies the maximum time needed to process a method call accessible lists memory locations that methods may access callable lists methods that can be called by the method under specification

JML in a Nutshell 17 Heavyweight specs: behavior requires diverges assignable when ensures signals (E1 signals (En en) accessible callable

JML in a Nutshell 18 Heavyweight specs: normal behavior It is a behavior specification case with signals clause implicitly defined as signals (java.lang.Exception) false; guarantees normal termination  no exception may be thrown

JML in a Nutshell 19 Heavyweight specs: exceptional behavior It is a behavior specification case with ensures clause implicitly defined as ensures false; Guarantees that the method throws an exception

JML in a Nutshell 20 Multiple cases specs Normal and exceptional spec cases may be combined public requires assignable size, ensures && \result == public requires assignable signals_only public Object pop();

JML in a Nutshell 21 Class invariants Properties that must hold in all visible states of an object public invariant x != null && !name.equals(“”); Static or Instance invariants Implicitly included in preconditions and normal and exceptional postconditions Do not hold for methods declared with clause helper private invariants state Rep Invariant

JML in a Nutshell 22 Loop (in)variants Loop statements can be annotated with loop invariants and variant functions. Help in proving partial and total correctness of the loop statement long sum = 0; int[] a = new int[100]; int i = a.length; mantaining -1 =0) sum += a[i];

JML in a Nutshell 23 Assertions An assertion is a predicate that must always be true assert i>0 w.r.t. Java 1.4+ assert JML assertions cannot have any side- effects and can use JML expressions.

JML in a Nutshell 24 History Constraints “Relationships that should hold for the combination of each visible state and any visible state that occurs later in the program execution” Used to constrain the way the values change over time int a; constraint a == \old(a); boolean[] b; constraint b.lenght >= \old(b.lenght);

JML in a Nutshell 25 Advanced Topics Model fields –Model methods and types –Fields visibility Abstract models Purity Data groups Specification inheritance Refinement

JML in a Nutshell 26 Model fields Represents a field or a variable used only in specification Describes abstract values of objects They can be mapped on a concrete field using keyword represents public class MathFoo { public model eps private float error; private represents eps <- error; }

JML in a Nutshell 27 Visibility JML imposes visibility rules similar to Java Keyword spec_public loosens visibility for specs. Private spec_public fields are allowed in public specs. private double x = 0.0; !Double.isNaN(x+dx) public void moveX(double dx){… Not a good practice! You are exposing internal representation!

JML in a Nutshell 28 Abstract models JML provides a Java class library for specification purposes Package org.jmlspecs.model –Collections: sequence, set, bag –Algebric functions and relations –Exceptions and iterators Almost all are immutable objects with pure methods Can be used during RAC Users can define their own models

JML in a Nutshell 29 Purity A pure method is a method without side effects ( \assignable nothing ) It is declared with the modifier pure A class is pure if all its methods are pure Only pure method are allowed in specifications

JML in a Nutshell 30 Data groups A set of model and concrete fields to which you refer by a specific name A declaration of a model field automatically creates a data group with the same name of the model field The main purpose of a data group is to refer to the elements of this set without exposing their internal representation Locations members of a data group may be assigned during the executions of methods that have permission to assign to the data group public model int public model JMLObjectSequence in

JML in a Nutshell 31 Specification inheritance A subclass inherits specifications of its superclass and of its implemented interfaces –All instance model fields –Instance method specifications –Instance invariants and instance history constraints Specifications of a superclass are conjuncted with new specs with the clause also Support behavioural notion of subtyping, accordingly to Liskov’s substitution principle: –preconditions are disjoined –postconditions are conjoined as ∩ (old(pre i ) -> post i ) –invariants are conjoined

JML in a Nutshell 32 Refinement files Specifications can be separated from implementations Specs are written in a file Foo.java-refined Implementation is written in file Foo.java which contains the clause refine “Foo.java-refined” Useful for adding specifications to existing code

JML in a Nutshell 33 Example: IntSet Informal specification “ IntSets are unbounded sets of integers with operations to create a new empty IntSet, test whether a given integer is an element of an IntSet, and add or remove elements.”

JML in a Nutshell 34 IntSet à la Liskov (1) public interface IntSet { public void insert(int x) //MODIFIES: this //EFFECTS: Adds x to the elements of this public void remove(int x) //MODIFIES: this //EFFECTS: Removes x from this public boolean isIn(int x) //EFFECTS: If x is in this returns true, else returns false. } Mutator Observer

JML in a Nutshell 35 IntSet à la Liskov (2) public class IntSetAs_list implements IntSet{ … private Vector els; public IntSetAs_list(){ //EFFECTS: Initializes this to be empty. els = new Vector(); } … } Abstraction Function AF(c) = {c.els.get(i).intValue | 0 <= i < c.els.size} Representation Invariant c.els != null && for all integers i (0 c.els.get(i) is an Integer) && for all integers i, j | (0 c.els.get(i).intValue != c.els.get(j).intValue)

JML in a Nutshell 36 public interface IntSet { public model instance JMLValueSet public initially theSet != null && public instance invariant theSet != && (\forall JMLType e; e instanceof /** Insert the given integer into this set. */ public assignable ensures theSet.equals(\old(theSet.insert(new public void insert(int elem); /** Tell if the argument is in this set. */ public ensures \result == theSet.has(new public boolean isIn(int elem); /** Remove the given integer from this set. */ public assignable ensures theSet.equals( \old(theSet.remove(new JMLInteger(elem))) public void remove(int elem);} IntSet in JML (1) Model Field Abstract Invariant

JML in a Nutshell 37 import java.util.*; model import org.jmlspecs.models.*; public class IntegerSetAsList implements IntSet { private Vector els; in theSet; private invariant els != null (\forall int i; 0<=i && i<els.size(); els.get(i) != null els.get(i) instanceof Integer (\forall int j=0; i<j && j<els.size(); els.get(i) != private represents theSet <- abstractValue(); /** Return the abstract value of this IntegerSetAsList. private pure model JMLValueSet abstractValue() JMLValueSet ret = new Iterator iter = while (iter.hasNext()) ret = IntSet in JML (2) Abstraction Function Rep Invariant

JML in a Nutshell 38 IntSet in JML (3) /** Initialize this set to be the empty set. */ public assignable ensures theSet != null && public IntegerSetAsList() { els = new Vector(); } public boolean isIn(int i) { return els.contains(new Integer(i)); } public void insert(int i) { els.add(new Integer(i)); } public void remove(int i) { els.remove(new Integer(i)); }

JML in a Nutshell 39 Tools Parsing & Typechecking Runtime assertion checking Testing Documentation Extended static checking Program verification

JML in a Nutshell 40 jmlc The JML compiler Translates Java code with JML assertions into bytecode Adds runtime checks: –During execution, all assertions are tested and any violation of an assertion produces an Error (uses jmlrac script).

JML in a Nutshell 41 jmlunit Inserts support for JML within JUnit Writes out a JUnit test oracle for given Java files Specifications are used to check whether tested code runs properly  Tests are only as good as the quality of the specifications!

JML in a Nutshell 42 jmldoc Produces HTML pages with API and JML specifications for Java classes

JML in a Nutshell 43 ESC/Java Extended Static Checker for Java Tries to prove correctness of specifications at compile-time, fully automatically Not sound: it may miss an error that is actually present Not complete: it may warn of errors that are impossible It finds a lot of potential bugs quickly: –NullPointer, ArrayIndexOutOfBounds, ClassCast…

JML in a Nutshell 44 LOOP Logic of Object Oriented Programming, project of University of Nijmegen Based on a formalization of Java and JML semantics in the theorem prover PVS LOOP compiler translates JML annotations in PVS proof obligations, to be proved interactively

JML in a Nutshell 45 Related Works Early programming languages –Gypsy –Alphard –Euclid –CLU DBC based –Eiffel –SPARK –B method OCL from UML Spec#

JML in a Nutshell 46 Conclusions Strenghts Easy to learn Source code is the formal model –Gradual introduction –Support for legacy code Wide range of tools Weakenesses No support for: –concurrency –object invariants within callbacks –modeling alias relationships Strong definition of pure methods: –many constraints

JML in a Nutshell 47 References