Slide 1 Introduction to the Z Formal Specifications Language.
-
Upload
bethanie-hunter -
Category
Documents
-
view
218 -
download
0
Transcript of Slide 1 Introduction to the Z Formal Specifications Language.
Slide 1
Introduction to the Z Formal Specifications Language
Slide 2
Z as a specification language A formal specification notation based on set
theory Has been developed at the Programming
Research Group at the Oxford University Computing Laboratory since the late 1970s.
Probably now the most widely-used specification language
An international standard for the Z notation is being developed under the guidance of ISO.
Slide 3
Z as a specification language
Specification are built from components called schemas.
Schemas are specification building blocks Graphical presentation of schemas make Z
specifications easier to understand Mathematical notation of schemas allows the
building of formal completeness and consistency proofs to validate the specifications
Slide 4
Z schemas Introduce specification entities and defines
invariant predicates over these entities A predicate is a Boolean expression Some predicates can have side-effects that change
the state of the entities involved Schemas can be included in other schemas and
may act as type definitions Names are local to schemas In many respects, Z schemas are akin to objects.
Slide 5
Problem: storage tank monitoring A storage tank is monitored by a control system. The system consists of a container which holds
something and a indicator panel which shows the current fill level and the danger level.
If the storage tank goes over the danger level, a warning light must be lighted on the indicator panel.
Fill operations must be specified as to ensure the tank to be refilled but never overfilled.
Slide 6
A container specification
contents <= capacity
Containercontents: Ncapacity: N
Schema variable declarations
Schema predicatesSchema name
Container [contents: N; capacity: N | contents <= capacity]
Slide 7
The Z Notation
A schema includes A name identifying the schema A signature introducing entities and their types A predicate part defining relationships between the entities in
the signature by stating a logical expression which must always be true (an invariant).
Slide 8
An indicator specification
light = on reading >= dangerLevel
Indicator
light: {off, on}reading: N dangerLevel: N
If the storage tank goes over the danger level, a warning light must be lighted on the indicator panel.
Slide 9
Specification of a storage tank
reading = contentscapacity = 250000danger_level = 245000
StorageTank
ContainerIndicator
Slide 10
Specification of a storage tank
contents <= capacitylight = on reading >= dangerLevelreading = contentscapacity = 250000danger_level = 245000
StorageTank
contents: Ncapacity: N reading: N dangerLevel: Nlight: {off, on}
Slide 11
A partial spec. of a fill operation
contents + amount? <= capacitycontents’ = contents + amount?
FillOK
StorageTankamount?: N
Slide 12
Z conventions
A schema name prefixed by the Greek letter Delta () means that the operation changes some or all of the state variables introduced in that schema
A variable name decorated with a ? represents an input
A variable name decorated with a quote mark (N’) represents the value of the state variable N after an operation
Slide 13
Z conventions
A schema name prefixed by the Greek letter Xi () means that the defined operation does not change the values of state variables
A variable name decorated with a ! represents an output
Slide 14
A partial spec. of a fill operation
contents + amount? <= capacitycontents’ = contents + amount?
FillOK
StorageTankamount?: N
Slide 15
Storage tank fill operation
capacity < contents + amount?r! =“Insufficient tank capacity – Fill cancelled”
OverFill
StorageTankamount?: N r!: seq CHAR
Fill
FillOK OverFill
Slide 16
Full problem specificationContainer [content: N; capacity: N | content <= capacity]
Indicator [light:{off,on};reading: N; dangerLevel: N | light = on reading >= dangerLevel]
StorageTank [Container; Indicator | reading=content; capacity=250000; dangerLevel = 245000]
FillOK [StorageTank; amount?: N | contents + amount? <= capacity;
content’ = content + amount? OverFill [StorageTank; amount?: N; r!: seq CHAR | capacity < contents + amount?; r! =“Insufficient tank capacity – Fill cancelled”
Fill [FillOK OverFill]
Slide 17
Operation specification
Define the “normal” operation as a schema Define schemas for exceptional situations Operations may be specified incrementally as
separate schema then the schema combined to produce the complete specification
Combine all schemas using the disjunction (or) operator (written )
Slide 18
Z Notations A schema includes
A name identifying the schema A signature introducing entities and their types A predicate part defining invariants over these entities
Conventions Marks before a schema,
Delta ( means changes Xi means no changes
Marks after a state variable, ? means input ! means output ‘ represents the value of the variable after an operation
Slide 19
Z symbols Sets: S : P X S is a set of XsS : F X S is a finite set of Xsx S x is a member of Sx S x is not a member of SS T S is a subset of TS T union of S and TS T intersection of S and TS \ T difference of S and T empty setN set of natural numbers : {0,1,2, …} Z set of integer numbers : {...-2,-1,0,1,2, …} max(S) maximum value of the (non-empty) set Smin(S) minimum value of the (non-empty) set S#S cardinality of S
Slide 20
Z symbolsFunctions:f : X Y f is a partial function from X to Yf : XY f is a total function from X to Ydom f domain of fran f range of ff : {x1 y1, x2 y2} extensional function definitionf {x1 y1} extensional addition of mappings
Logic:P negationPQ conjunctionPQ disjunctionPQ equivalencePQ implication
Slide 21
Key points Z specifications are made up of a mathematical model of
the system state and a definition of operations on that state
A Z specification is presented as a number of schemas
Schemas may be combined to make new schemas Operations are specified by defining their effect on the
system state. Operations may be specified incrementally. Different
schemas can be combined to complete the specification. The notation used is very cryptic, though great effort is
made toward understandability.
Slide 22
Z Specification Examples
Slide 23
Example 1
Specifications for a
Data Dictionary
Slide 24
Data dictionary specification A data dictionary is used as an example. This is part of a
CASE system and is used to keep track of system names Data dictionary structure
Item name Description Type. Assume in these examples that the allowed types are those used
in semantic data models Creation date
Operations for lookup, addition, replacing, and deletion of entries are to be formally specified.
An operation for extracting and sorting all entity, relation or attribute entries has to be specified.
Slide 25
Given sets
Z does not require everything to be defined at specification time
Some entities may be ‘given’ and defined later The first stage in the specification process is to
introduce these given sets [NAME, DATE] We don’t care about these representations at this stage
Slide 26
Type definitions
There are a number of built-in types (such as INTEGER) in Z
Other types may be defined by enumeration SemModelTypes = { relation, entity, attribute }
Schemas may also be used for type definition. The predicates serve as constraints on the type
Slide 27
Specification using functions
A function is a mapping from an input value to an output value SmallSquare = {11, 24, 39, 416, 525, 636, 749}
The domain of a function is the set of inputs over which the function has a defined result dom SmallSquare = {1, 2, 3, 4, 5, 6, 7 }
The range of a function is the set of results which the function can produce rng SmallSquare = {1, 4, 9, 16, 25, 36, 49 }
Slide 28
Data dictionary modeling A data dictionary may be thought of as a
mapping from a name (the key) to a value (the description in the dictionary)
Operations are Add. Makes a new entry in the dictionary or
replaces an existing entry Lookup. Given a name, returns the description. Delete. Deletes an entry from the dictionary Replace. Replaces the information associated with an entry Extract. Extract and sort by name all entries having a specified
type
Slide 29
Data dictionary entry
#description <= 2000
DataDictionaryEntry
entr y: NAMEdesc: seq chartype: Sem_model_typescreationDate: DATE
Slide 30
Data dictionary as a function
DataDictionary
DataDictionaryEntryddict: NAME {DataDictionaryEntry}
ddict’ = Ø
InitDataDictionary
DataDictionary
Slide 31
Add operation
name? dom ddictddict’ = ddict {name? entry?}
AddSuccess
DataDictionaryname?: NAMEentry?: DataDictionaryEntry
name? dom ddicterror! = “Name already in dictionary”
AddFailure
DataDictionaryname?: NAMEerror!: seq char
Slide 32
Lookup operation
name? dom ddicterror! = “Name not in dictionary”
LookupNotFound
DataDictionaryname?: NAMEerror!: seq char
name? dom ddictentry! = ddict (name?)
LookupFound
DataDictionaryname?: NAMEentry!: DataDictionaryEntry
Slide 33
Function over-riding operator
The replacing entry function uses the function overriding operator (written ). This adds a new entry or replaces and existing entry. phone = { Ian 3390, Ray 3392, Steve 3427} The domain of phone is {Ian, Ray, Steve} and the range is
{3390, 3392, 3427}. newphone = {Steve 3386, Ron 3427} phone newphone = { Ian 3390, Ray 3392,
Steve 3386, Ron 3427}
Slide 34
Replace operation
ddict’ = ddict {name? entry}
Replace
DataDictionaryname?: NAMEentry?: DataDictionaryEntry
Slide 35
Deleting an entry
Uses the domain subtraction operator (written ) which, given a name, removes that name from the domain of the function
phone = { Ian 3390, Ray 3392, Steve 3427} {Ian} phone {Ray 3392, Steve 3427}
Slide 36
Delete entry
name? dom ddictddict’ = {name?} ddict
DeleteFound
DataDictionaryname?: NAME
name? dom ddicterror = “entity specified for deletion does not exist in the dictionary”
DeleteNotFoundDataDictionaryname?: NAMEerror!: seq char
Slide 37
Extracting entities of specific type
1n : dom ddict ddict(n).type = inType? ddict(n) return!
ExtractDataDictionaryinType? : SemModelTypesreturn!: seq {DataDictionaryEntry}
2i : 1 <= i <= #return! return!(i).type = inType?
4i,j : i,j return! (i<j) return!.name(i) <NAME return!.name(j)
3i : 1 <= i <= #return! return!(i) rng ddict
1. For all entries in ddict whose type is inType, there is an entry in return. This does not ensure that all elements of return are elements of ddict, hence the necessity of the next two constraints.2. The type of all members of return is inType. 3. All members of return are members of the range of ddict.4. return is sorted by its name attribute
Slide 38
Add, Lookup and DeleteAdd
AddSuccess AddFailure
Lookup
LookupFound LookupNotFound
Delete
DeleteFound DeleteNotFound
Slide 39
Data dictionary specification
TheDataDictionary
DataDictionaryInitDataDictionaryAddLookupDeleteReplaceExtract
Slide 40
Example 2
Modular Specifications for a
Birthday Book
Slide 41
Birthday book specification
A system which records people’s birthdays Operations include addition and query of
birthdays The system must be able to give a list of
birthdays occuring on any given day
Slide 42
Z schemas Z schemas represent both the static and dynamic
aspects of a system Static
the states it can occupy the invariant relationships (constraints) that are maintained on
the state as its values are changed
Dynamic the operations that are possible on the system state the relationships between operations inputs and outputs the changes of states that happen during the application of
operations
Slide 43
Data dictionary modeling
The database is modeled as a function mapping persons’ names to their birthday dates
Operations are Add. Makes a new entry {name birthday} in the birthday
book Find. Given a name, returns the birthday Remind. Returns a list of the persons having their birthday on a
given date
Slide 44
known = dom birthday
BirthdayBook
known : PP NAMEbirthday : NAME DATE
Birthday book
birthday: is a function which, when applied to a name, gives the birthday associated with it
known: the set of names with birthdays recorded Derived component of the state. Might not be part of the implementation. Gives clarity to the specifications.
Slide 45
Birthday book
Only one constraint is implied: As birthday is defined as a function, each person can only have
one birthday
Does not make any unnecessary assumptions on implementation constraints maximum number of records definition of NAME and DATE ordering of records
Slide 46
Intitial system state
known =
InitBirthdayBook
BirthdayBook
known = dom(birthday), hence if known is empty, birthday is empty.
Slide 47
name? known
AddBirthday
Birthday Bookname? : NAMEdate? : DATE
birthday’ = birthday {name? date?}
Add operation
The schema does not say what happens if the precondition is not met
Complete specifications should take into account all state cases that can arise
Will be settled later in a modular way
Slide 48
Add operation How does this ensure that:
known’ = known {name?}
A proof of it can be derived using the system invariant properties and the inherent properties of dom
The possibility to build such proofs is a major advantage of formal specification techniques
known’ = dom birthday’ [spec of BirthdayBook]= dom(birthday {name? date?})[spec. of AddBirthday]= dom birthday dom {name? date?} [dom distributivity]= dom birthday {name?} [dom definition]= known {name?} [spec. of BirthdayBook]
Slide 49
name? known date! = birthday(name?)
FindBirthday
BirthdayBookname? : NAMEdate! : DATE
Find operation
Including BirthdayBook is equivalent to include predicates known’ = known and birthday’ = birthday
What happens if the name looked for is not in the database? Again, this schema does not provide a complete specification.
Slide 50
Remind operation
cards! = {n : known | birthday(n) = today?}
Remind
BirthdayBooktoday? : DATEcards! : PP NAME
Specifies a definition of the output of the operation with regard with the system state
Does not specify how the search is implemented Exactly specifies the problem to be solved, while leaving
maximal freedom to designers and programmers
Slide 51
Specification completeness The specification does not take into account special state
cases leading to errors Adding a new record for someone already in the system Trying to find a person unknown to the system
Implementing such incomplete specifications will probably lead to a broken system
Designers/programmers will have to invent their own solutions to the problem, which might not be agreed by the client
System might lose some data System might behave correctly, but without giving warnings to the
user on faulty inputs, or give meaningful messages on empty output
Slide 52
Specification completeness
Solution: Develop new schemas to enable the covering of special cases in
all operations Combine these new schemas with the existing ones to form a
robust version of the system specification
Advantages: Provides an incremental and modular description of the
specifications Specifications are easier to understand
Slide 53
Specification completeness Add an extra output result! of type REPORT to each operation
on the system that returns: ok if the operation is successful alreadyKnown or notKnown appropriately if an error happens
The type REPORT is defined as a free definition
Three schemas are defined to provide a definition of the states applying to the output of the appropriate REPORT value
REPORT = {ok,alreadyKnown,notKnown}
Slide 54
Specification completeness
result! = ok
Successresult! : REPORT
name? known result! = alreadyKnown
AlreadyKnownBirthdayBooktoday? : DATEresult! : REPORT
name? known result! = notKnown
NotKnownBirthdayBooktoday? : DATEresult! : REPORT
Slide 55
Complete addition operation
RAddBirthday
BirthdayBookname? : NAMEdate? : DATE
name? known birthday’ = birthday {name? date?}
result! : REPORT
result! = okname? known birthday’ = birthday result! = alreadyKnown
RAddBirthday
(AddBirthday Success) AlreadyKnown
Slide 56
Complete find operation
name? known date! = birthday(name?)
RFindBirthday
BirthdayBookname? : NAMEdate! : DATEresult! : REPORT
result! = okname? known birthday’ = birthday result! = notKnown
RFindBirthday
(FindBirthday Success) NotKnown
Slide 57
Complete remind operation
name? known cards! = {n : known | birthday(n) = today?}
RRemindBirthdayBooktoday? : DATEcards! : PP NAMEresult! : REPORT
result! = ok
RRemind
Remind Success
Slide 58
Key Points Z specifications provide a mathematical model of
a system encompassing both static (state) and dynamic (operations) aspects
Specifications completeness is a key quality to achieve
Completeness can be achieved incrementally using modular schema composition
Incremental composition leads to more manageable and understandable specifications
Slide 59
Z specification examples (part II)
Slide 60
Example: DATE
Slide 61
Format of DATE
Date could have different formats: November 7,2001 11/07/2001 7-11-2001 …
Assume using this format: dd mm yyyy,
with which today is 7 11 2001 do not care about zeroes
Slide 62
Initial suggestion
DATE
day: 1..31month:1..12year: 1900.. 9999
Problems: invalid dates caused by different days in different months leap year year overflow
Slide 63
Definition of leap_year
leap_year: P (N)
year:1990..9999 leap_year(year) (year mod 4 = 0) (year mod 100 0 year mod 400 = 0)
Slide 64
DATE
DATE
day: 1..31month:1..12year: 1900.. 9999
month {2,4,6,9,11} month {4,6,9,11} day 30 month = 2 leap_year(year) day 28 month = 2 leap_year(year) day 29
Slide 65
Example: Radiation Safety interlock system
Slide 66
An Interlock System A safety interlock system is designed to prevent people
from being exposed to radiation. An interlock system:
Ensures that all appropriate radiation areas are clear of personnel prior to the use of radiation sources
Prevents people from entering areas where radiation levels exceed certain limits
Ensures that anyone entering an area where there is significant radiation is exposed to a minimal dose of radiation.
Necessary to control access not only to the directly radiated areas, but also to adjoining areas due to leakage.
Slide 67
Radiation Safety Interlock System
Building a hypothetical system Be able to determine whether rooms are clear of personnel
before activating the radiation source Prevent activation if they are not clear of personnel Assume there is some way of determining when people enter or
leave a room, such as using “magnetic badges”.
Slide 68
Plan of building
3
1
2
RS
Slide 69
Radiation Safety Interlock System The radiation source goes through four phases:
Switched off: RS is switched off People are allowed to access any room
Powered up: RS is powered up Room 1 contains no people. and the door must be locked
Discharged A beam is discharged into room 2 Rooms 1 and 2 must contain no people Door to room 2 locked
Full activated Rooms 1 and 2 and the adjoining room 3 must contain no people.
Slide 70
Types definition
status of the radiation source STATUS ::= SwitchOff | PowerUp | Discharge |Activated
status of the doors DOORS ::= Open | Locked
number of rooms
num_of_rooms: N1
num_of_rooms = 3
1. Declared external to any schema2. Global to any part of the specification declared after it
3. N1: positive natural number ( >0 )
Slide 71
The state of the system
State
num_in_room: seq1 Ndoors: seq1 DOORSstatus_of_system: STATUS
#num_in_room = num_of_rooms#doors = num_of_rooms
1. num_in_room: the number of people in each room2. doors: the number of doors associated with each room, either they are all open, or they are all locked.3. seq1: non-empty sequence
Slide 72
Initial State
Init
State
ran num_in_room = {0} ran doors = {Open}status_of_system = SwitchOff
Initial state All the rooms are empty RS is switched off All doors are open
Slide 73
Enter a room
Enter_room
Stateroom_no?: NN
doors(room_no?) = Opennum_in_room = num_in_room {room_no? num_in_room(room_no?) + 1}doors = doorsstatus_of_system = status_of_system
If a person enters a room, the number of people in that room is incremented.
A person can only enter a room if the relevant doors are open.
The status of radiation source and doors are unaffected.
Slide 74
Leave a room
Leave_room
Stateroom_no?: NN
num_in_room = num_in_room {room_no? num_in_room(room_no?) - 1}doors = doorsstatus_of_system = status_of_system
If a person leaves a room, the number of people in that room is decremented.
Slide 75
Operation of Changing the status
Phase 1
State
status_of_system = SwitchOff num_in_room(1) = 0doors = doors { 1 Locked}status_of_system = PowerUp
Phase 1: the RS goes from “switched off” to “powered up” Room 1 must be clear of people Its door is locked
Slide 76
Operation of Changing the status
Phase 2
State
status_of_system = PowerUp num_in_room(2) = 0doors = doors { 2 Locked}status_of_system = Discharged
Phase2: the RS goes from “powered up” to “discharge” Room 2 must be clear of personnel The appropriate door(s) locked.
• What about room 1?
Slide 77
Operation of Changing the status
Phase 3
State
status_of_system = Discharged num_in_room(3) = 0doors = doors { 3 Locked}status_of_system = Activated
Phase3: the RS goes from “discharge” to “full activated” Room 3 must be clear of personnel The appropriate door(s) locked.
Slide 78
Operation of Changing the status
Deactive
State
dom doors = dom doors ran doors = {Open}status_of_system = SwitchOff
On switching off the system, we can make all rooms available.
Slide 79
Exceptions
What is the response of the system if we attempt to power up while someone is in room 1?
What happens if someone enters a room that is supposed to be locked?
…
Slide 80
Writing Specifications Start from informal descriptions Define the required types Define the state variables Define the relationships
Looking for verbs in the descriptions associated with the objects If possible, build ER diagrams Different levels of abstraction
Define the initial state Identify the operations, define a reasonable system Consider exception Combine