Rigorous Software Development CSCI-GA 3033-011 Instructor: Thomas Wies Spring 2012 Lecture 6 Disclaimer. These notes are derived from notes originally.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 18 Program Correctness To treat programming.
Rigorous Software Development CSCI-GA Instructor: Thomas Wies Spring 2012 Lecture 7.
Rigorous Software Development CSCI-GA Instructor: Thomas Wies Spring 2012 Lecture 12.
Rigorous Software Development CSCI-GA Instructor: Thomas Wies Spring 2013 Lecture 5 Disclaimer. These notes are derived from notes originally.
Chapter 24 Lists, Stacks, and Queues
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
COSC 1P03 Data Structures and Abstraction 10.1 The List If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping.
Rigorous Software Development CSCI-GA Instructor: Thomas Wies Spring 2012 Lecture 10.
Rigorous Software Development CSCI-GA Instructor: Thomas Wies Spring 2012 Lecture 8.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
§3 The Stack ADT 1. ADT A stack is a Last-In-First-Out (LIFO) list, that is, an ordered list in which insertions and deletions are.
Rigorous Software Development CSCI-GA Instructor: Thomas Wies Spring 2012 Lecture 11.
The Java Modeling Language JML Erik Poll Digital Security Radboud University Nijmegen.
 Balancing Symbols 3. Applications
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
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.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
Road Map Introduction to object oriented programming. Classes
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
JML and Class Specifications Class invariant JML definitions Queue example Running JML in Eclipse.
1 CS211, Lecture 20 Priority queues and Heaps Readings: Weiss, sec. 6.9, secs When they've got two queues going, there's never any queue!
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
Ranga Rodrigo. Class is central to object oriented programming.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Chapter 3 List Stacks and Queues. Data Structures Data structure is a representation of data and the operations allowed on that data. Data structure is.
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.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
Inheritance Extending Class Functionality. Polymorphism Review Earlier in the course, we examined the topic of polymorphism. Many times in coding, we.
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.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Comp 249 Programming Methodology Chapter 15 Linked Data Structure – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Spec# Andreas Vida. Motivation Correct and maintainable software Correct and maintainable software Cost effective software production Cost effective software.
Chapter 15 Linked Data Structures Slides prepared by Rose Williams, Binghamton University Kenrick Mock University of Alaska Anchorage Copyright © 2008.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
Implementing ArrayList Part T2 Lecture 6 School of Engineering and Computer Science, Victoria University of Wellington  Thomas Kuehne, Marcus Frean,
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
CSC 243 – Java Programming, Fall, 2008 Tuesday, September 30, end of week 5, Interfaces, Derived Classes, and Abstract Classes.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Modular Decomposition, Abstraction and Specifications
External Scope CECS 277 Mimi Opkins.
Lecture 5:Interfaces and Abstract Classes
Modern Programming Tools And Techniques-I
Creating and Using Objects, Exceptions, Strings
Implementing ArrayList Part 1
Accessible Formal Methods A Study of the Java Modeling Language
Creating and Using Classes
Stacks.
Generic programming in Java
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Fundaments of Game Design
Java Modeling Language (JML)
Programming Languages 2nd edition Tucker and Noonan
Chapter 11 Abstraction - The concept of abstraction is fundamental in
Presentation transcript:

Rigorous Software Development CSCI-GA Instructor: Thomas Wies Spring 2012 Lecture 6 Disclaimer. These notes are derived from notes originally developed by Jochen Hoenicke. They are copyrighted material and may not be used in other course settings outside of New York University in their current form or modified form without the express written permission of one of the copyright holders.

Java Modeling Language (JML) JML is a behavioral interface specification language (BISL) for Java. Proposed by G. Leavens, A. Baker, C. Ruby: JML: A Notation for Detailed Design, 1999 Combines ideas from two approaches: – Eiffel with its built-in language for Design by Contract – Larch/C++ a BISL for C++

JML Syntax: Method Specifications In JML the specification precedes the method requires formula : – The specification only applies if formula holds when method is called. – Otherwise behavior of method is undefined. ensures formula : – If the method exits normally, formula has to hold.

A JML formula is a Java Boolean expression. The following list shows some operators of JML that do not exist in Java: \old(expression) : – the value of expression before the method was called (used in ensures clauses) \result : – the return value (used in ensures clauses). F ==> G : – states that F implies G. This is an abbreviation for !F || G. \forall Type t; condition; formula: – states that formula holds for all t of type Type that satisfy condition. JML Syntax: Formulas

A simple JML method contract requires n >= ensures \result >= public static int factorial(int n) { int result = n; while (--n > 0) result *= n; return result; } JML Example: Factorial

JML Syntax: Method Specifications In JML the specification precedes the method requires formula ensures formula assigns variables : – The method only changes values of variables signals (exception) formula : – If the method signals exception then formula holds. signals_only exceptions : – The method may only throw exceptions that are a subtype of one of the exceptions. – If omitted, method can signal only exceptions that appear in throws clause. diverges formula : – The function may only diverge if formula holds.

Specifying Side Effects Side effects of method calls are not restricted to the state of the object on which the method is invoked. A method can change the heap in an unpredictable way. How can we specify side effects? We add frame conditions to contracts that specify which parts of the heap are not affected by a method call.

The assignable clause restricts the possible changes to the heap. The specification requires x >= assignable ensures \result <= Math.sqrt(x) Math.sqrt(x) < \result + public static int isqrt(int x) { body } expresses that isqrt has no side effects. Specifying Side Effects

Specifying Exceptions signals (IllegalArgumentException) x < signals_only public static int isqrt(int x) { body } If IllegalArgumentException is thrown, x < 0 holds. IllegalArgumentException is the only type of exception that is thrown. If no signals_only clause is specified, JML assumes a sane default value: the method may throw only exceptions it declares with the throws keyword (in this case none). The code is still allowed to throw an error like an OutOfMemoryError or a ClassNotFoundError.

Making Exceptions Explicit public requires x >= assignable ensures \result <= Math.sqrt(x) && Math.sqrt(x) < \result + public requires x < assignable signals (IllegalArgumentException) public static int isqrt(int x) throws IllegalArgumentException { if (x < 0) throw new IllegalArgumentException(); body }

If several specifications are given with also, the method must fulfill all of these specifications. A specification with normal_behavior implicitly has the clause signals (java.lang.Exception) false so the method may not throw an exception. A specification with exceptional_behavior implicitly has the clause ensures false so the method may not terminate normally. Making Exceptions Explicit

Structuring Specifications with also public normal requires x > ensures \return = public normal requires x <= ensures \return = public int foo (int x) { body }

Lightweight vs. Heavyweight Specifications A lightweight specification requires assignable ensures public void foo() throws IOException; is an abbreviation for the heavyweight specification public requires diverges assignable ensures signals_only public void foo() throws IOException;

Pure Methods The specification public boolean isEmpty () { body } is an abbreviation for the specification assignable diverges public boolean isEmpty () { body }

Null References The specification public void foo Object o); is an abbreviation for the specification requires o != null; public void foo (Object o); By default, all references are non_null, i.e. nullable references have to be specified explicitly: public void foo Object o);

JML Syntax: Class Specifications In JML class invariants are also invariant formula : – Whenever a method is called or returns, then formula has to hold. constraint formula : – formula defines a history constraint, i.e. a relation between any states s and s’ such that s’ occurs after s in an execution of the program.

Case Study: Priority Queue Subsystems request timer events and queue them. First timer event is passed to the timer. Priority queue maintains events in its internal data structure.

Priority Queue Interface public interface PriorityQueue { public void enqueue(Comparable o); public Comparable removeFirst(); public boolean isEmpty(); }

Adding Specifications: 1 st Attempt public interface PriorityQueue { public ensures public void enqueue(Comparable o); public requires public Comparable removeFirst(); public boolean isEmpty(); }

Specification Is Incomplete The specification allows undesired behavior: After removeFirst() new value of isEmpty() is undefined. In a correct implementation, after two enqueue() and one removeFirst() the queue is not empty. The specification does not say so. Problem: – The internal state is not visible in the specification – There is not even internal state in an interface!

Adding Model Fields Solution: add a model field that records the size. public interface PriorityQueue { public instance model int size; public invariant size >= 0; public ensures size == \old(size) + public void enqueue(Comparable o); public requires ensures size == \old(size) - public Comparable removeFirst(); public ensures \result == (size == public boolean isEmpty(); }

Model Fields public instance model int size; A model field only exists in specifications. Public model fields can be accessed by specifications of other classes. Only specifications can access model fields (they are read-only). If a model field is accessed in code, the compiler complains.

Visibility in JML public instance model int size;... public ensures \result == (size > public boolean isEmpty(); Why is size public? The external interface must be public. The specification is part of the interface. To understand the specification, one needs to know about size. Therefore, size is public.

Implementing the Specification public class Heap implements PriorityQueue { private Comparable[] elems; private int numElems; private represents size = numElems; public void enqueue(Comparable o) { elems[numElems++] = o;... } public Comparable removeFirst() {... return elems[--numElems]; } public isEmpty() { return numElems == 0; }

Representing Model Fields Every model field in a concrete class must be represented: private represents size = numElems; The representing expression can also call pure methods: private represents size = computeSize();

Obtaining Complete Specifications The specification is still incomplete. Which values are returned by removeFirst() ? We need a model field representing the queue. JML provides useful predefined types to model complex data structures.

Complete Specification of Priority Queue model import org.jmlspecs.models.JMLObjectBag; public interface PriorityQueue { public instance model JMLObjectBag queue; public ensures queue.equals(\old(queue).insert(o)); public void enqueue(Comparable o); public requires ensures \old(queue).has(\result) queue.equals(\old(queue).remove(\result)) (\forall java.lang.Comparable queue.has(o); \result.compareTo(o) <= 0); public Comparable removeFirst(); public ensures \result == public boolean isEmpty(); }

What is JMLObjectBag org.jmlspecs.models.JMLObjectBag is a pure class. A pure class has only pure methods and no references to non-pure classes. Therefore, it can be used in specifications. JML provides many predefined types: release/javadocs/org/jmlspecs/models/package-summary.html release/javadocs/org/jmlspecs/models/package-summary.html

For objects, e.g., \old(this) == this, since \old(this) is the old pointer not the old content of the object this. Why does it work as expected with \old(queue) ? JMLObjectBag is immutable The insert method of JMLObjectBag is declared as public JMLObjectBag Object elem) Compare this to the add method of List: public boolean Object elem) insert returns a reference to a new larger bag. the content of \old(queue) and queue never change but \old(queue) and queue are references to different objects. How Does It Work?

Representing queue using a Model Method import org.jmlspecs.models.JMLObjectBag; public class Heap implements PriorityQueue { private Comparable[] elems; private int numElems; private represents queue = computeQueue(); private model pure non_null JMLObjectBag computeQueue() { JMLObjectBag bag = new JMLObjectBag(); for (int i = 0; i < numElems; i++) { bag = bag.insert(elems[i]); } return bag; }

Representing queue by a Ghost Field model import org.jmlspecs.models.JMLObjectBag; public class Heap implements PriorityQueue { private Comparable[] elems; private int numElems; private ghost JMLObjectBag ghostQueue; private represents queue = ghostQueue; public void enqueue(Comparable o) { set ghostQueue = ghostQueue.insert(o);... } public Comparable removeFirst() {... ghostQueue = ghostQueue.remove(first); return first; }

The assignable Problem model import org.jmlspecs.models.JMLObjectBag; public interface PriorityQueue { public instance model JMLObjectBag queue; public ensures public void Comparable o);... } Compilation produced a warning: >jmlc -Q PriorityQueue.java File "PriorityQueue.java", line 7, character 24 caution: A heavyweight specification case for a non-pure method has no assignable clause [JML] Lets add an assignable clause!

Adding assignable What does the method enqueue change? It changes the model field queue and nothing else. model import org.jmlspecs.models.JMLObjectBag; public interface PriorityQueue { public instance model JMLObjectBag queue; public ensures assignable public void Comparable o);... } However, when compiling Heap.java: File "Heap.java", line 50, character 29 error: Field "numElems" is not assignable by method "Heap.enqueue( java.lang.Comparable )"; only fields and fields of data groups in set "{queue}" are assignable [JML]

Mapping Fields To Model Fields We have to tell JML that elem and numElems are the implementation of the model field queue. There is a special JML syntax to do this: import org.jmlspecs.models.JMLObjectBag; public class Heap implements PriorityQueue { private Comparable[] elems; in queue; private int numElems; in queue; private represents queue = }

Data Groups A data group gives a name to a set of locations without exposing implementation details. Every model field forms a data group. Other fields in the class or in sub-classes can be associated with this data group private Comparable[] elems; in queue; private int numElems; in queue; Methods with specification assignable queue may modify any field in the data group queue.

More About Data Groups There is a special data group objectState, which should represent the object state. All representation fields should be added to this group. Adding a data group to another data group adds all subgroups recursively: public interface PriorityQueue { public instance model JMLObjectBag queue; in objectState;... } After this change numElems and elems are also automatically contained in objectState.

Grouping Fields with Data Groups Data groups are useful to group fields. class Calendar { model JMLDataGroup datetime; in objectState; model JMLDataGroup time, date; in datetime; int day, month, year; in date; int hour, min, sec; in time; int timezone; in objectState; Locale locale; in objectState;... assignable datetime; void setDate(Date date); assignable timezone; void setTimeZone(); }

Data Groups and Visibility Data groups and model fields are useful for resolving visibility issues: class Tree { public model JMLDataGroup content; in objectState; private Node rootNode; in content; assignable content; public void insert(Object o); } Using assignable rootNote would produce an error.