1. Computer Science клуб - Екатеринбург
Март 2012
Fun with Formal Program Semantics
(О формальной семантике программ –
просто)
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 1
Всего слайдов
2. Тема 2: «Основной ингредиент»:
понятие о реализационной семантике
(или как превратить эзотерический
язык TEL в игрушечный язык
программирования ToyPL)
Шилов Николай Вячеславович
03/10/12 2
Всего слайдов
3. Историческая справка
• Минуло почти 45 лет с момента публикации
Робертом В. Флойдом статьи
Assigning Meanings to Programs
(Proc. Symp. Applied Mathematics, Am. Math. Soc., v.19, 1967)
• в которой была сделана первая (и удачная)
попытка разработать математически-точный
метод описания формальной семантики (смысла)
программ.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 3
Всего слайдов
4. Историческая справка
• Уже прошло почти 15 лет после публикации
Дэвидом А. Шмидтом призыва к академической
общественности
On the Need for a Popular Formal Semantics
(ACM SIGPLAN Notices, 1997)
• сделать формальную семантики программ
понятной и доступной широкому кругу
инженеров-программистов.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 4
Всего слайдов
5. Историческая справка
• После таких призывов академическая активность
в попытках обобщить, сделать доступной и
полезной формальную семантику, представить
свой «взгляд с высоты» нарастала, в неё
включались всё новые учёные.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 5
Всего слайдов
6. Историческая справка
• Например, Петер Д. Мозес в 2001 г. в обзоре
The Varieties of Programming Language Semantics
And Their Uses
(A.P. Ershov International Conference «Perspectives of System Informatics»)
• пропагандировал свой подход к многообразию
формальных семантик и путях их использования.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 6
Всего слайдов
7. Историческая справка
• Аннотация доклада гласит: This paper surveys the
main frameworks available for describing the
dynamic semantics of programming languages. ...
The paper is intended to be accessible to all
computer scientists. Familiarity with the details of
particular semantic frameworks is not required,
although some understanding of the general
concepts of formal semantics is assumed.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 7
Всего слайдов
8. Историческая справка
• В следующем 2002 г. известный учёный Патрик
Кузо опубликовал журнальную статью
Constructive Design of a Hierarchy of Semantics
of a Transition System by Abstract Interpretation
(Theor. Comp. Sci., 2002)
• в которой строит иерархию формальных
семантик.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 8
Всего слайдов
9. Историческая справка
• The hierarchy includes the maximal trace semantics
of a transition system, big-step semantics,
termination and nontermination semantics, Plotkin’s
natural, Smyth’s demoniac and Hoare’s angelic
relational semantics and equivalent nondeterministic
denotational semantics, D. Scott’s deterministic
denotational semantics, generalized and Dijkstra’s
conservative/liberal predicate transformer
semantics, generalized/total and Hoare’s partial
correctness axiomatic semantics.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 9
Всего слайдов
10. Историческая справка
• All the semantics are presented in a uniform fixpoint
form and the correspondences between these
semantics are established through composable
Galois connections, each semantics being formally
calculated by abstract interpretation of a more
concrete one using Kleene and/or Tarski fixpoint
approximation transfer theorems.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 10
Всего слайдов
11. Историческая справка
• Но наука не стоит на месте, и одновременно с
попытками бросить взгляд с высоты на картину,
которую представляют сложившиеся к XXI веку
семантические формализмы, продолжают
появляться новые семантические парадигмы.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 11
Всего слайдов
12. Историческая справка
• Например, так называемая теоретико-игровая
семантика Самсона Абрамского и Чих-Хао Лук
Онга. Причём, авторы этой семантики
утверждают, что данный формализм готов (в
смысле «дозрел») для моделирования и
верификации программного обеспечения:
Applying game semantics to compositional software
modeling and verication
(Tools and Algorithms for Construction and Analysis of Systems, 2004)
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 12
Всего слайдов
13. Лирическое отступление:
зачем всё это надо?
• Но по прежнему «значительно больше экспертов-
теоретиков, чем практикующих инженеров-
программистов» (Д.А. Шмидт, 1997).
• Поэтому в январе 2010 г. Дэвид Л. Парнас в статье
Really Rethinking «Formal Methods» предложил: «Мы
должны подвергнуть сомнению предположения,
лежащие в основе хорошо известных современных
формальных методов разработки программного
обеспечения, чтобы понять, почему они не получили
широкого распространения, и что в них следует
изменить».
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 13
Всего слайдов
14. М.В. Ломоносов:
«Математику уж затем любить надо,
что она ум в порядок приводит»
• Но, может быть, значение формальных методов в
программировании (формальной семантики в
том числе) не сводится к моделированию и
верификации программного обеспечения?
• Формальные методы (формальная семантики в
частности) выполняют туже роль, что и
математика в воспитании мышления: они
дисциплинирует ум программистов и в порядок
его приводят.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 14
Всего слайдов
15. Как превратить TEL
в язык программирования
• We want to make a programming language with the
same syntax as TEL by providing a programming
semantics for it.
• As a result, we will get another language that we
would refer to as Toy Programming Language ToyPL:
its syntax is the same, but ToyPL and TEL are
different languages since they have different
semantics.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 15
Всего слайдов
16. Основной ингредиент:
виртуальная машина
• Since a programming language is a language for
organization of automatic data processing, the best
way to represent programming language is to
describe its implementation semantics, how it works
on a “computer”, what processes of data
transformation are defined by its programs on this
platform. Since we have no any particular target
platform in mind, we have to define ToyPL virtual
machine.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 16
Всего слайдов
17. Основной ингредиент:
виртуальная машина
• A virtual machine is an abstract computer with
instruction set executable (interpretable) at any
conventional computer platform.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 17
Всего слайдов
18. Основной ингредиент:
виртуальная машина
• Mendel Rosenblum wrote (ACM Queue, 2004):
– The term virtual machine initially described a
1960s operating system concept: a software
abstraction with the looks of a computer system’s
hardware (real machine).
– Forty years later, the term encompasses a large
range of abstractions — for example, Java virtual
machines that don’t match an existing real
machine.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 18
Всего слайдов
19. Основной ингредиент:
виртуальная машина
– Despite the variations, in all definitions the virtual
machine is a target for a programmer or
compilation system. In other words, software is
written to run on the virtual machine.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 19
Всего слайдов
20. ToyPL-VM:
виртуальная машина для ToyPL
• The instruction set of ToyPL-VM consists of (labeled)
operators of the following two kinds:
– assignment “<label> : <variable> :=
<expression> goto <label> ;
– choice <label> : <condition> then <label> else
<label> ;
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 20
Всего слайдов
21. ToyPL-VM:
виртуальная машина для ToyPL
• Example of ToyPL-VM program sample.exe:
0: if z<0 then 1 else 2;
1: z:= -1 goto 8;
2: x:= 0 goto 3;
3: y:= 0 goto 4;
4: if y≤z then 5 else 7;
5: y:= y+2*x+1 goto 6;
6: x:= x+1 goto 4;
7: x:= x-1 goto 8;
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 21
Всего слайдов
22. ToyPL-VM:
виртуальная машина для ToyPL
• Let N ≥ 1 be some fixed integer parameter that
characterizes the bit-size of our virtual machine’s
word.
• Assume that S is a program of ToyPL-VM and let V
AR(S) be the set of all variables that occur in S .
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 22
Всего слайдов
23. ToyPL-VM:
виртуальная машина для ToyPL
• A state (of S) is a total function s : V AR(S) → Z/2N
that assigns every variable x∈V AR(S) some residuals
in Z/2N , i.e. an integer number s(x)∈[0...(2N −1)].
• A configuration (of S) is a pair of the form (label,
state), where label has instance(s) in S (i.e. marks any
operator, or occurs after goto, then or else in some
operator).
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 23
Всего слайдов
24. ToyPL-VM:
виртуальная машина для ToyPL
• Let l: x:=t goto l′ be an assignment within S. A firing
of the assignment is any pair of configurations (l, s), (l
′ , upd(s, x, s(t)), where upd = λf:A→B. λa∈A.
λb∈B.
(λx∈A. (if x=a then b else f(x)).
• Упражнение #1: s(t) – значение выражения t в
состоянии s. Дайте формальное
определение.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 24
Всего слайдов
25. ToyPL-VM:
виртуальная машина для ToyPL
• Let l: ϕ then l+ else l− be a choice within S.
A firing of the choice is any pair of configurations (l,
s), (l′, s), where s is a state and l′ is a label in {l+,
l−} such that l′=l+, if s|=ϕ (i.e. ϕ holds in the state
s), and l′=l− otherwise.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 25
Всего слайдов
26. ToyPL-VM:
виртуальная машина для ToyPL
• A computational step (of S) is a firing of any
assignment or choice within this program.
• Let a computation (of S) be any finite or infinite
sequence of configurations (l0 , s0 ), . . . (li , si ), ,
(l(i+1) , s(i+1) ), . . . such that every pair of consequent
configurations (li , si ) , (l(i+1) , s(i+1)) within this
sequence is a computational step.
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 26
Всего слайдов
27. ToyPL-VM:
виртуальная машина для ToyPL
• Run (of S) is a computation that starts with the label
l0 ≡ 0 and is either infinite or finishes with any
terminal label ln (i.e. does not mark any operator
within the program).
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 27
Всего слайдов
28. ToyPL-VM:
виртуальная машина для ToyPL
• An example of a finite run of sample.exe:
(0, 10, 15, 5), (2, 10, 15, 5), (3, 0, 15, 5), (4, 0, 0, 5),
(5, 0, 0, 5), (6, 0, 1, 5), (4, 1, 1, 5), (5, 1, 1, 5), (6, 1, 4, 5),
(4, 2, 4, 5), (5, 2, 4, 5), (6, 2, 9, 5), (4, 3, 9, 5),
(7, 3, 9, 5), (8, 2, 9, 5)
• In this example N = 4 and configurations are
represented by quadruples (l, s(x), s(y), s(z)).
Шилов Николай Вячеславович
Шилов Николай Вячеславович
03/10/12 28
Всего слайдов
29. Реализационная семантика языка ToyPL
• Implementation semantics for ToyPL relies upon
translation algorithm TR that maps every ToyPL-
program α to the corresponding program Sα for
ToyPL virtual machine.
• The idea behind this algorithm is quite trivial:
– draw a flowchart of a ToyPL-program,
– enumerate operators in the right order,
– use these numbers as labels and represent the
enumerated operators as labeled operators of the
corresponding program of ToyPL-VM.
Шилов Николай Вячеславович
03/10/12 29
Всего слайдов
30. Реализационная семантика языка ToyPL
• TR(x:=t) = 0 : x:=t goto 1;
• TR((α)) = TR(α)
• TR(α ; β) = TR(α) ∪ (TR(β) + max(TR(α)))
• TR(if ϕ then α else β) =
{0: if ϕ then 1 else (1 + max(TR(α)));} ∪
(TR(α)((max(TR(α))+max(TR(β)))/max(TR(α))) + 1) ∪
(TR(β) + max(TR(α)) + 1)
• TR(while ϕ do α) =
{0: if ϕ then 1 else 1 + max(T R(α));}
∪ (TR(α) + 1)(0/(1 + max(T R(α))))
Шилов Николай Вячеславович
03/10/12 30
Всего слайдов
31. Реализационная семантика языка ToyPL
• Упражнение #2:
Покажите, что TR(sample) = sample.exe.
Шилов Николай Вячеславович
03/10/12 31
Всего слайдов
32. Реализационная семантика языка ToyPL
• The implementation semantics is a particular
instance of the operational semantics where the
underling machine is a virtual computer.
• In particular, for every ToyPL-program α let the
implementation semantics of α be the set of all runs
of the translated program TR(α) on ToyPL-VM.
Шилов Николай Вячеславович
03/10/12 32
Всего слайдов
33. Реализационная семантика языка
• For the first time the implementation semantics for
imperative programming languages was introduced
as a part of a so-called Vienna Development Metho d
(VDM), one of the longest-established Formal
Methods.
• VDM has grown at IBM’s Vienna Laboratory in the
1970s inder supervision of Dines Bjorner and Cliff
Jones (The Vienna Development Method: The Meta-
Language, Lect. Not. in Comp. Sci., v.61, 1978.)
Шилов Николай Вячеславович
03/10/12 33
Всего слайдов
34. Пример реализационной семантики
• The implementation semantics of the sample
program sample is equal to the set of all possible
runs of the program sample.exe.
• This set consists of the following three disjoint parts:
Шилов Николай Вячеславович
03/10/12 34
Всего слайдов
35. Пример реализационной семантики
• all finite sequences of configurations that have the
following form
(0, p, q, r) , (2, p, q, r) , (3, 0, q, r) , (4, 0, 0, r) , (5, 0, 0, r) ,
(6, 0, 1, r) , (4, 1, 1, r) , . . . . . . . . . (4, ⌊ √r⌋ , ⌊ √r⌋2 , r) ,
(5, ⌊ √r⌋ ,⌊ √r⌋2 , r) , (6, ⌊ √r⌋ , (⌊ √r⌋ +1)2 , r) ,
(4, (⌊ √r⌋ +1), (⌊ √r⌋ +1)2 , r) ,
(7, (⌊ √r⌋ + 1), (⌊ √r⌋ + 1)2 , r) , (8, ⌊ √r⌋ , (⌊ √r⌋ + 1)2 , r),
where (⌊ √ r⌋ + 1)+ < 2N;
Шилов Николай Вячеславович
03/10/12 35
Всего слайдов
36. Пример реализационной семантики
• all finite sequences of configurations that have the
following form
(0, p, q, r) , (2, p, q, r) , (3, 0, q, r) , (4, 0, 0, r) ,
(5, 0, 0, r) , (6, 0, 1, r) , (4, 1, 1, r) , ... (4, ⌊ √r⌋ , ⌊ √r⌋2 , r) ,
(5, ⌊ √r⌋ ,⌊ √r⌋2 , r) , (6, ⌊ √r⌋ , (⌊ √r⌋ + 1)2 mod(2N ), r) ,
(4, (⌊ √r⌋ + 1)mod(2N ), (⌊ √r⌋ + 1)2 mod(2N ), r) , …
(5, (⌊ √r⌋ + k)mod(2N ), (⌊ √r⌋ + k)2 mod(2N ), r) ,
(6, (⌊ √r⌋ + k)mod(2N ), (⌊ √r⌋ + k +1)2 mod(2N ), r) ,
(4, (⌊ √r⌋ + k + 1)mod(2N ), (⌊ √r⌋ + k +1)2 mod(2N ), r) ,
(7, (⌊ √r⌋ + k + 1)mod(2N ), (⌊ √r⌋ + k +1)2 mod(2N ), r) ,
(8, (⌊ √r⌋ + k)mod(2N ), (⌊ √r⌋ + k +1)2 mod(2N ), r),
where (⌊ √r⌋ + 1)2 mod(2N ) ≤ r but (⌊ √r⌋ + k +1)2
mod(2N ) > r for some k > 0;
Шилов Николай Вячеславович
03/10/12 36
Всего слайдов
37. Пример реализационной семантики
• all infinite sequences of configurations that have the
following form
(0, p, q, r) , (2, p, q, r) , (3, 0, q, r) , (4, 0, 0, r) ,
(5, 0, 0, r) , (6, 0, 1, r) , (4, 1, 1, r) , …
(4, ⌊ √r⌋ , ⌊ √r⌋2 , r) , (5, ⌊ √r⌋ ,⌊ √r⌋2 , r) ,
(6, ⌊ √r⌋ , (⌊ √r⌋ + 1)2 mod(2N ), r) ,
(4, (⌊ √r⌋ + 1)mod(2N ), (⌊ √r⌋ + 1)2 mod(2N ), r) , …
(5, (⌊ √r⌋ + k)mod(2N ), (⌊ √r⌋ + k)2 mod(2N ), r) ,
(6, (⌊ √r⌋ + k)mod(2N ), (⌊ √r⌋ + k + 1)2 mod(2N ), r) ,
(4, (⌊ √r⌋ + k + 1)mod(2N ), (⌊ √ r⌋ + k + 1)2 mod(2N ), r) , …
where (⌊ √ r⌋ + k) 2 mod(2 N ) ≤ r for all k > 0.
Шилов Николай Вячеславович
03/10/12 37
Всего слайдов
38. Пример реализационной семантики
• Упражнение #3: Проверьте корректность
описания реализационной семантики.
• The example demonstrates formally that the ToyPL-
program sample and the corresponding program
sample.exe for ToyPL-VM either compute (in the
variable x) the integer part of the square root of the
initial value r (of the variable z) in the case when (⌊
√r⌋ + 1)2 < 2N, or something strange, or diverge in the
opposite case.
Шилов Николай Вячеславович
03/10/12 38
Всего слайдов
39. Input – Output семантика для ToyPL
• Since the implementation semantics for ToyPL is
already defined, we can define input-output
semantics for ToyPL-programs as follows:
• for every ToyPL-program α and all states s′ and s′′ of
α, let us write (s′ ,s′′ )∈ IO(α) and say that α outputs s
′′ for input s′ , if there exists a run of TR(α) that starts
with s′ and finishes with s′′ .
Шилов Николай Вячеславович
03/10/12 39
Всего слайдов
40. Пример Input – Output семантики
• For example, for every input state (p,q, r) the
program sample always outputs another state ((⌊
√r⌋ + k)mod(2N),(⌊ √r⌋ + k + 1)2 mod(2N ),r),
where
– ⌊.. .⌋ denotes the floor function,
– k ≥ 0 is the least integer such that (⌊ √r⌋ + k)2
mod(2N ) ≤ r, but (⌊ √r⌋ + k + 1)2 mod(2N ) > r.
Шилов Николай Вячеславович
03/10/12 40
Всего слайдов