20120309 formal semantics shilov_lecture02

40
06/16/22 Шилов Николай Вячеславович Всего слайдов 1 Fun with Formal Program Semantics (О формальной семантике программ – просто) Шилов Николай Вячеславович Computer Science клуб - Екатеринбург Март 2012

Upload: computer-science-club

Post on 28-May-2015

218 views

Category:

Education


0 download

TRANSCRIPT

Page 1: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 1

Fun with Formal Program Semantics (О формальной семантике программ –

просто)

Шилов Николай Вячеславович

Computer Science клуб - ЕкатеринбургМарт 2012

Page 2: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 2

Тема 2: «Основной ингредиент»: понятие о реализационной семантике

(или как превратить эзотерический язык TEL в игрушечный язык программирования ToyPL)

Page 3: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 3

Историческая справка

• Минуло почти 45 лет с момента публикации Робертом В. Флойдом статьи

Assigning Meanings to Programs(Proc. Symp. Applied Mathematics, Am. Math. Soc., v.19, 1967)

• в которой была сделана первая (и удачная) попытка разработать математически-точный метод описания формальной семантики (смысла) программ.

04/12/23 3Шилов Николай Вячеславович Всего слайдов

Page 4: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 4

Историческая справка

• Уже прошло почти 15 лет после публикации Дэвидом А. Шмидтом призыва к академической общественности

On the Need for a Popular Formal Semantics(ACM SIGPLAN Notices, 1997)

• сделать формальную семантики программ понятной и доступной широкому кругу инженеров-программистов.

04/12/23 4Шилов Николай Вячеславович Всего слайдов

Page 5: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 5

Историческая справка

• После таких призывов академическая активность в попытках обобщить, сделать доступной и полезной формальную семантику, представить свой «взгляд с высоты» нарастала, в неё включались всё новые учёные.

04/12/23 5Шилов Николай Вячеславович Всего слайдов

Page 6: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 6

Историческая справка

• Например, Петер Д. Мозес в 2001 г. в обзоре The Varieties of Programming Language Semantics

And Their Uses(A.P. Ershov International Conference «Perspectives of System Informatics»)

• пропагандировал свой подход к многообразию формальных семантик и путях их использования.

04/12/23 6Шилов Николай Вячеславович Всего слайдов

Page 7: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.

04/12/23 7Шилов Николай Вячеславович Всего слайдов

Page 8: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 8

Историческая справка

• В следующем 2002 г. известный учёный Патрик Кузо опубликовал журнальную статью

Constructive Design of a Hierarchy of Semantics of a Transition System by Abstract Interpretation

(Theor. Comp. Sci., 2002)

• в которой строит иерархию формальных семантик.

04/12/23 8Шилов Николай Вячеславович Всего слайдов

Page 9: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.

04/12/23 9Шилов Николай Вячеславович Всего слайдов

Page 10: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.

04/12/23 10Шилов Николай Вячеславович Всего слайдов

Page 11: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 11

Историческая справка

• Но наука не стоит на месте, и одновременно с попытками бросить взгляд с высоты на картину, которую представляют сложившиеся к XXI веку семантические формализмы, продолжают появляться новые семантические парадигмы.

04/12/23 11Шилов Николай Вячеславович Всего слайдов

Page 12: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 12

Историческая справка

• Например, так называемая теоретико-игровая семантика Самсона Абрамского и Чих-Хао Лук Онга. Причём, авторы этой семантики утверждают, что данный формализм готов (в смысле «дозрел») для моделирования и верификации программного обеспечения:Applying game semantics to compositional software

modeling and verication (Tools and Algorithms for Construction and Analysis of Systems, 2004)

04/12/23 12Шилов Николай Вячеславович Всего слайдов

Page 13: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 13

Лирическое отступление: зачем всё это надо?

• Но по прежнему «значительно больше экспертов-теоретиков, чем практикующих инженеров-программистов» (Д.А. Шмидт, 1997).

• Поэтому в январе 2010 г. Дэвид Л. Парнас в статье Really Rethinking «Formal Methods» предложил: «Мы должны подвергнуть сомнению предположения, лежащие в основе хорошо известных современных формальных методов разработки программного обеспечения, чтобы понять, почему они не получили широкого распространения, и что в них следует изменить».

04/12/23 13Шилов Николай Вячеславович Всего слайдов

Page 14: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 14

М.В. Ломоносов: «Математику уж затем любить надо,

что она ум в порядок приводит»• Но, может быть, значение формальных методов в

программировании (формальной семантики в том числе) не сводится к моделированию и верификации программного обеспечения?

• Формальные методы (формальная семантики в частности) выполняют туже роль, что и математика в воспитании мышления: они дисциплинирует ум программистов и в порядок его приводят.

04/12/23 14Шилов Николай Вячеславович Всего слайдов

Page 15: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.

04/12/23 15Шилов Николай Вячеславович Всего слайдов

Page 16: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.

04/12/23 16Шилов Николай Вячеславович Всего слайдов

Page 17: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 17

Основной ингредиент:виртуальная машина

• A virtual machine is an abstract computer with instruction set executable (interpretable) at any conventional computer platform.

04/12/23 17Шилов Николай Вячеславович Всего слайдов

Page 18: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.

04/12/23 18Шилов Николай Вячеславович Всего слайдов

Page 19: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.

04/12/23 19Шилов Николай Вячеславович Всего слайдов

Page 20: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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> ;

04/12/23 20Шилов Николай Вячеславович Всего слайдов

Page 21: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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;04/12/23 21Шилов Николай Вячеславович

Всего слайдов

Page 22: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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 .

04/12/23 22Шилов Николай Вячеславович Всего слайдов

Page 23: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 23

ToyPL-VM:виртуальная машина для ToyPL

• A state (of S) is a total function s : V AR(S) → Z/2N that assigns every variable xV 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).

04/12/23 23Шилов Николай Вячеславович Всего слайдов

Page 24: 20120309 formal semantics shilov_lecture02

04/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:AB. aA. bB.

(xA. (if x=a then b else f(x)).• Упражнение #1: s(t) – значение выражения t в

состоянии s. Дайте формальное определение.

04/12/23 24Шилов Николай Вячеславович Всего слайдов

Page 25: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.

04/12/23 25Шилов Николай Вячеславович Всего слайдов

Page 26: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.

04/12/23 26Шилов Николай Вячеславович Всего слайдов

Page 27: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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).

04/12/23 27Шилов Николай Вячеславович Всего слайдов

Page 28: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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)).

04/12/23 28Шилов Николай Вячеславович Всего слайдов

Page 29: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.

Page 30: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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(α))))

Page 31: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 31

Реализационная семантика языка ToyPL

• Упражнение #2:

Покажите, что TR(sample) = sample.exe.

Page 32: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.

Page 33: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.)

Page 34: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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:

Page 35: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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;

Page 36: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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(2⌊ ⌋ N ), ( √r + 1)⌊ ⌋ 2 mod(2N ), r) , … (5, ( √r + k)mod(2⌊ ⌋ N ), ( √r + k)⌊ ⌋ 2 mod(2N ), r) , (6, ( √r + k)mod(2⌊ ⌋ N ), ( √r + k +1)⌊ ⌋ 2 mod(2N ), r) , (4, ( √r + k + 1)mod(2⌊ ⌋ N ), ( √r + k +1)⌊ ⌋ 2 mod(2N ), r) , (7, ( √r + k + 1)mod(2⌊ ⌋ N ), ( √r + k +1)⌊ ⌋ 2 mod(2N ), r) , (8, ( √r + k)mod(2⌊ ⌋ N ), ( √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;

Page 37: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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(2⌊ ⌋ N ), ( √r + 1)⌊ ⌋ 2 mod(2N ), r) , … (5, ( √r + k)mod(2⌊ ⌋ N ), ( √r + k)⌊ ⌋ 2 mod(2N ), r) , (6, ( √r + k)mod(2⌊ ⌋ N ), ( √r + k +⌊ ⌋ 1)2 mod(2N ), r) , (4, ( √r + k + 1)mod(2⌊ ⌋ N ), ( √ r + k + 1)⌊ ⌋ 2 mod(2N ), r) , … where ( √ r + k) 2 mod(2 N ) ≤ r for all k > 0.⌊ ⌋

Page 38: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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.

Page 39: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 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 .′ ′′

Page 40: 20120309 formal semantics shilov_lecture02

04/12/23 Шилов Николай Вячеславович Всего слайдов 40

Пример Input – Output семантики

• For example, for every input state (p,q, r) the program sample always outputs another state (( ⌊√r + k)mod(2⌋ N),( √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.