Научная статья на тему 'DYNAMIC SEPARATION LOGIC AND ITS USE IN EDUCATION'

DYNAMIC SEPARATION LOGIC AND ITS USE IN EDUCATION Текст научной статьи по специальности «Математика»

CC BY
36
8
i Надоели баннеры? Вы всегда можете отключить рекламу.
Ключевые слова
DYNAMIC SEPARATION LOGIC / FRAME RULE / SOUNDNESS

Аннотация научной статьи по математике, автор научной работы — Makarov Evgeny Maratovich

Mathematical logic is widely used in hardware and software verification. Hoare logic is particularly suitable for reasoning about imperative programs. Its extension, separation logic, introduces the separating conjunction, which makes it possible to reason about programs working with pointers and mutable data structures. Dynamic logic, an example of modal logic, is yet another formalism used for verification. This article introduces propositional dynamic separation logic, which adds separating conjunction to dynamic logic. We describe syntax, semantics and Hilbert-style deductive system for propositional dynamic separation logic and prove its soundness. The definition of the logic is rather abstract. Thus, the programming language consists of so-called regular programs rather than while-programs, and the set of atomic commands can be arbitrary as long as they correspond to local actions. Special attention is devoted to the soundness of the frame rule, which allows writing program specification using a small footprint, i.e., specifying exactly the portion of the heap that the program reads or writes. Programs that perform tests are also treated differently from regular dynamic logic. The article also argues for the use of separation logic in computer science curriculum. It is more intuitive that other substructural logics and can be taught even in introductory logic courses. At the same time, it is an active research area with numerous verification tools built on its foundation. Therefore, it serves an excellent introduction to formal methods.

i Надоели баннеры? Вы всегда можете отключить рекламу.
iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.
i Надоели баннеры? Вы всегда можете отключить рекламу.

Текст научной работы на тему «DYNAMIC SEPARATION LOGIC AND ITS USE IN EDUCATION»

THEORETICAL QUESTIONS OF COMPUTER SCIENCE, COMPUTATIONAL MATHEMATICS, COMPUTER SCIENCE AND COGNITIVE INFORMATION TECHNOLOGIES

УДК 510.643

DOI: 10.25559/SITITO.16.202003.543-550

Dynamic Separation Logic and its Use in Education

E. M. Makarov

Lobachevsky State University of Nizhny Novgorod, Nizhny Novgorod, Russian Federation 23 Gagarin Av., Nizhny Novgorod 603950, Russian Federation evgeny.makarov@itmm.unn.ru

Mathematical logic is widely used in hardware and software verification. Hoare logic is particularly suitable for reasoning about imperative programs. Its extension, separation logic, introduces the separating conjunction, which makes it possible to reason about programs working with pointers and mutable data structures. Dynamic logic, an example of modal logic, is yet another formalism used for verification. This article introduces propositional dynamic separation logic, which adds separating conjunction to dynamic logic.

We describe syntax, semantics and Hilbert-style deductive system for propositional dynamic separation logic and prove its soundness. The definition of the logic is rather abstract. Thus, the programming language consists of so-called regular programs rather than while-programs, and the set of atomic commands can be arbitrary as long as they correspond to local actions. Special attention is devoted to the soundness of the frame rule, which allows writing program specification using a small footprint, i.e., specifying exactly the portion of the heap that the program reads or writes. Programs that perform tests are also treated differently from regular dynamic logic.

The article also argues for the use of separation logic in computer science curriculum. It is more intuitive that other substructural logics and can be taught even in introductory logic courses. At the same time, it is an active research area with numerous verification tools built on its foundation. Therefore, it serves an excellent introduction to formal methods.

Keywords: dynamic separation logic, frame rule, soundness.

The author declares no conflicts of interest.

For citation: Makarov E.M. Dynamic Separation Logic and its Use in Education. Sovremennye informacionnye tehnologii iIT-obrazovanie = Modern Information Technologies and IT-Education. 2020; 16(3):543-550. DOI: https://doi.org/10.25559/SITITO.16.202003.543-550

Abstract

G ®

Контент доступен под лицензией Creative Commons Attribution 4.0 License. The content is available under Creative Commons Attribution 4.0 License.

Vol. 16, No. 3. 2020 ISSN 2411-1473 sitito.cs.msu.ru

Modern Information Technologies and IT-Education

ТЕОРЕТИЧЕСКИЕ ВОПРОСЫ ИНФОРМАТИКИ, ПРИКЛАДНОЙ МАТЕМАТИКИ, КОМПЬЮТЕРНЫХ НАУК И КОГНИТИВНО-ИНФОРМАЦИОННЫХ ТЕХНОЛОГИЙ

Динамическая логика разделений и ее использование в образовании

Е. М. Макаров

ФГАОУ ВО «Национальный исследовательский Нижегородский государственный университет им. Н.И. Лобачевского», г. Нижний Новгород, Российская Федерация 603022, Российская Федерация, г. Нижний Новгород, пр. Гагарина, д. 23 evgeny.makarov@itmm.unn.ru

Аннотация

Математическая логика широко применяется для верификации программ и аппаратного обеспечения. Одной из логик, наиболее подходящих для верификации императивных программ, является логика Хоара. Ее расширение, логика разделений, использует разделяющую конъюнкцию, которая позволяет рассуждать о программах, использующих указатели и изменяемые структуры данных. Еще одним формализмом, используемым в верификации, является динамическая логика— частный случай модальной логики. Данная статья описывает пропозициональную динамическую логику разделений, которая добавляет разделяющую конъюнкцию к динамической логике.

Мы описываем синтаксис, семантику и исчисление в гильбертовском стиле для пропозициональной динамической логики разделений и доказываем ее корректность. Определение логики является достаточно абстрактным. Так, используемый язык программирования состоит из так называемых регулярных программ вместо программ с обычными конструкциями if и while. Множество атомарных программ может быть произвольным при условии, что они порождают локальные действия. Особое внимание уделяется корректности правила кадра, позволяющего писать локальные спецификации программ, то есть указывать участки памяти, которые непосредственно читаются или изменяются программой. Условные операторы также рассматриваются отлично от стандартной динамической логики.

Статья также содержит аргументы в пользу использования логики разделений в изучении компьютерных наук. Данная логика более проста, чем другие субструктурные логики, и может преподаваться даже в начальных курсах математический логики. В то же время, логика разделений является областью активных исследований с большим количеством применений. На основе этой логики построено много инструментов для верификации. Поэтому она является отличным введением в формальные методы.

Ключевые слова: динамическая логика разделений, правило кадра, корректность. Автор заявляет об отсутствии конфликта интересов.

Для цитирования: Макаров, Е. М. Динамическая логика разделений и ее использование в образовании / Е. М. Макаров. — DOI 10.25559/SITITO.16.202003.543-550 // Современные информационные технологии и ИТ-образование. — 2020. — Т. 16, № 3. — С. 543-550.

Современные информационные технологии и ИТ-образование

Том 16, № 3. 2020 ISSN 2411-1473 sitito.cs.msu.ru

k THEORETICAL QUESTIONS OF COMPUTER SCIENCE, COMPUTATIONAL MATHEMATICS,

E. M. Makarov COMPUTER SCIENCE AND COGNITIVE INFORMATION TECHNOLOGIES

Introduction

Mathematical logic has long been used to help create and verify computer software [1]. While generic first- and higher-order logics can be used to prove properties of programs,1 in practice specialized logics are necessary. One of the oldest examples of such logic is Hoare logic [2; 3]. It uses formulas, or assertions, of first-order logic (or some other chosen logic) to describe contents of variables, or states. The derivable judgments of Hoare logic, called triples, have the form {F}}{(?}, where F and G are assertions, called pre- and postconditions, respectively, and C is a program, or command. Such triple may express partial or total correctness of the program C. In the first case, the triple means that if C starts in a state satisfying F and finishes execution, then the final state satisfies —. Total correctness additionally demands that C terminates.

As a calculus, Hoare logic provides axiomatic semantics to programs. It includes a collection of axioms and inference rules that allow deriving specifications of programs.

A serious shortcoming of Hoare logic has to do with shared mutable data structures. When a program is allowed to use pointers, a single field can be referenced from different places, and updating the content of one pointer may unexpectedly change the content of a seemingly unrelated pointer. This situation is known as aliasing. To deal with such programs, in early 2000s Reynolds, O'Hearn and others invented separation logic [4; 5].

Assertions and reasoning about them in separation logic is borrowed from the so-called logic of bunched implications (BI logic) [6]. During the early days of separation logic assertions were primarily though of as predicates on heaps, i.e., memory segments. BI logic adds to classical logic new connectives * and —*, called separating conjunction and separating implication. Assertion Fi ui} is considered true on a heap u if it can be divided into two disjoint portions a\ and <72 such that F\ is true on (7\ and *} is true on er2. The connective —* is an implication that approximately relates to * and ordinary implication relates to conjunction. To talk about heaps, separation logic uses the predicate I i— which means that value — is stored in the heap at location I. Various axioms, for example, saying that the is a partial function, can be added. Separation logic also includes an important frame rule.

{F}C{G}

{F *H}C{G *#} ( )

It means that if C converts a heap satisfying F into one satisfying G, then it will work similarly when run on a larger heap and won't touch the excess part. This rule allows writing function specification using small footprint, i.e., specifying exactly the portion of the heap that the function reads or writes. Using the frame rule, this specification can be lifted to reason about a larger program. Hoare logic and separation logic have enjoyed great success as machinery for specifying and proving program correctness. Many software tools were created for verifying software with different degrees of human participation. Some successful projects are listed in Section 4.

Dynamic logic [7] is yet another formalism for reasoning about programs. Unlike Hoare and separation logics, its judgments are not restricted to triples and can be arbitrary formulas. It is a modal logic that for every program C includes a modal operator [G]. Formula [G]F is true in a state CT if every terminating execution of C

starting in <? ends in a state satisfying F. Thus, Hoare triple {F}G{G} can be expressed as F —\\G]G. As a result, dynamic logic is at least as expressive as Hoare logic.

Dynamic logic has also been quite useful for practical verification. For example, the KeY Project [8] uses dynamic logic in a tool that allows verifying Java programs against specifications written in the Java Modeling Language.

Since Hoare logic can be embedded into dynamic logic, it makes sense to extend the latter by adding separating connectives. To our knowledge, this has not been done. So the first contribution of this paper is a formulation of propositional dynamic separation logic and a proof of its soundness. The second contribution is a discussion of why dynamic and separation logics form a particularly suitable subject in computer science education. This paper deals with propositional dynamic separation logic and, following [9], abstracts from many concrete details of a programming language. For this reason it does not show examples of verifying realistic algorithms. Several examples, including in-place reversal of a linked list, copying a tree and Schorr-Waite graph marking algorithm, can be found in [4].

The outline of this paper is as follows. Section 2 introduces dynamic separation logic and describes its similarity with traditional separation logic. Section 3 proves soundness of dynamic separation logic. The use of dynamic and separation logics in education is discussed in Section 4. Finally, Section 5 concludes and points to future research.

Dynamic Separation Logic

This section introduces dynamic separation logic. Most of the technical details are based on [9] and are similar to regular separation logic. The main difference is that separation logic uses triples while dynamic separation logic uses formulas of the BI logic with added modal operators [G].

Definition 1. Formulas F and commands С are described using the following mutually recursive grammar.

.F,G::=p| Cru?|fa|g|?mp|-PF|:FЛF{F| K-?F| F*F|[C]F C::= a|C}C||C + {'|C*|.F?

The command Gi; C2 executes C\ followed by G2; C\ + C2 nondeterministically chooses and runs one of G} C% C* executes С zero or more times, while Fl does nothing if F is true in the current state and terminates the process normally otherwise (instead of terminating the process may be though of as diverging since we are interested in partial correctness). This language is nondeterministic due to the presence of +, so there may be multiple computations starting in the same state.

In this programming language some operators can be expressed using well-known translation [7, Sect. 5.1].

skipc true?

fa! = faire?

if F fa{n f?i {'se Cp = (F?; Ga? + }-F; Ge)

waHe F dotffF=(ir?;<?Pf*;-2Ff

f{2e2tC2ntil F = G;(-F?;G)2; Ff

Variable p ranges over the countable set of propositional variables, and a ranges over the set of atomic commands. The following example is taken from [5].

1 For example, it is well-known that Kleene's T predicate, which describes the computation of a given Turing machine, is representable in formal arithmetic and so can

be used to express and formally prove properties of algorithms encoded by Turing machines.

Vol. 16, No. 3. 2020 ISSN 2411-1473 sitito.cs.msu.ru

Modern Information Technologies and IT-Education

ТЕОРЕТИЧЕСКИЕ ВОПРОСЫ ИНФОРМАТИКИ, ПРИКЛАДНОЙ МАТЕМАТИКИ,

КОМПЬЮТЕРНЫХ НАУК И КОГНИТИВНО-ИНФОРМАЦИОННЫХ ТЕХНОЛОГИЙ Е М Макаров

Example 2. Let arithmetic expressions E and atomic actions a be defined by the following grammar.

E::=x,y,...\0\l\E + E\ ExE\E-E a::=x:=E\x:=[E]\[E]:=E\x := cons (E, ...,E) | dispose(£J)

Here [E] denotes the content of memory, or heap, at address E. Therefore, x := [E] reads the content of memory at address E into X; [FjJ := E2 writes the value of E2 to address Fi; X := COns(Fi,..., En) allocates n consecutive cells, writes values of Ei,...,En there and assigns x to the address of the first of those cells; and dispose(F) frees the memory cell at address E. Commands that access the heap may generate a fault if the required address is not allocated.

Commands are interpreted as binary relations on the set E of states. Historically the first example of states was heaps possibly paired with stores, i.e., values of local variables. A crucial feature of heaps is that they support the operation of union of disjoint portions of a heap. Over time, many other interpretations of states were proposed. The following definition generalizes over them.

Definition 3. A separation algebra is a triple (£, *, e) where * is a partial binary operation on E and e£S satisfying the following properties for all 0 1,02 G X.

1. 01 * <72 = <72 *

2. e*a = a*e = a;

3. * cr = 02 * O" =

Thus, E is a partial commutative monoid. We write 01 ^ 02 if 02 = 01 * 0' for some 0 and 01 # 02 if 01 * 0"2 is defined.

Example 4. Let E = Heaps = L —^fln V where L is a set of locations, V is a set of values, and —^fin denotes the set of finite partial functions. Then e denotes the nowhere defined function and * is the union of functions with disjoint domains. One can take L = N and V = Z [5]. For another example, consider unspecified disjoint sets Atoms and Addresses, let L = Addresses and V be the set of all finite tuples whose elements come from Z U Atoms U Addresses [4]. This construction allows representing linked lists, i.e., sequences of pairs whose second element is either an atom nil or an address of the following pair.

Example 5. Let Var be the set of local variables and L and V be as in the previous example. Then £ = Stores X Heaps where Stores = Var —^fin V. This represents the variables-as-resource model [10].

Example 6. Let V = Z X (0,1]. Then heaps with values from V can be viewed as collections of cells with permissions. Permission 1 gives the process full access to the cell and allows reading, writing and freeing it. Permissions strictly smaller than 1 give only reading access. The union of heaps is defined as follows.

((v,p), if hi(l) = (v,p), hi(l) is undefined

(v.p), if /12(0 = (v,p), h\ (/) is undefined

(v,p! +p2), if MO = {v,pi),h2{l) = (v,p2),pi +P2 < 1

This definition allows sharing permissions between several processes.

Definition 7. A predicate on a separation algebra (£, *, e) is a subset of £ Variables P, Q, R range over predicates.

As usual in dynamic logic, the semantics of formulas is defined by a function [•] mapping formulas to predicates. We write 0 |= F if 0 G [FJ. Similarly, the semantics of commands is usually described by a function that we'll also denote [•] mapping commands to binary relations on £ This turns E into a Kripke frame [7, Sect. 3.7] and leads to the standard definition

a |= [C]F = ^ V0'. 0[C]a' 0' |= F.

However, one has to decide how to incorporate memory faults into this definition. A computation starting from a certain state may behave in one of the following ways:

1. finish normally and produce a final state;

2. terminate (for example, after executing F?) without producing a final state;

3. run forever;

4. terminate with a memory fault.

Options 2 and 3 do not violate partial correctness, but 4 does. Namely, if one computation of C starting in a produces a fault, then 0 [C]F by definition, even if other computations of C finish successfully. Thus we need to distinguish between cases 2 and 4 above.

In the early days of separation logic [5] this was done by defining a state 0 safe for C if option 4 above never happens when C is run in 0. This concept was then used to formulate the soundness of the frame rule. However, [9] introduced a more compact way to define 0 |= [C]F that automatically takes memory faults into account. Namely, instead of a binary relation [CJ is viewed as a function from £ to F(£) where F(-) denotes a powerset. Then 0 |= [C]F holds if [C] (0) C [F| To deal with faults, we give the following definition.

Definition 8. Let F(E)T =f P(S) U {T} where T £ P(£) is a new greatest element. The order C is defined as follows: UQV holds iff V = T or U,V G P(S) and U C V. The set P(E)T is clearly a complete lattice, whose join and meet are denoted by LI and n. Variables U, V range over P(E)T. The greatest element T of f>(E)T should not be confused with [true] = P(£). In particular, T is not a predicate and a |= T is not defined.

Definition 9. An action is a function from £ to P(£)T. The set of all actions is a complete lattice under pointwise order: / Cj if /(0) C 5(0) for all u£ £. Somewhat abusing the notation, the join and meet on the set of actions is also denoted by LI and n. Variables /, g range over actions.

A semantics maps commands to actions. It has to be defined in such a way that if C may arrive at a memory fault starting in 0, then |C](0) = T. Then the definition

0" |= [C]F holds if |C](0) C [F]

has the desired effect: it implies that cr [C]F if C produces a fault because [F] S F(E) and therefore T C [F] is false. It will be shown in Section 3 that the following definitions characterizes actions satisfying the frame rule (1).

Definition 10. An action /: £ P(£)T is called local if /(0! * o-2) C f(a1) * {02} for all 01 # 02. If / is local, then /(01) T implies that /(01 * 02) ^ T. For f = [CJ this means that if C does not produce a memory fault starting in 01, than it won't produce a fault starting in a larger

Современные информационные технологии и ИТ-образование

Том 16, № 3. 2020 ISSN 2411-1473 sitito.cs.msu.ru

E. M. Makarov

THEORETICAL QUESTIONS OF COMPUTER SCIENCE, COMPUTATIONAL MATHEMATICS, COMPUTER SCIENCE AND COGNITIVE INFORMATION TECHNOLOGIES

547

state <7\ * <72- Further, if C starts in * (72, then every final state can be split into a er^ and cr2 where C converts G\ into <7^. Thus, C does not touch the additional portion <72 of the state, which is exactly what the frame rule says.

It may seem at first that the condition on actions that is equivalent to the frame rule can be states as follows.

iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.

a[ e /(<7i) a[*a2e /(<7i * a2)

But the allocation operator from Example 2 does not satisfy this property. Indeed, consider the separation algebra consisting of heaps from Example 4. Let [Zi i—> V\,..., ln i—> Vn] denote the heap that maps Zj to Vi (all li are assumed to be different). Then X := cons(l) may convert the empty heap e to [0 i—> 1]. But if X := COns(l) is executed in a heap where 0 is already allocated, for example, in [0 i—> 0], then it has to allocate a new address, so x ■— cons(l) cannot convert e * [0 0] to [0 1] * [0 0]. Note, however, that x := cons(l) may convert e * [0 i—> 0] to, say, [1 i—>• 1] * [0 i—>■ 0], and the same instructions is allowed to change e into [1 i-> 1] in accordance with the definition of local action.

It is proved in [5] that atomic actions from Example 2 are local. One example of a non-local action is a constant function /(cr) = {e}. Indeed, Definition 10 requires that /(f7i * o-2) = {e} c /(<7i) * {C72} = {e} * {<72} = {o"2>, which is false in general. Another non-local action g assigns the same value, say, 0, to all allocated cells. Then g converts [0 1] to [0 0], but g does converts [0 i—> 1,1 i—2] to [0 0,1 0] rather than [0 i—>■ 0,1 i—2], as expected of a local action.

Now we are ready to define the semantics of formulas and commands.

Definition 11. A model is a pair of separation algebra (E, *, e) and a function [■] mapping propositional variables to predicates and atomic commands to local actions. We define the following op -erations on elements of F(E) and

u e P(S)T).

—iP <= Y*\ P P AQd= PnQ PVQ=PUQ P Q = (S \ P) U Q P * Q =f {a | a = <7i * 02, <7i e P, <72 E Q for some o\, 02 £ E}

[f]U = {c I /("") E U} Using these operations a model extends the mapping [■] to all formulas: for example, [Fi A F2] = [Fi] A [F2], In addition, the semantics of atomic formulas is defined.

[true] = E, [false] = 0, [emp] = {e}

It's important to note that for [F] is a predicate, not T, for every formula F.

The mapping [•] is extended to all commands as follows.

[C1;C2] = [C1];[C2]

OO

[ci = □ [Cf

71=0

[C1+C2] = [C1]U[C2]

{a}, Va'.a^a'

<j'\=F

P^JM = < 0, V(7'. <J<a' => T, otherwise

(/;<?)(*) 1 ^ G my, /W = T otherwise

= ids

fn+1

The definition of [CJ is expected possibly with the exception of [F?]: in regular dynamic logic [F?](cr) is simply defined as {(7} if a |= F and 0 otherwise [7, Sect. 5.2].

It is proved in [9, Lemma 9] that local actions form a complete lattice, which, together with the way [C] is defined, implies that all actions corresponding to commands are local. We consider the case of F?, which is stated in [9] but not proved in detail. Suppose (7i ^ <7 implies <7 |= F for all cr Then the same property holds when <7i is replaced with <7i * <72. Therefore, [F?](ai) = {ai}, [F?](<7i * a2) = {(n * a2} and [F?](cri * cr2) C [F?]((7i) * {a2} holds since both sides are equal to {(7i * (72}.

Suppose 0"i ^ a implies (7 F for all cr. Then again the same property holds when is replaced with o\ * <72, so

[F?](cti) = [F?](cri * cr2) = 0, from which the desired conclusion follows.

Finally, if none of the cases above is true, then [F?](<7i) = T = [F?](<7i) * {(72} by Definition 8, so the property holds since T is the greatest element. A natural question asks which formulas F define actions [F?] that don't return T, i.e., terminate normally. One such class of formulas does not depend on the heap but uses only local variables, i.e., the store. Since the content of the heap can be loaded into local variables, this does not represent an essential restrictions and corresponds to conditions used in the if operators in popular languages like C and Java. To take advantage of such formulas one has to use predicate dynamic logic rather than propositional dynamic logic considered in this paper.

Soundness of Dynamic Separation Logic

Lemma 12. Let M = (E, *, e, [■]) be a model and / : E —^ F(E)T be an action. Then the following conditions are equivalent:

1. f is local, i.e., /(<7i * cr2) C /((Ji) * {cr2} for all <7i # <72;

2. [f]P*Q C [/](P* Q) for all predicates P, Q;

3. RQ [f]P implies R*Q^[f]{P*Q) for all predicates P,

Q, R.

Proof. (1) =>- (2). Fix P and Q and suppose cr \= [f]P * Q. Then (7 = <7i * (72 where (7i |= [f]P and (72 |= Q for some cri,cr2 G E. By definition /((7i) C P and {i72} C Q. By locality /(<7i * 0*2) C /(cri) * {C2} C. P * Q. Here we use mono-

Vol. 16, No. 3. 2020 ISSN 2411-1473 sitito.cs.msu.ru

Modern Information Technologies and IT-Education

ТЕОРЕТИЧЕСКИЕ ВОПРОСЫ ИНФОРМАТИКИ, ПРИКЛАДНОЙ МАТЕМАТИКИ,

КОМПЬЮТЕРНЫХ НАУК И КОГНИТИВНО-ИНФОРМАЦИОННЫХ ТЕХНОЛОГИЙ Е М Макаров

tonicity of * with respect to C, which is checked straightforwardly. Therefore, <7 |= [/](P*Q).

(2) =>• (3). Fix P, Q, R and assume that R Q[f]P and <7 |= R * Q. Then for some <7i, (J2 such that <7 = <7i * <72 we have <7i |= R, from where <7i |= [f]P, and <72 |= Q, i.e., <7 |= [f]P * Q. By assumption, a f= [/](P * Q).

(3) =>■ (1). Fix arbitrary <7i and (T2 and assume a\ ^ d2. If /(fl) = T, then /(<7i) * {<72} = T and the claim follows. Otherwise, let P = /(<7i), Q = {<72} and R = [/]P Then

N \S\P and (72 |= Q, that is, <7i * a2 \= [f]P * Q. By assumption cri * <72 |= [/](P*Q), i.e., [/](<7i * <72) Q P * Q = /(01) * {<72}, as required.

Definition 13. Let M = (£, *, e, [[■]) be a model. We say that a predicate P is true in M and write M \= P if P = E A formula F is called true in M (written M \= F) if M |= [F]. A formula is called valid if it is true in every model. An inference rule deriving predicate Q from Qi , ...,Pn is sound if M \= Pi, ...,M\=Pn implies M |= Q for every M. Similarly, an inference rule deriving formula G from F\,..., Fn is sound if M \= Fi,...,M \= Fn implies M \= G for every M.

Definition 14. A Hilbert-style deductive system for dynamic separation logic is given by the following axioms and inference rules:

1. Axioms of classical propositional logic;

2. C](P G) ([C]P [C]G);

3. [G](F AG)f> ([G]F A [G]G);

4. [Ci + C2]F «->• [Gi]P A [C2]F;

5. [Gi;G2]PO[GI][G2]P;

6. [F] A [G][G*]P [C*]F;

7. PA [G*](P [G]P) -»• [C]F;

8. [G]P*G-> [G](F*G); P F —>■ G

9.

G

10.

11. -

P * true

nP * true -F

Points 2 and 3 of Lemma 12 shows that it is sound and can replace the frame axiom.

The additional flexibility of dynamic logic with respect to regular separation logic make several primitive inference rules of the latter derivable. For example, [9] has the rule

{FJG{G,}, i = 1,... ,n

{VlLi WiVLiGi}

{F}C{GJ, i = 1,... ,n

{K=iFi}C{K=iGi}

In dynamic logic we have the following facts about derivability: if T = {Fi^- [C]Gi | * = l,...,n},then

n n n n

r I- V ^ ^ [C]( V C,) and rh/\Fi^[C](/\Gi).

¿=1

i=1

i=1

¿=1

Separation Logic in Education

Dynamic and separation logics are excellent topics for introducing students to formal methods and theoretical computer science. Though they require certain mathematical maturity, they are accessible to undergraduate students. In fact, this article uses hardly any concepts that cannot be considered in the introductory courses of discrete mathematics and mathematical logic. The logic of bunched implications, on which separation logic is built, is an example of a substructural logic, where the structural rules of weakening and contraction

Г h F Г, G h F

Г, G, G h F Г, G h F

[F?] G o (F -s- G) '

Theorem 15 (Soundness). The deductive system of Definition 14 is sound, i.e., every derivable formula is valid.

Proof. One has to show that all axioms are valid and all inference rules are sound. Axioms 1-7 are standard axioms of dynamic logic, which are valid in all Kripke models. Axiom 8, called the frame axiom, is valid by Lemma 12 since actions corresponding to all commands are local. Inference rules 9 and 10 are also standard for a modal logic. Finally, dynamic logic has the axiom that is the conclusion of rule 11. The direction —> is valid in our setting as well, but as for the opposite direction, [P?]((7) may return T, in which case <7 ft [F?]G. To prevent [F?](cr) = T formula F must be true in all <7' such that <7 ^ <7' or F must be false in all a' such that <7 ^ <7'. This is ensured by the assumptions of rule 11. If a' |= F * true -»• F and a \= F for some <7 ^ a', then a' |= F as well, and similarly for —iF.

Frame rule (1) can be written in dynamic separation logic as follows.

R [C]P

R*Q [C](P *Q)

are not generally valid. This reveals itself in the fact that the formula F * F «-»• F is not valid, in contrast to FAF^F. Indeed, <7 |= F * F means that the state <7 can be divided into <7i and <72, each of which validate F. This is different from F being true on the whole state.

Another prominent substructural logic is linear logic [11, Chap. 9], which is often used to describe resources. However, separation logic is more accessible to new students due to its simple heap (or, more generally, separation algebra) semantics. Even though classical logic can be embedded into linear logic via a translation, the BI logic is simply an extension of classical logic. A student just needs to understand the semantics of separation conjunction and separating implication (the latter is more rarely used in practice). Thus studying separation logic introduces a student to a world of non-classical logics in a natural way. It demonstrates how a logic can create a model of a computational process and solve a nontrivial problem of tracking pointers.

Hoare logic and separation logic represent a natural entry into the world of formal verification since they can be naturally encoded in a proof assistant such as Coq or Isabelle. This allows formalizing proofs both of properties about the logic themselves (such as soundness and completeness) and of algorithm specifications [12]. As the author of one book on formal methods put it speaking about correctness of programs, "the author and many other researchers today feel that proofs on paper have outlived their usefulness. Instead, the proofs are all found in the parallel world of the accompanying Coq source code" [13]. It turns out that formal verification of even well-known algorithms, such as computing vertex cover or independent set, can uncover incompletenesses in existing proofs and improve the complexity bounds [14].

A great success story in formal verification is the electronic text-

Современные информационные технологии и ИТ-образование

Том 16, № 3. 2020 ISSN 2411-1473 sitito.cs.msu.ru

E. M. Makarov

THEORETICAL QUESTIONS OF COMPUTER SCIENCE, COMPUTATIONAL MATHEMATICS, COMPUTER SCIENCE AND COGNITIVE INFORMATION TECHNOLOGIES

549

book "Software Foundations" by B.C. Pierce et al., which is widely used around the world. This book in five volumes covers a multitude of topics: propositional and predicate logic, definitions and proofs by induction, Hoare logic, simply typed lambda calculus, functional programming, and so on. All definitions, theorem and proofs in the book are implemented in Coq. The latest volume covers specifying and verifying real-world C programs using separation logic. A similar book based on Isabelle is [15-16]. Another textbook that uses Coq and separation logic is [17]. Dynamic logic is used, for example, in the "Bug Catching" course [18] at Carnegie Mellon University. This course also utilizes a fully automatic system Why3 [19] based on Hoare logic for proving program correctness. Despite being accessible to students, separation logic is located at the cutting edge of research in computer science [20; 21]. Many software tools have been developed that allow verifying realistic and intricate programs [22]. For example, a significant portion of an industrial, preemptive OS kernel has been verified [23]. Peter O'Hearn, one of the researchers at the origin of separation logic, joined Facebook and developed a static analyzer tool that catches thousands of bugs per month [24].

Using this research may help develop computer science curriculum that takes professional standards seriously and actively uses educational software [25-27]. For these reasons it seems a good idea to teach separation logic in mandatory and optional courses as an excellent introduction to modern computer science. One personal positive example for the author was supervising a master's thesis devoted to proving soundness of the frame rule for separation logic with regular programs used in this paper as opposed to while programs in [5]. The project received an excellent grade.

Conclusion and Future Work

We have introduced propositional dynamic separation logic and proved its soundness. We have also argued for including separation logic into computer science curriculum as an excellent introduction to both research problems and practical software verification. The next obvious step is proving completeness of dynamic separation logic, considering its first-order variant and studying whether the use of dynamic logic creates advantages over regular separation logic that uses Hoare triples in practical program verification. Another important variant of separation logic that can be converted to dynamic flavor is concurrent separation logic [22].

References

[1] Clarke E.M., Wing J.M. Formal methods: state of the art and future directions. ACM Computing Surveys. 1996; 28(4):626-643. (In Eng.) DOI: https://doi. org/10.1145/242223.242257

[2] Hoare C.A.R. An axiomatic basis for computer programming. Communications of the ACM. 1969; 12(10):576-580. (In Eng.) DOI: https://doi.org/10.1145/363235.363259

[3] Apt K.R., Olderog E.R. Fifty years of Hoare's logic. Formal Aspects of Computing. 2019; 31(6):751-807. (In Eng.) DOI: https://doi.org/10.1007/s00165-019-00501-3

[4] Reynolds J.C. Separation logic: a logic for shared mutable data structures. In: Proceedings 17th Annual IEEE Sympo-

sium on Logic in Computer Science. Copenhagen, Denmark; 2002. p. 55-74. (In Eng.) DOI: https://doi.org/10.1109/ LICS.2002.1029817

iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.

[5] Yang H., O'Hearn P. A Semantic Basis for Local Reasoning. In: Nielsen M., Engberg U. (ed.) Foundations of Software Science and Computation Structures. FoSSaCS 2002. Lecture Notes in Computer Science. 2002; 2303:402-416. Springer, Berlin, Heidelberg. (In Eng.) DOI: https://doi.org/10.1007/3-540-45931-6_28

[6] O'Hearn P.W., Pym D.J. The Logic of Bunched Implications. Bulletin of Symbolic Logic. 1999; 5(2):215-244. (In Eng.) DOI: https://doi.org/10.2307/421090

[7] Harel D., Kozen D., Tiuryn J. Dynamic Logic. MIT Press; 2000. Available at: https://mitpress.mit.edu/books/dy-namic-logic (accessed 02.09.2020). (In Eng.)

[8] Ahrendt W., Beckert B., Bubel R., et al. Deductive Software Verification— The KeY Book. From Theory to Practice. In: Ahrendt W., et al. Lecture Notes in Computer Science. 2016; 10001. Springer, Cham. (In Eng.) DOI: https://doi. org/10.1007/978-3-319-49812-6

[9] Calcagno C., O'Hearn P.W., Yang H. Local Action and Abstract Separation Logic. In: 22nd Annual IEEE Symposium on Logic in Computer Science (LICS 2007). Wroclaw, Poland; 2007. p. 366-378. (In Eng.) DOI: https://doi.org/10.1109/ LICS.2007.30

[10] Parkinson M., Bornat R., Calcagno C. Variables as Resource in Hoare Logics. In: 21st Annual IEEE Symposium on Logic in Computer Science (LICS'06). Seattle, WA, USA; 2006. p. 137146. (In Eng.) DOI: https://doi.org/10.1109/LlCS.2006.52

[11] Troelstra A., Schwichtenberg H. Basic Proof Theory. 2nd ed., Cambridge Tracts in Theoretical Computer Science. Cambridge, Cambridge University Press; 2000. (In Eng.) DOI: https://doi.org/10.1017/CBO9781139168717

[12] Chlipala A. Certified Programming with Dependent Types: A Pragmatic Introduction to the Coq Proof Assistant. MIT Press; 2013. Available at: https://mitpress.mit.edu/ books/certified-programming-dependent-types (accessed 02.09.2020). (In Eng.)

[13] Chlipala A. Proof engineering: implementation challenges in rigorously verified software. In: Proceedings of the Programming Languages Mentoring Workshop (PLMW '15). Association for Computing Machinery, New York, NY, USA; 2015:8. (In Eng.) DOI: https://doi.org/10.1145/2792434.2792442

[14] Eßmann R., Nipkow T., Robillard S. Verified Approximation Algorithms. In: Peltier N., Sofronie-Stokkermans V. (ed.) Automated Reasoning. IJCAR 2020. Lecture Notes in Computer Science. 2020; 12167:291-306. Springer, Cham. (In Eng.) DOI: https://doi.org/10.1007/978-3-030-51054-1_17

[15] Nipkow T. Term rewriting and beyond - theorem proving in Isabelle. Formal Aspects of Computing. 1989; 1(1):320-338. (In Eng.) DOI: https://doi.org/10.1007/BF01887212

[16] Nipkow T., Klein G. Concrete Semantics: With Isabelle/ HOL. Springer, Cham; 2014. (ln Eng.) DOl: https://doi. org/10.1007/978-3-319-10542-0

[17] Sergey I., Wilcox J.R., Tatlock Z. Programming and proving with distributed protocols. Proceedings of the ACM on Programming Languages. 2017; 2(POPL):28. (ln Eng.) DOl: https://doi.org/10.1145/3158116

Vol. 16, No. 3. 2020 ISSN 2411-1473 sitito.cs.msu.ru

Modern Information Technologies and IT-Education

Ц5П ТЕОРЕТИЧЕСКИЕ ВОПРОСЫ ИНФОРМАТИКИ, ПРИКЛАДНОЙ МАТЕМАТИКИ,

550 КОМПЬЮТЕРНЫХ НАУК И КОГНИТИВНО-ИНФОРМАЦИОННЫХ ТЕХНОЛОГИЙ Е М Макаров

[18] Bradley A.R., Manna Z. The Calculus of Computation: Decision Procedures with Applications to Verification. Springer, Berlin, Heidelberg; 2007. (In Eng.) DOI: https://doi. org/10.1007/978-3-540-74113-8

[19] Filliatre J.C., Paskevich A. Why3 - Where Programs Meet Provers. In: Felleisen M., Gardner P. (ed.) Programming Languages and Systems. ESOP 2013. Lecture Notes in Computer Science. 2013; 7792:125-128. Springer, Berlin, Heidelberg. (In Eng.) DOI: https://doi.org/10.1007/978-3-642-37036-6_8

[20] Krebbers R., Jung R., Bizjak A., Jourdan J.H., Dreyer D., Birkedal L. The Essence of Higher-Order Concurrent Separation Logic. In: Yang H. (ed.) Programming Languages and Systems. ESOP 2017. Lecture Notes in Computer Science. 2017; 10201:696-723. Springer, Berlin, Heidelberg. (In Eng.) DOI: https://doi.org/10.1007/978-3-662-54434-1_26

[21] Jung R., Jourdan J.-H., Krebbers R., Dreyer D. RustBelt: securing the foundations of the rust programming language. Proceedings of the ACM on Programming Languages. 2017; 2(POPL):66. (In Eng.) DOI: https://doi. org/10.1145/3158154

[22] Brookes S., O'Hearn P.W. Concurrent separation logic. ACM SIGLOG News. 2016; 3(3):47-65. (In Eng.) DOI: https://doi. org/10.1145/2984450.2984457

[23] Xu F., Fu M., Feng X., Zhang X., Zhang H., Li Z. A Practical Verification Framework for Preemptive OS Kernels. In: Chaudhuri S., Farzan A. (ed.) Computer Aided Verification. CAV 2016. Lecture Notes in Computer Science. 2016; 9780:59-79. Springer, Cham. (In Eng.) DOI: https://doi. org/10.1007/978-3-319-41540-6_4

[24] O'Hearn P. Separation Logic. Communications of the ACM. 2019; 62(2):86-95. (In Eng.) DOI: https://doi. org/10.1145/3211968

[25] Zakharova I., Kuzenkov O. The Experience of Updating the Educational Standards of Higher Education in the Field of ICT. Sovremennye informacionnye tehnologii i IT-obrazo-vanie = Modern Information Technologies and IT-Education. 2017; 13(4):46-57. (In Russ., abstract in Eng.) DOI: https://doi.org/10.25559/SITITO.2017.4.510

[26] Zakharova I., Kuzenkov O. Mathematical Programs Modernization Based on Russian and International Standards. Sovremennye informacionnye tehnologii i IT-obrazovanie = Modern Information Technologies and IT-Education. 2018; 14(1):233-244. (In Eng., abstract in Russ.) DOI: https://doi. org/10.25559/SITITO.14.201801.233-244

[27] Kuzenkov O., Kuzenkova G., Kiseleva T. The use of electronic teaching tools in the modernization of the course "Mathematical modeling of selection processes". Obrazovatel'nye tehnologii i obshhestvo = Educational Technology & Society. 2018; 21(1):435-448. Available at: https://elibrary.ru/ item.asp?id=32253185 (accessed 02.09.2020). (In Russ., abstract in Eng.)

Submitted 02.09.2020; approved after reviewing 14.10.2020; accepted for publication 10.11.2020.

Поступила 02.09.2020; одобрена после рецензирования 14.10.2020; принята к публикации 10.11.2020.

ÂbôûtthëâûthôrHH|HH|HHH||

Evgeny M. Makarov, Senior Instructor of the Department of Algebra, Geometry and Discrete Mathematics, Institute of Information Technology, Mathematics and Mechanics, Lobachevsky State University of Nizhny Novgorod (23 Gagarin Av., Nizhny Novgorod 603950, Russian Federation), Ph.D. (Computer Science), ORCID: http://orcid.org/0000-0003-0399-0946, evgeny.makarov@itmm. unn.ru

The author has read and approved the final manuscript.

|об авторе:|

Макаров Евгений Маратович, старший преподаватель кафедры алгебры, геометрии и дискретной математики, Институт информационных технологий, математики и механики, ФГА-ОУ ВО «Национальный исследовательский Нижегородский государственный университет им. Н.И. Лобачевского» (603022, Российская Федерация, г. Нижний Новгород, пр. Гагарина, д. 23), ORCID: http://orcid.org/0000-0003-0399-0946, evgeny makarov@itmm.unn.ru

Автор прочитал и одобрил окончательный вариант рукописи.

Современные информационные технологии и ИТ-образование

Том 16, № 3. 2020 ISSN 2411-1473 sitito.cs.msu.ru

i Надоели баннеры? Вы всегда можете отключить рекламу.