Logica Relacional:
Transcription
Logica Relacional:
problem ::= decl form decl ::= var : typexpr typexpr ::= type | type → type Formulas | type ⇒ typexpr M : form → en X : expr → env env = (var + t value = (atom (atom → val Logica Relacional: form ::= expr in expr (subset) |!form (neg) | form && form (conj) | form || form (disj) | all v : type/form (univ) | some v : type/form (exist) expr ::= expr + expr (union) | expr & expr (intersection) | expr − expr (difference) |∼ expr (transpose) M [a in b]e = X M [!F ]e = ¬M [ M [F &&G]e = M [F || G]e = M M! [all v : t/F ] = {M [F ](e ⊕ M" [some v : t/F {M [F ](e ⊕ X[a + b]e = X[ X[a&b]e = X[a X[a − b]e = X[ X[∼ a]e = { .x X[a.b]e = X[a] expr in expr (subset) |!form (neg) | form && form (conj) | form || form (disj) | all v : type/form (univ) Expresiones | some v : type/form (exist) Logica Relacional: expr ::= expr + expr (union) | expr & expr (intersection) | expr − expr (difference) |∼ expr (transpose) | expr.expr (navigation) | +expr (transitive closure) | {v : t/form} (set former) | V ar V ar ::= var (variable) | V ar[var] (application) M [F &&G]e = M [F || G]e = M! [all v : t/F {M [F ](e M" [some v : t/ {M [F ](e X[a + b]e = X X[a&b]e = X X[a − b]e = X X[∼ a]e = { . X[a.b]e = X[a X[+a]e = the r ;r ⊆ r and X[{v : t/F }]e {x ∈ e(t)/M X[v]e = e(v) X[a[v]]e = {. ∃x. .x, y1 , . Logica Relacional: Semantica de las Formulas oblem ::= decl∗ form cl ::= var : typexpr pexpr ::= pe ype → type ype ⇒ typexpr m ::= pr in expr (subset) orm rm (neg) orm rm && form (conj) orm rm || form (disj) ll v : type/form (univ) ome v : type/form (exist) pr ::= pr + expr (union) xpr & expr (intersection) xpr − expr (difference) M : form → env → Boolean X : expr → env → value env = (var + type) → value value = (atom × · · · × atom)+ (atom → value) M [a in b]e = X[a]e ⊆ X[b]e M [!F ]e = ¬M [F ]e M [F &&G]e = M [F ]e ∧ M [G]e M [F || G]e = M [F ]e ∨ M [G]e M! [all v : t/F ] = {M [F ](e ⊕ v*→{ x })/x ∈ e(t)} M" [some v : t/F ] = {M [F ](e ⊕ v*→{ x })/x ∈ e(t)} X[a + b]e = X[a]e ∪ X[b]e X[a&b]e = X[a]e ∩ X[b]e X[a − b]e = X[a]e \ X[b]e X[∼ a]e = { .x, y/ : .y, x/ ∈ X[a]e } caches are small istic) operation t main memory ca fun Flush(s, some x: s’.ca s’.ca s’.m {a } } In the third line x->Data denotes into the set x, an e ⇒ typexpr M [a in b]e = X[a]e ⊆ X[b]e ::= M [!F ]e = ¬M [F ]e in expr (subset) M [F &&G]e = M [F ]e ∧ M [G]e m (neg) M [F || G]e = M [F ]e ∨ M [G]e m && form (conj) M! [all v : t/F = Semantica de] las Expresiones m || form (disj) {M [F ](e ⊕ v*→{ x })/x ∈ e(t)} lem ::= decl∗ form v : type/form (univ) M" : form v→: t/F env] → [some = Boolean ::= var : typexpr me v : type/form (exist) X : expr {M [F→ ](eenv ⊕ v*→ →{value x })/x ∈ e(t)} xpr ::= env = (var + type) → value ::= value × ·∪ · · X[b]e × atom)+ X[a + = b]e(atom = X[a]e e+→ type expr (union) (atom = → X[a]e value)∩ X[b]e X[a&b]e er ⇒ typexpr & expr (intersection) X[a − b]e = X[a]e \ X[b]e r − expr (difference) M [a in X[a]e ⊆ X[b]e X[∼ a]eb]e = {=.x, y/ : .y, x/ ∈ X[a]e } ::=(transpose) xpr M [!F ]e = ¬M [F ]e X[a.b]e X[a]e;X[b]e in expr (subset) r.expr (navigation) M [F &&G]e = smallest M [F ]e ∧rM [G]ethat X[+a]e = the such m xpr(neg) (transitive closure) M r[F;r||⊆G]e =M [F ]e ∨ r and X[a]e ⊆M r [G]e mt/form} && form (conj) (set former) M [all: vt/F : t/F = X[{v }]e] = ! m || form (disj) r [F ](e ⊕[F v*→ x })/x e(t)} {x{M ∈ e(t)/M ](e{ ⊕ v*→{ ∈ x })} v : type/form (univ) M [some v : t/F ] = X[v]e = e(v) " me ::=v : type/form (exist) {M [F ⊕1 ,v*.→ })/x X[a[v]]e =](e {.y . .{,xyn // ∈ e(t)} (variable) ∃x. .x, y1 , . . . , yn / ∈ e(a) ∧ .x/ ∈ e(v)} ::= r[var] (application) X[a + b]e = X[a]e ∪ X[b]e + expr (union) X[a&b]e = X[a]e ∩ X[b]e r & expr (intersection) b]e = X[a]e \ of X[b]e Figure 2: Grammar X[a and− semantics Alloy r − expr (difference) X[∼ a]e = { .x, y/ : .y, x/ ∈ X[a]e } Logica Relacional: fun Flush some s’ s’ s’ caches are } sm istic)} operatio main memory In the third l fun Flush x->Data deno some into the set x, tion Flush wis’ s’ the main prob Functions s’ c instance, we c lines not }mark } fun Dirty In the third all al x->Data deno into the set x, El Lenguaje de Especificacion Alloy Lenguaje de especificacion cuyo lenguaje y semantica estan basados en la logica relacional. Provee mecanismos para definir tipos similar a las clases de los lenguajes orientados a objetos. Permite introducir axiomas y operaciones que determinan el modelo formal. Alloy: Ejemplos: Grafos sig Nodo { } sig Grafo { nodos : set Nodo arcos : nodos -> nodos } Alloy: Ejemplos: Grafos Conexos module grafosconexos sig Nodo { } one sig Grafo { nodos : set Nodo, arcos : nodos -> nodos } fact conexo { all disj n1, n2 : Grafo.nodos | n2 in n1.(^(Grafo.arcos + ~(Grafo.arcos))) } assert noTieneAislado{all n : Grafo.nodos | some n.(Grafo.arcos) || some n.(~(Grafo.arcos))} check noTieneAislado for 5 Alloy: Ejemplos: Grafos Aciclicos module grafoaciclico sig Nodo { } one sig Grafo { nodos : set Nodo, arcos : nodos -> nodos } fact acyclic { no ^(Grafo.arcos) & iden } Alloy: Ejemplos: Grafos Aciclicos Dirigidos module grafoaciclicodirigido sig Nodo { } one sig Grafo { nodos : set Nodo, arcos : nodos -> nodos } fact acyclic { no ^(Grafo.arcos) & iden } fact hasRoot { one n : Grafo.nodos | n.(*(Grafo.arcos)) = Grafo.nodos } pred conexo() { all disj n1, n2 : Grafo.nodos | n2 in n1.(^(Grafo.arcos + ~ (Grafo.arcos))) } assert DAGConexo {conexo()} check DAGConexo for 8 Alloy: Ejemplos: Listas encadenadas module listaSimplementeEncadenada sig Data {} sig List { first : lone Data, next : lone List } one sig Empty extends List {} fact emptyIsEmpty {no Empty.first && no Empty.next} fact allToEmpty {all l : List | Empty in l.*next} assert acyclic {all l : List | l not in l.(^next)} check acyclic for 7 Como obtener Alloy? http://alloy.mit.edu Disponible para numerosas plataformas. Fundamentos de DynAlloy: Logica Dinamica Logica que permite modelar evolucion de los estados. Permite modelar propiedades de la ejecucion de programas secuenciales no-deterministicos. main.map . een specified, Sintaxis de la Logica Dinamica DSFlush(s)} (15) T to formula lting formula. R DYNAMIC us for reasoncalling Fig. 1, uced in Fig. 8. ) can be suc- set of function symbols, and P is the set of atomic predicate symbols. Atomic actions contain input and output formal parameters. These parameters are later instantiated with actual variables when actions are used in a specification. The sets of programs and formulae on Σ are mutually defined in Fig. 9. action ::= a1 , . . . ak (atomic actions) | skip | action+action (nondeterministic choice) | action;action (sequential composition) | action∗ (finite iteration) | dform? (test) expr ::= var | f (expr1 , . . . , exprk ) (f ∈ F with arity k) dform ::= p(expr1 , . . . , exprn ) (p ∈ P with arity n) | !dform (negation) | dform && dform (conjunction) | dform || dform (disjunction) | all v : type | dform (universal) | some v : type | dform (existential) | [action]dform (box) Figure 9: Syntax of dynamic logic Semantica de la Logica Dinamica Q : form → ST → Boolean P : action → P (ST × ST ) Z : expr → ST → s Q[p(t1 , . . . , tn )]µ = (Z[t1 ]µ, . . . , Z[tn ]µ) ∈ env(p) (atomic formula) Q[!F ]µ = ¬Q[F ]µ Q[F &&G]µ = Q[F ]µ ∧ Q[G]µ Q[F || G]µ = Q[F ]µ ! ∨ Q[G]µ Q[all v : t | F ]µ = {Q[F ](µ ⊕ v'→x) | x ∈ env (t)} " Q[some v : t ! | F ]µ = {Q[F ](µ ⊕ v'→x) | x ∈ env (t)} Q[ [a]F ]µ = {Q[F ]ν | (µ, ν) ∈ P (a)} P [a] = env (a) (atomic action) P [skip] = { (µ, µ) : µ ∈ ST } P [a + b] = P [a] ∪ P [b] P [a;b] = P [a]◦P [b] P [a∗ ] = (P [a])∗ P [α?] = { (µ, µ) : Q[α]µ } Z[v]µ = µ(v) Z[f (t1 , . . . , tk )]µ = env (f )(Z[t1 ]µ, . . . , Z[tk ]µ) Figure 10: Semantics of dynamic logic h : A → B be th B we will defin and predicate sy – Actions: # env (a), wh ing (h−1 (s – Functions: – Predicates By constructio The previous uses [14, Thm. 4 rather than plai theory Ψ is a s Such a structur its domain. The are not a set of b Ejemplo de Especificacion en Logica Dinamica all x : Nat | x = x0 => [A(x)](x = x0+1) (x=x0 && y=y0) => [Swap(x,y)](x=y0 && y=x0) (x=x0 && y=y0) => [Swap(x,y) ; Swap(x,y)](x=x0 && y=y0) Programas via Acciones Programa atomico via accion atomica (por ejemplo +1, o Swap) P1 ; P2 ---> T(P1) ; T(P2) if C then P1 else P2 fi ---> C? ; T(P1) + (!C)? ; T(P2) while C do P ---> (C? ; T(P))* ; (!C)? Aserciones de Correccion Parcial pre => [P]post La formula es satisfecha for aquellos estados que satisfacen “pre”, y para los cuales todo estado alacanzable por P satisface “post”. P pre(s) post(s1) P post(s2) P !post(s3) Como analizar aserciones de correccion parcial? Mediante el calculo de la precondicion mas debil de un programa. Permite caracterizar los estados que satisfacen la asercion en logica de primer orden. ! use names " (composite action). Wey!will in general x , x . . . for program variables, 1 2 ! n y n wlp[a(y), f ] = pre| n value post|xof =⇒ f |yvariables . ! |xprogram ! . . . forallthe after (5) action exeand will use names x!1 ,xx!2 , =⇒ v cution. We will denote by α| substitution all freethat occurrences of variable x x the (5). few points need to be explained about First, weofassume free variables the fresh v in formula α. generated by the translation function are by amongst y ! , variable x0 . Variables in x0 are atomic naction specified as #pre, post$(x) used in variable a composite acgiven When in (7).anSecond, is anaarray of new variables, oneisfor each formal parameters are substituted by actual parameters. Sinceitswefree assume all ifiedtion, by the action. Last, notice that the resulting formula has again actualinparameters are variables, blesvariables amongstare y ! ,input/output x0 . This is variables, also preserved the remaining cases in let theus say, y. situation, itionInofthis function wlp.function wlp is defined as follows: ! " ! ! y definition of function n ywlp is the n r the remaining action constructs, the following: wlp[a(y), f ] = pre| =⇒ all n post| | =⇒ f | . (5) ! x x x y! wlp[g?, f ] = g =⇒ f A few points need to be explained about (5). First, we assume that free variables wlp[p1! + p2 , f ] = wlp[p1 , f ] ∧ wlp[p2 , f ] in f are amongst y , x0 . Variables in x0 are generated by the translation function wlp[p1 ;p2 , f ] = # wlp[p1 , wlp[p2 , f ]] pcat given in (7). ∗ Second, n is an ∞ array of new variables, one for each variable wlp[p , f ] = i=0 wlp[pi , f ] . modified by the action. Last, notice that the resulting formula has again its free oticevariables that wlp amongst yields Alloy these cases, except the iteration y ! , formulas x0 . Thisinisall also preserved in thefor remaining cases in the truct, where the resultingwlp. formula may be infinitary. In order to obtain an definition of function y formula, we can imposeaction a bound on the depth of iterations. This iswlp equivalent For the remaining constructs, the definition of function is the following: xing a maximum length for traces. A function Bwlp (bounded weakest liberal wlp[g?, f ] = g =⇒ f ondition) is then defined exactly as wlp, except for iteration, where it is defined wlp[p1 + p2 , f ] = wlp[p1 , f ] ∧ wlp[p2 , f ] wlp[p1 ;p2 , fn] = # wlp[p1 , wlp[p2 , f ]] $ ∞ i ∗ wlp[p , f] . wlp[p = ∗ , f] i Bwlp[pi=0 , f] . (6) Bwlp[p , f ] = Calculo de la Precondicion mas Debil Entonces... Una formula pre => [P]post es valida cuando pre => wlp(P,post) es valida. DynAlloy Extension de Alloy para facilitar el analisis de propiedades de ejecuciones. Mejor separacion de intereses que utilizando trazas directamente en la especificacion. El “DynAlloy Analyzer” permite analizar especificaciones DynAlloy automaticamente. ction Write. This time, “after ” means that m! gets its value in an environment eachable through the execution of action Write (cf. Fig. 3). Since Write denotes a inary relation on the set of environments, there is a precise notion of input/output nducing a before/after relationship. Sintaxis de DynAlloy .2 Syntax and Semantics of DynAlloy he syntax of DynAlloy’s formulas extends the one presented in Fig. 1 with the ddition of the following clause for building partial correctness statements: Efficient program Analysis of{f DynAlloy Specifications f ormula ::= . . . | {f ormula} ormula} “partial correctness” · 11 The syntax for programs Fig. 2) is the class of regular programs program ::=(cf. !f ormula, f ormula"(x) “atomicdefined action”in Harel et al. 2000], plus a new rule to allow for the construction of atomic “test” actions | f ormula? om their pre and post conditions. In+the definition of atomic actions, xchoice” denotes | program program “non-deterministic sequence of formal parameters. Thus, it is to be expected that the precondition | program;program “sequential composition” ∗ a formula whose free variables are within x, while postcondition variables might | program “iteration” lso include primed versions of the formal parameters. CM Transactions on Software and Methodology, Vol. TBD, No. in TDB, Month Year. Fig. Engineering 2. Grammar for composite actions DynAlloy In Fig. 3 we extend the definition of function M to partial correctness assertions and define the denotational semantics of programs as binary relations over env . The definition of function M on a partial correctness assertion makes clear that we are actually considering a partial correctness semantics. This follows from the fact that we are not requesting environment e to belong to the domain of the relation P [p]. and d keep their initial values. This allows us to use simpler formulas in pre and post conditions. Notice that, since parallel composition of actions is not an allowed action combinator, this assumption does not restrict the sound composition of actions or programs. Although parallel composition is not available, one could still define it by means of interleaving of atomic actions, via nondeterministic choice and sequential composition, as usual in concurrent programming. Semantica de DynAlloy M [{α}p{β}]e = M [α]e =⇒ ∀e! !" # $ e, e! ∈ P [p] =⇒ M [β]e! P : program → P (env × env ) P [&pre, post'] P [α?] P [p1 + p2 ] P [p1 ;p2 ] P [p∗ ] Fig. 3. 3.3 = = = = = A(&pre, post') { &e, e! ' : M [α]e ∧ e = e! } P [p1 ] ∪ P [p2 ] P [p1 ];P [p2 ] P [p]∗ Semantics of DynAlloy. Specifying Properties of Executions in Alloy and DynAlloy Suppose that we want to specify that a given property P is invariant under sequences of applications of the operations “SysFlush” and “SysWrite”, from certain 2.Suppose THE ALLOY SPECIFICATION LANGUAGE we want to specify systems involving memories with cache. We might recognize that, inweorder to specify memories, types for data and addresses are In this section, introduce the reader to thedata Alloy specification language by means especially necessary. We can start et byal. indicating the example existenceserves of disjoint sets of an example extracted fromthen [Jackson 2001]. This as a means (of for data and addresses, which in language Alloy areand specified using signatures: foratoms) illustrating the standard features of the their associated semantics, the shortcomings overcome by our alternative semantics, and will be used as a basis sig Addr { } sig Data { } for the properties of traces we will analyze. Suppose we want to specify systems involving with cache. We might These are basic signatures. We do not assume any memories special properties regarding the recognize that, in order to specify memories, data types for data and addresses are structures of data and addresses. especially We can then defined, start by we indicating existence disjoint sets With datanecessary. and addresses already can nowthe specify whatof constitutes a (of atoms) for data and addresses, which in Alloy are specified using signatures: memory. A possible way of defining memories is by saying that a memory consists of a set of addresses, and a (total) mapping from these addresses to data values. In sig Addr { } sig Data { } our case, we will use memories in order to model what is common to a cache and aThese main memory, the signature must declared abstract: are basic so signatures. We do notbe assume anyas special properties regarding the of data and addresses. 6 structures · Marcelo F. Frias et abstract al. sig Memory { With data and addresses already defined, we can now specify what constitutes a addrs: set Addr, memory. A possible way of defining memories is by saying that a memory consists 6 · Marcelo F. Frias et al. map: addrs -> lone Data For the example, one could define other (perhaps more complex) kinds of memories of a set of addresses, and a (total) mapping from these addresses to data values. In } signature: as extensions of the Memory our case, weexample, will use memories in order to model what is common a cache and For the one could define other (perhaps more complex)tokinds of memories a main memory, soofin the signature must be declared as abstract: The modifier “lone” the above definition indicates that sig MainMemory extends Memory {}“map” is functional and as extensions the Memory signature: total (for each element a of addrs, there exists exactly one element d in Data such abstract sig Memory { sig MainMemory extends that map(a) = d). sig Cache extends Memory { Memory {} addrs: set Addr, Alloy allows for the definition signatures as subsets of the set denoted by dirty: setofaddrs map: addrs -> lone Data sig Cache extends another “parent” signature. This is done via Memory what is {called signature extension. } } dirty: set addrs ACM Transactions on Software Engineering and Methodology, Vol. TBD, No. TDB, Month Year. As specified in these definitions, MainMemory and Cache are special kinds of mem}above The modifier “lone” in the indicates ories. In caches, a subset of addrs isdefinition recognized as dirty.that “map” is functional and total (for each element of addrs, exists exactly one element dand in Data such As specified in these MainMemory Cache are special of memA system might now bea definitions, defined to there be composed ofand a main memory akinds cache: thatories. map(a) = d). In caches, a subset of addrs is recognized as dirty. sig {to be composed AlloyA allows the now definition of signatures as subsets of thememory set denoted systemfor might be System defined of a main and a by cache: cache: Cache, another “parent” signature. This is done via what is called signature extension. sig System { main: MainMemory ACM Transactions on Software Engineering and Methodology, Vol. TBD, No. TDB, Month Year. cache: Cache, } main: MainMemory As the previous definitions show, }signatures are used to define data domains and their structure. The attributes of a signature denote relations. For instance, the the previous definitions show,represents signaturesa are usedrelation, to definefrom datamemory domains and “addrs” As attribute in signature Memory binary their structure. The attributes of a signature denote relations. For instance, atoms to sets of atoms from Addr. Given a set m (not necessarily a singleton) the “addrs” attribute in signature represents binary relation, from memory of Memory atoms, m.addrs denotes Memory the relational imagea of m under the relation Ejemplo: {α} A {β} affirms that whenever action A is executed on a state satisfying α, if it terminates, it does so in a state satisfying β. This approach is particularly appropriate, since behaviors described by functions are better viewed as the result of performing an action on an input state. Thus, the definition of function Write could be expressed as an action definition, of the following form: Ejemplo (continuacion) {true} Write(m : Memory, d : Data, a : Addr) (3) {m! .map = m.map ++ (aEfficient → d)}Analysis . of DynAlloy Specifications At first glance it is difficult to see the differences between (1) and (3), since { true }the same information. The crucial differences are both formulas seem to provide reflected in the semantics,SysWrite(s: as well as System) in the fact that actions can be sequentially composed, iterated or composed by nondeterministic choice, while Alloy functions, { some d: Data, a: Addr | in principle, cannot. s’.cache = s.cache ++ (a d) and An immediately apparent difference between (1)→and (3) is that action Write ! s’.cache.dirty s.cache.dirty a and does not involve the parameter m , while=function Write+uses it. This is so because ! s’.main = s.main we use the convention that m denotes the}state of variable m after execution of action Write. This time, “after ” means that m! gets its value in an environment { true } of action Write (cf. Fig. 3). Since Write denotes a reachable through the execution binary relation on the set of environments, there is a precise notion of input/output SysFlush(s: System) inducing a before/after relationship. · 13 { some x: set s.cache.addrs | Syntax and Semantics of DynAlloy s’.cache.map = s.cache.map - x→Data and The syntax of DynAlloy’ss’.cache.dirty formulas extends the one presented = s.cache.dirty - x and in Fig. 1 with the addition of the following clause for building partial correctness statements: s’.main.map = s.main.map ++ Data | d = s.cache.map[a]} } f ormula ::={a: . . .x,| d: {f ormula} program {f ormula} “partial correctness” Notice that the previous specifications are as understandable as the ones given Alloy. Moreover, byisusing partial statements on in the set of regular The syntax for in programs (cf. Fig. 2) the class of correctness regular programs defined programs generated thefor setthe of construction atomic actions SysWrite, SysFlush }, we can [Harel et al. 2000], plus a new rule to by allow of {atomic actions assert the invariance of a property P under finite applications of functions SysWrite 3.2 } } In the third line of the above definition of function SysFlush, x->Data denotes the set of all ordered pairs whose first elements fall into the set x, and whose second elements range over Data. (continuacion) Functions can also be used to represent special states. For instance, we can characterize the states in which the cache lines not marked as dirty are consistent with main memory: Ejemplo pred DirtyInv(s: System) { all a : !s.cache.dirty | s.cache.map[a] = s.main.map[a] } (2) In this context, the symbol “!” denotes negation, indicating in the above formula that “a” ranges over atoms that are non dirty addresses. { DirtyInv(s) } 2.2 Properties of a Model (SysWrite(s) + SysFlush(s))* As the reader might expect, a model can be enhanced by adding properties (axioms) { DirtyInv(s’) } to it. These properties are written as logical formulas, much in the style of the ACM Transactions on Software Engineering and Methodology, Vol. TBD, No. TDB, Month Year.