20

Successes in Logic Programs

Embed Size (px)

Citation preview

Successes in Logic ProgramsAnnalisa Bossi, Nicoletta CoccoDip. di Matematica Applicata e InformaticaUniversit�a di Venezia-Ca' Foscari - Italybossi, [email protected]. In this paper we study how to verify that a pure Prologprogram has solutions for a given query. The detailed analysis of thefailure/success behaviour of a program is necessary when dealing withtransformation and veri�cation of pure Prolog programs. In a previouswork [10] we de�ne the class of noFD programs and queries which cannothave �nitely failing derivations. Now by introducing the concept of a setof exhaustive tests, we de�ne the larger class of successsful predicates. Weprove that such predicates have at least a successful derivation for anynoFD terminating query. Moreover we propose some techniques based onprogram transformations for simplifying the veri�cation of the successfulcondition.Keywords and Phrases: pure Prolog programs, failure/success analysis,program transformations1 IntroductionWhen developing a logic program we, more or less explicitly, have to analize itwith respect to correctness, termination properties and the existence of success-ful computations. On correctness and termination veri�cation there have beenrather many proposals such as [21, 8, 3, 12, 7, 24]. While for distinguishing fail-ing and successful computations or for ensuring the presence of successes in acomputation, very little is available, both in terms of methodology and tools.We can illustrate the kind of information on derivations we would like to inferthrough a few simple examples.Example 1. Let us considerreverse([], [ ]).reverse([X jXs], Zs) reverse(Xs, Ys), append(Ys, [X], Zs).app([], Ys, Ys).app([X jXs], Ys, [X jZs]) app(Xs, Ys, Zs).with directional type reverse(+ : List;� : List) and app(+ : List;+ : List;� :List).This well-known program shows the simplest case: a program which does notproduce �nitely failing derivations (FDs) when correctly queried. 2In a previous work [10] we have given a su�cient condition for ensuring that agiven program and query are without failures, namely they cannot have �nitelyfailing derivations (noFD). Basically we formalize the following two observations.

Let us consider reverse (or app), it is de�ned for any input in the directionaltype, hence any correct query cannot cause a failure in input. Furthermore outputterms in the body of its clauses are \new" variables, not appearing leftmost,hence reverse cannot cause a failure in output since when the LD-resolutionwill reach the output terms, they will be still variables and then instantiable.As a consequence a well-typed query with \new" variables in output will nothave FDs. The condition we give in [10] is very restrictive, since we want it tobe simple and veri�able from the text of the program.The requirement of not having FDs is useful in program transformations whenwe assume a Prolog interpreter, (this was our main motivation in [10]) and whenreasoning on e�ciency, but it is too strong in general. In fact in many cases wecannot expect the program not to have FDs, we would be satis�ed to know thatthe program has at least a successful derivation for a given query.Example 2. Let us considerdelete([], X, [ ]).delete([X jXs], X, Ys) delete(Xs, X, Ys).delete([X jXs], Z, [X jYs]) X 6= Z, delete(Xs, Z, Ys).with directional type delete(+ : List;+ : Any;� : List).This program can produce FDs since it contains uni�cation tests, namelyX 6= Z,which can fail. But, by examining also the heads of the clauses, we could observethat all possible cases are de�ned, namely they are exhaustive on the input types.Hence, since the directional type guarantees termination, delete can be queriedwith at least one successful derivation. 2Example 3. Now let us consider:posPivot(L, Pos) oddLength(L, Length), Pos is Length div 2 +1.posPivot(L, 0) evenLength(L, Length).oddLength(L, N) length(L, N), odd(N).evenLength(L, N) length(L, N), even(N).with directional type: posP ivot(+ : List;� : Nat), evenLength(+ : List;� :Nat), oddLength(+ : List;� : Nat), length(+ : List;� : Nat) and even(+ :Nat), odd(+ : Nat).In this program the predicates evenLength(L;N) and oddLength(L;N) are usedas tests and they can cause FDs. But also in this program we could show thatthe tests are exhaustive on the input types. Since the directional type ensurestermination, we can also show that posP ivot can be queried with at least onesuccessful derivation. 2From these few examples it should be evident that the failure/success analysisof a logic program is not such a simple task. The simple condition we de�nein [10], for ensuring that a program has no FDs, applies only to a rather smallclass of programs. Many programs have FDs since they use tests, which byde�nition are assumed to fail for some inputs. On the other hand, programswith tests generally use them to de�ne a di�erent behaviour for each possible

input, namely they generally use a set of exhaustive tests. Hence in order torecognize that a program has at least one solution for a given query, we have tobe able to recognize a set of exhaustive tests. Tests are not easy to characterize,they can be prede�ned and with input only, as in Example 2, or de�ned by theuser and supplying also an output, as in Example 3. In this paper we intendto explore all these cases and to give a general methodology for failure/successanalysis.In Section 2 we set some notation and recall the de�nitions of noFD programand query. In Section 3 we give a general de�nition for a set of exhaustive testsfor a predicate and we use it to de�ne the class of successful predicates. We provethat a noFD query, de�ned by successful predicates, has at least one successfulLD-derivation, if it universally terminates. In section 4 we propose some tech-niques, based on program transformations, for simplifying the veri�cation of thesuccessful property and describe a methodology for verifying that a predicate issuccessful. Conclusions follows in section 5.2 Basic NotionsGiven a substitution � and a set of variablesX , we denote by �jX the substitutionobtained from � by restricting its domain toX . Given an expression (term, atom,query,. . . ) E, we denote the set of variables occurring in it by Var(E). We oftenwrite �jE to denote �jVar(E). A renaming is a substitution which is a permutationof its domain. We write E � E0 to denote that E and E0 are variant expressions,that is there exists a renaming � such that E = E0�. When a renaming of Emaps V ar(E) in \new" variables we call it a new renaming of E and we speakof E� as a new variant of E.We consider de�nite logic programs executed by means of LD-resolution, whichconsists of the usual SLD-resolution combined with the leftmost selection ruleas Prolog interpreters do. Throughout the paper we use queries instead of goals.A query is a sequence of atoms or fail. fail stands for the query associatedto a failure and 2 for the empty query. An LD-derivation ending with 2 is asuccessful LD-derivation, one ending with fail is a failing one (FD).We consider the property of universal termination for a query Q in a programP , which means that the LD-tree of Q in P is �nite. This termination propertyhas been widely studied [7, 12, 24] and it ensures termination with a Prologinterpreter.We denote sequences by bold characters and we call p(X) a general atom when itsterms are all distinct variables. We use identi�ers to label clauses and derivations.Then l : Q j ���!P R stands for "an LD-derivation, l, of the queryQ in P , whichends in the query R and � is the composition of the relevant and idempotentmgu0s applied during the derivation". Similarly Q j ���!P 2 denotes a successfulLD-derivation of Q in P with c.a.s. �jQ. Q j ��!P R denotes one derivationstep, we say that it is non-trivial if R is not fail. The length of an LD-derivationl is denoted by j l j.The rest of the notation is more or less standard and essentially follows [23, 1].

We make use of the notion of modes and types introduced in [14, 5, 2]. We con-sider a combination of modes and types and adopt the following assumption:every considered relation has a �xed mode and a �xed type associated with it.This assumption allows us to talk about types of input positions and of outputpositions of an atom. For example, app(+ : List;+ : List;� : List) denotes aternary relation app with the �rst two positions moded as input and typed asList and the third position moded as output and typed as List. A similar deno-tation is called a directional type in [13]. From [5, 2] we take also the notion ofwell-typed query and program, which guarantees that mode and type propertiesare preserved through LD-resolution, and from [4] the notion of simply modedclause and query. Here we recall only the main de�nition of well-typed program.To simplify the notation, when writing an atom as p(u : S;v : T), we assumethat u : S is a sequence of typed terms �lling in the input positions of p andv : T is a sequence of typed terms �lling in the output positions of p.De�nition 1 (Well-typed query, clause, program [2]).{ A query p1(i1 : I1;o1 : O1); : : :; pn(in : In;on : On) is well-typed i�for j 2 [1; n] j= o1 : O1; : : :;oj�1 : Oj�1 ) ij : Ij:{ A clause p0(o0 : O0; in+1 : In+1) p1(i1 : I1;o1 : O1); : : :; pn(in : In;on : On):is well-typed i� for j 2 [1; n+ 1]j= o0 : O0; : : :;oj�1 : Oj�1 ) ij : Ij:{ A program is well-typed i� every clause of it is. 2Note that a query with only one atom is well-typed i� this atom is correctlytyped in its input positions.Besides we need the following de�nitions.De�nition 2 (simply moded sequence). Let P be a well-typed program andQ = B1; : : :; Bm a well-typed query in P . The input (output) terms of Q, de-noted by In(Q)(Out(Q)), are the terms in input (output) positions in Q.Q is simply moded i� output positions are �lled in with distinct variableswhich do not appear leftmost, namely 8j 2 [1;m], Out(Bj) = V ar(Out(Bj )); ifX1; : : :; Xk are the output terms in Bj , then Xi 6= Xh, for i 6= h, i; h 2 [1; k];and Out(Bj) \ (V ar(B1; : : :; Bj�1) [ V ar(In(Bj))) = ;. 2A simply moded sequence is exactly what is called simply moded query in [4].De�nition 3 (input-correct and simply moded instance). Let A be ansimply moded atom and � a substitution. We say that A� is an input-correctand simply moded instance of A i� A� is correctly typed in input and Out(A�)is a new variant of Out(A). 2

Intuitively in an LD-derivation, FDs may happen when some term is instantiatedin an "incorrect" way, namely this means that for avoiding FDs, inputs must becorrectly given, while outputs should be correctly instantiated by the evaluation.In [10] we de�ne an interesting class of programs: programs without failures(noFD programs). These programs have a clear functionality from input to out-put but they can be non-deterministic. They satisfy the strong property that, inan LD-derivation, for any selected atom correctly typed in input positions andwith uninstantiated variables in output positions, there exists a unifying clausein P .De�nition 4 (noFD program). Let P be a well-typed program.A clause c : H A1; : : :; An: in P is without failures (noFD clause) i�1. c is simply moded (namely the sequence of atoms in the body, A1; : : :; An, issimply moded and V ar(In(H)) \ V ar(Out(A1; : : :; An)) = ;);2. for all i 2 [1; n] and for any input-correct and simply moded instance Ai� ofAi, there exists a clause in P whose head uni�es with Ai�.A predicate p in P is without failures (noFD predicate) i� all the clauses in (thedeductive closure of) its de�nition in P are noFD ones. The program de�ning pis then a program without failures (noFD program). 2De�nition 5 (noFD query). Let Q = B1; : : :; Bm be a well-typed query.Q is without failures (noFD query) in a program P i�1. the query Q is simply moded;2. for j 2 [1;m] and for any input-correct and simply moded instance Bj� ofBj , there exists a clause in P whose head uni�es with Bj�. 2The condition for being noFD is local, namely each clause can be consideredseparately. Only atoms in the clause bodies and in the queries have to satisfythe restrictions, on the head atoms no restriction is required. Hence a well-typed program containing only facts is trivially noFD. Note also that the �rstconditions are syntactic ones and then very simple to verify. The last conditionis more complex but, if a type de�nition is available, it can be statically veri�edsince it just requires uni�cation. Hence the noFd-condition is decidible.For example given the de�nition of list, we can easily verify that reverse andapp in Example 1 are noFD programs.Let us consider the two queries Q1 = app([X ]; [2]; [X jXs]) and Q2 = app([1]; [2];[X jXs]) with the app program in Example 1. These queries are well-typed butthey are not simply moded. Hence they are not noFD queries; they have no FDsthough. This shows us that the noFD property is a su�cient conditions, but notnecessary to absence of FDs.noFD programs and queries form a rather restricted class since output terms inthe query and in body atoms must always be uninstantiated variables. Moreovertests are not allowed. Let us consider the programs in Examples 2, 3. They are

not noFD. The presence of test predicates in the bodies make impossible to thesecond condition in the noFD de�nition to be satis�ed for all clauses.In [10] we also prove the \persistency" of the noFD property through LD-derivation and the main result, namely that a noFD query in a noFD programcannot have FDs.Lemma 1. Let P be a noFD program and Q a noFD query in P . Let us considerone non-trivial LD-derivation step Q j ��!P Q0. The query Q0 is also noFD. 2Theorem 1. Let P be a noFD program and Q a noFD query in P . Then Qcannot have �nitely failing derivations. 2In [10] we also discuss the use of noFD condition both in the �eld of veri�cationof program properties and in the �eld of program transformations. We give someexamples showing how the noFD property can greatly simplify the applicabilityconditions of transformation operations, such as decreasing unfolding, replace-ment and switch, in transformation systems which take into account terminationproperties.3 Successful PredicatesAs we saw the �rst condition in noFD de�nition is simple but restrictive sinceit forbids compound terms in output. This could be either bypassed by programtransformation or weakened by allowing also restricted compound terms in out-put.The second solution could be obtained by considering nicely moded clauses andqueries [16] instead of simply moded ones. This would allow also compoundterms in output, but they must contain only \new" variables. Nicely modedprograms have been studied in connection with uni�cation freedom properties.This enlargement would rather complicate the veri�cation of the noFD propertysince we should check also the type structure in the compound terms.The �rst solution can be illustrated by means of a simple example.Example 4. Let us considerlast(L, E) reverse(L, [E| Xs]).with directional type last(+ : List;� : Any) and reverse(+ : List;� : List).This program is not noFD since the atom reverse(L; [EjXs]) is not simplymoded. But we could transform it into the equivalent programlast(L, E) reverse(L, Zs), selFirst(Zs, E).selFirst([X| Xs], X).with directional type last(+ : List;� : Any), reverse(+ : List;� : List) andselF irst(+ : List;� : Any).This program is noFD. 2

Hence by explicitly introducing subterm selectors and constructors it is possibleto transform a non-noFD program into a noFD one.Let us consider now the second, more serious, restriction given by our noFDde�nition: using tests in a program prevents it to be noFD. In this sectionwe de�ne a class which is wider than the one of noFD programs and whichcharacterizes a weaker property: the programs in the class can have FDs but,when the query universally terminates, it has at least one successful derivation.We call it the class of successful programs. In order to give a simple de�nitionof such a class of programs, we need to de�ne the property of a set of tests ofconsidering all possible cases in input.First of all we need to identify tests. We do not give a de�nition of what atest is, for us it is just a predicate which can fail. Hence it cannot be noFD. ThenoFD property does not characterize non-failure (it is not a necessary condition),then also its negation, the non-noFD property, does not characterize the failureproperty (it is not su�cient). On the other hand the simplest heuristics foridentifying tests among body atoms is to choose both non-noFD atoms (queries)and atoms which are noFD but their de�nition is not. In the following we assumethat, given a program, we can partition the atoms in the clause bodies into testsand non-tests.De�nition 6 (exhaustive tests). Let P be a well-typed program wrt the direc-tional type T and let p be a predicate de�ned in P by the clauses p(ti) Ti;Bi:,with i 2 [1;m].fT1; : : :;Tmg are exhaustive tests for p wrt input types in T i�for any A, input-correct and simply moded instance of the general atom p(X),there exists i, i 2 [1;m], such that � = mgu(A; p(ti)) and Ti� has at least onesuccessful LD-derivation. 2Example 5. Let us consider the following trivial programp(X, Y, Z) X = Y, r(1, Z).p(a, B, Z) some(B), r(2, Z).p(b, a, Z) r(3, Z).p(b, c, Z) r(4, Z).some(b).some(c).r(X, Y) ...with directional type:T = p(+ : fa; bg;+ : fa; b; cg;� : R);= (+ : Any;+ : Any); some(+ : fa; b; cg);r(+ : f1; 2; 3; 4g;� : R).We identify X = Y and some(B) as tests since they are not noFD (condition 2in De�nition 5 is not satis�ed).fX = Y; some(B); true; trueg are exhaustive tests for p wrt input types in T .In fact input-correct and simply moded instances A of p(X1; X2; X3) are suchthat the �rst term of A is in fa; bg and the second in fa; b; cg.

Let us consider all possible cases.1) A = p(a; a; T ) or A = p(b; b; T ), then the �rst de�nition of p can be chosenand � = mgu(A; p(X;Y; Z)), with � = fX=a; Y=a; T=Zg or � = fX=b; Y=b; T=Zg.In both cases the test (X = Y )� is successful.2) A = p(a; b; T ) or A = p(a; c; T ), then the second de�nition of p can bechosen and � = mgu(A; p(a;B; Z)), with � = fB=b; T=Zg or � = fB=c; T=Zg.In both cases the test some(B)� is successful.3) A = p(b; a; T ), then the third de�nition of p can be chosen and � =mgu(A; p(b; a; Z)), with � = fT=Zg. The test true� is successful.4) A = p(b; c; T ), then the forth de�nition of p can be chosen and � =mgu(A; p(b; c; Z)), with � = fT=Zg. The test true� is successful.Since the condition in De�nition 6 is satis�ed, the tests are exhaustive. 2The previous example shows that we can always introduce a dummy test \true"in a clause in order to complete the set of exhaustive tests associated to apredicate p with types in T . When p is de�ned also by facts, the introduction ofthe dummy test \true" is necessary for satisfying De�nition 6.Since we assume that we can partition the body atoms into tests and non-tests,we can restrict the deductive dependency relation to non-test predicates.De�nition 7 (s-dependency). Let P be a well-typed program and p a predicatede�ned in P by the clauses p(ti) Ti;Bi:, with i 2 [1;m], and Ti tests.p s-depends on q i� q is a predicate symbol in Bi with i 2 [1;m].�P denotes the transitive closure of s-dependency in P .sDep(p) is the set of predicates from which p s-depends also indirectly: sDep(p) =fq j p �P qg. 2Now we can give the main de�nition.De�nition 8 (successful predicate). Let P be a well-typed program wrt thedirectional type T .A predicate p in P is successful wrt the input types in T i�for all the predicates q in sDep(p)[fpg the following two conditions are veri�ed:let q(ti) Ti;Bi:, with i 2 [1;m], be the clauses de�ning q in P ,1. T1; : : :;Tm are exhaustive tests for q wrt input types in T ;2. (noFD conditions) for i 2 [1;m]{ the sequence Bi is simply moded;{ V ar(Out(Bi) \ (V ar(In(q(ti))) [ V ar(Ti)) = ;;{ for all D 2 Bi and for any input-correct and simply moded instance D�of D, there exists a clause in P whose head uni�es with D�. 2The intuitive idea is that if p is a successful predicate, for any input-correct andsimply moded query p(t), there is at least a clause in the de�nition of p which isapplicable, whose tests are successful and which produces a non-�nitely failingderivation (noFD conditions on the atoms in the body which follow the tests).Examples 2, 3 are successful predicates.Note that we require that tests are leftmost in the clause bodies. This is clearly

a restriction, since tests can appear also in other positions. For example letus consider a non-tail recursive de�nition of the maximum element in a list ofintegers. On the other hand this requirement can be dropped and we can give amore general (yet more complex) de�nition and proof.Note also that a noFD predicate which is de�ned for any well-typed input is asuccessful predicate. In fact we can always introduce the dummy test true in allthe clauses, thus having tests which are trivially exhaustive. For this reason alsoreverse and app in Example 1 are successful predicates.For successful predicates we can prove that any noFD query which universallyterminates has at least one successful derivation. We need two simple Lemmata�rst.Lemma 2. Let Q be simply moded and � be a substitution such that V ar(�) \V ar(Q) � (V ar(In(Q)) � V ar(Out(Q))). Then Q� is simply moded.Proof. Immediate from the de�nition of simply moded sequence and the condi-tion on the substitution �. 2Lemma 3. LetQ1 and Q2 be simply moded and such that V ar(Q1)\V ar(Out(Q2))= ;. Then Q1Q2 is simply moded.Proof. Immediate from the de�nition of simply moded sequence. 2Theorem 2. Let Q be a noFD query in P . If Q is universally terminating inP and all the predicates in Q are successful in P wrt the input types, then Qhas at least one successful LD-derivation in P .Proof. Let us assume that Q is universally terminating in P , then it has a �niteLD-tree in P .The proof can be given by induction on the depth n of the LD-tree for a uni-versally terminating, noFD query Q whose predicates are all successful.n = 1. By contradiction let us assume that all the derivations have the formQ j�!P fail. Hence the �rst atom of Q can unify with no clause in P . ButQ is noFD, hence well-typed, and its �rst atom is then input-correct and sim-ply moded. By the second property in De�nition 4, we have a contradiction for� = �.n > 1: Let Q = B1; : : :; Bn. Q is noFD, hence well-typed, and its �rst atom,B1, is then input-correct and simply moded. Since the predicates in Q are suc-cessful there exists a clause ci : p(ti) Ti;Ci: in P , i 2 [1;m], standardizedapart wrt Q, and a substitution � such that: � = mgu(B1; p(ti)) and Ti� has atleast one successful LD-derivation. Then, there exists the derivationQ j ��!P R,where R = (Ti;Ci; B2; : : :; Bn)� and R is not empty. Let � be a computed an-swer substitution for Ti�, we have the LD-derivation:Q j ��!P R j ���!P Q0, with Q0 = (Ci; B2; : : :; Bn)��.Q0 is still universally terminating and its predicates are successful since the pred-icates in Ci are in sDep(p) and p is successful.We prove that Q0 is noFD. Then, by inductive hypothesis applied to Q0, we havethe thesis.

{ Since p is successful and Q a noFD query, Ci and B2; : : :; Bn are simplymoded sequences.We assume standardization apart and � is a c.a.s. for Ti�, then{ V ar(��) \ V ar(B2; : : :; Bm) � V ar(B1).But Q is simply moded, then V ar(Out(B2; : : :; Bm)) \ V ar(B1) = ;, henceV ar(��)\V ar(B2; : : :; Bm) � (V ar(In(B2; : : :; Bm))�V ar(Out(B2; : : :; Bm))) and, by Lemma 2,(i) (B2; : : :; Bn)�� is simply moded and(ii) Out(B2; : : :; Bm)�� = Out(B2; : : :; Bm).{ V ar(��) \ V ar(Ci) � V ar(p(ti);Ti).Moreover V ar(ci) \ V ar(Q) = ; and � = �jci � �jQ.Since � = mgu(B1; p(ti)) and B1 is in the query and it is simply moded, wehave that V ar(�jci ) \ (V ar(Out(p(ti)))� V ar(In(p(ti)))) = ;.Then V ar(�jci) \ V ar(Ci) � V ar(In(p(ti))) and V ar(�jci�) \ V ar(Ci) �V ar(In(p(ti));Ti).Hence, since p is successful, V ar(�jci�)\V ar(Ci) � (V ar(In(Ci))�V ar(Out(Ci))) and, by Lemma 2,(iii) Ci�jci� = Ci�� is simply moded.{ V ar(Ci��) \ V ar(Q��)) � V ar(B1��).Because of (ii) we have also that V ar(B1��)\V ar(Out((B2; : : :; Bm)��)) =;. Then,(iv) V ar(Ci��) \ V ar(Out((B2; : : :; Bm)��)) = ;.Then, by (i), (iii), (iv) and Lemma 3, Q0 is simply moded.Let us now prove that Q0 satis�es also the second condition for noFD queries.(Ci; B2; : : :; Bm)�� is simply moded, then for any atom D in (Ci; B2; : : :; Bm)��and for any input-correct and simply moded instance D� there exist D0 inCi; B2; : : :; Bm and a substitution �0 such that D� = D0�0, and hence D0�0is a input-correct and simply moded instance of D0. Hence the second conditionfor noFD queries immediately follows from the fact that p is successful and Q isnoFD. 24 How to Verify that a Program is SuccessfulThe conditions in De�nition 8 are not so easy to verify. Problems are in condition1, namely how to single out tests and to prove that they are exhaustive. In thissection we propose some techniques for simplifying such task and a strategy forthe failure/success analysis.4.1 Accepted input typesIn De�nitions 6, 8 we state that a noFD predicate is successful only if it is de�nedfor any correct input wrt to its directional type. A simple example will show thepoint.

Example 6. Let us consider the following simple programlast([X],X).last([X, Y| Xs], E) last([Y| Xs], E).with directional type last(+ : List;� : Any).last is noFD but not successful. In fact by introducing the dummy test true weget the programlast([X],X) true.last([X, Y| Xs], E) true, last([Y| Xs], E).where ftrue; trueg are not exhaustive tests for last wrt the input types since lastis not de�ned for empty lists. But we can restrict the directional type associatedto last to last(+ : List+;� : Any), where List+ = List�f[]g. Now the programis both noFD and successful. 2Often the directional type associated to a predicate is actually larger than thetypes for which the predicate is de�ned. We can weaken the requirements inDe�nition 6 by introducing the notion of input types accepted by a predicate.De�nition 9 (accepted input types). Let P be a well-typed program andp a predicate de�ned in P by the clauses p(ti1; : : :; tin; si1; : : :; sir) Bi:, withi 2 [1;m], where tik, k 2 [1; n], are input terms and sih, h 2 [1; r], outputterms. Let Tk, for k 2 [1; n], be the types associated to the input positions in thedirectional type of p.The input types accepted by p, ATk, for k 2 [1; n], shortly accepted input types,are given by the sets of all the instances of terms in the k-th input positions ofthe heads of the de�nitions of p which belongs to Tk:ATk = ([�ft1k�; : : :; tmk�g) \ Tk. 2In a well-typed program the accepted input types can be subsets of the inputtypes declared in the directional type. They are the sets of terms which can bee�ectively used as inputs when querying the predicate.Abstract Interpretation techniques can be used for inferring type information fora program [15, 19, 17], with these techniques accepted input types are inferred.In order to automatize the veri�cation of the successful property, we could thenexploit tools for Abstract Interpretation.The de�nitions of exhaustive tests and successful predicate can be restricted toaccepted input types. In this case the condition on exhaustive tests in De�nition6 is simpli�ed since there always exists a clause i 2 [1;m] and an mgu � for anyinput-correct and simply moded instance of the predicate.Note that the property of being well-typed wrt a directional type is not preservedin general when we restrict the input types to the accepted ones.Example 7. Let us consider the following programlast([X], X).last([X| Xs], E) last(Xs, E).

this predicate is well-typed wrt the directional type last(+ : List;� : Any) butit is not well-typed wrt last(+ : List+;� : Any) which is the directional typewe obtain when we restrict it to accepted input types. 2Note that the mismatch between the declared directional type and the acceptedinput types always causes problems wrt failure/success analysis: wrt the �rstdirectional type last is not noFD, in fact the second condition in De�nition 4 isnot satis�ed since Xs in the body can be an empty list.In the following we assume that the directional type associated to a predicateare already restricted wrt accepted input types.4.2 Input-normalizationA major di�culty in using De�nition 8 is the identi�cation of exhaustive tests.We need to be able to single out some body atoms in a predicate de�nition andto prove that they are a set of exhaustive tests for that predicate. Atoms whichare eligible as tests are the ones which do not satisfy noFD conditions (condition2 in De�nition 8). Proving that they are exhaustive is not trivial. It is a semanticcondition and not decidable in general, as shown in [18], but in most practicalcases the conditions in De�nition 8 can be veri�ed.Let us consider Example 3. odd and even are non-noFD predicates, hence alsooddLength and evenLength which depend on them are non-noFD. In the de�ni-tion of posP ivot we choose them as tests. We should prove that foddLength(L;Length); evenLength(L;Length)g are exhaustive for posP ivot wrt input types.This means to prove that 8L 2 List; j L j= n 2 Nat and then 8n 2 Nat; even(n)_odd(n). Speci�cations could give us the knowledge we need for our proofs.We could study a priori a set of predicates and prove that for any input valueat least one of them is successful. This would give us \a tool" for verifying thecondition in De�nition 6.Among the most common sets of tests are arithmetic tests.Example 8. Let us consider the set fx < y; x � yg. We can verify once for allthat for any pair x; y 2 S, where S is any subset of Int, at least one inequalityis true and successful with a Prolog interpreter.This can be used for example in the following program.gcd(X, 0, X).gcd(X, Y, Gcd) mod(X, Y, Z), gcd(Y, Z, Gcd).mod(X, Y, X) X<Y.mod(X, Y, Z) X>=Y, X1 is X-Y, mod(X1, Y, Z).with directional type gcd(+ : Int+;+ : Int+;� : Int+) and mod(+ : Int+;+ :Int+;� : Int+), where Int+ is the set of non-negative integers.mod contains X < Y and X >= Y . Any correct application of the clausesde�ning mod will instantiate both X and Y to terms in Int+. We can then useour previous result and easily prove that such tests are exhaustive on the inputtypes and then both gcd and mod are successful predicates. 2

Another common set of tests which we can easily study a priori is given by uni-�cation tests, namely fx = y; x 6= yg, with x; y 2 T and T any type. Uni�cationis decidable, then at least one of the two is true and successful.If we allow negation in tests, we could consider also user-de�ned ground tests suchas for all predicate symbol p fp(x); not p(x)g, with x 2 T and T ground types.Since negation-as-failure for ground atoms corresponds to classical logic, we knowthat at least one of the two is true and successful with a Prolog interpreter.Example 9. Let us considersplit([], Set2, [], []).split(Set1, [], Set1, []).split([X jXs], Set2, [X jComplement], Intersection) not member(X, Set2), split(Xs, Set2, Complement, Intersection).split([X jXs], Set2, Complement, [X jIntersection]) member(X, Set2), split(Xs, Set2, Complement, Intersection).member(X, [X jXs]).member(X, [Y jYs]) member(X, Ys).with directional type split(+ : GroundList;+ : GroundList;� : GroundList;� :GroundList) and member(+ : Ground;+ : GroundList).This program contains tests predicates, namelymember(X;Set2) and not member(X;Set2),which for any correct use of split will become ground. By our previous observa-tion we can easily prove that such tests are exhaustive on the input types. Thenwe can prove that split is successful. 2By knowing more on the interpreter we could enlarge our set of \tools".Example 10. Let us consider fodd(x); even(x)g, with x 2 Nat. Suppose we knowthat for each choice of x for the Prolog interpreter at least one of the two issuccessful. Then when considering the programdoubleEven([], []).doubleEven([X jXs], [X jYs]) odd(X), doubleEven(Xs, Ys).doubleEven([X jXs], [Y jYs]) even(X), Y is X*2,doubleEven(Xs, Ys).with directional type doubleEven(+ : NatList;� : NatList) and even(+ : Nat),odd(+ : Nat);we could easily verify that ftrue; odd(X); even(X)g are exhaustive for doubleEven,with X 2 Nat. 2Note that in order to use this prede�ned knowledge we have to instantiate ourset of tests with input types. But instantiation is often not enough in orderto recognize a well-known case. Let us consider Example 2. There is only oneexplicit test, X 6= Z. Nevertheless we should recognize that delete is usinguni�cation tests, where the complementary test X = Z is implicit in the headof the second clause. To make it easier (and more automatizable) we introducea transformation for normalizing input arguments in a program.

De�nition 10 (input-normalized de�nition). Let P be a well-typed programand p(i1; : : :; in; o1; : : :; or) a predicate de�ned in P , where ik, with k 2 [1; n],are the input positions and oh, with h 2 [1; r] the output positions in p. LetV = fX1; : : :; Xng be a set of new variables wrt p, namely variables which donot appear in the de�nition of p.The input-normalized de�nition of p, pN , is the program obtained by substitutingeach clause in the de�nition of p: p(t1; : : :; tn; s1; : : :; sr) D:with the corresponding input-normalized clause: p(X1; : : :; Xn; s1; : : :; sr) X1 =t1; : : :; Xn = tn;D:The program thus obtained is input-normalized wrt p. V is the set of normalizedinput variables for pN .Xk = tk, for k 2 [1; n], are the input equalities in each clause in the de�nitionof pN , with directional type = (+ : Tk;� : Tk), where Tk is the type associatedto the k-th input position. 2Lemma 4. Let P be a well-typed program and p a predicate de�ned in P . Letus associate in pN , to each input equality Xk = tk, the directional type = (+ :Tk;� : Tk), where Tk is the type associated to the k-th input position in thedirectional type of p. Then pN is well-typed.Proof. Trivial, by De�nition of well-typed clause. 2Lemma 5. Let P be a well-typed program and p a predicate de�ned in P . pN isclause-wise equivalent to p.Proof. By unfolding the input equalities in each clause in pN , we obtain theclauses of p again. On the other hand we already proved [9] that unfoldingpreserves both c.a.s. and universal termination. 2Note that the property of being noFD is not preserved through input-normalization.In fact even if the original predicate p is noFD, pN can be non-noFD since in gen-eral input equalities do not satisfy the simply modedness condition in De�nition4.Example 11. Let us de�ne appN wrt the directional type app(+ : List;+ :List;� : List).app(X1, X2, Ys) X1 = [ ], X2 = Ys.app(X1, X2, [X jZs]) X1 = [X jXs], X2 = Ys, app(Xs, Ys, Zs).appN is not noFD. It does not satisfy the �rst syntactic condition in De�nition4 since compound terms are in output in the input equalities in the bodies. 2We assume that input-normalized programs always refer to the accepted inputtypes of the original program. Let us consider again Example 2.Example 12. After input-normalization we obtain:delete(X1; X2, [ ]) X1 = [ ], X2 = X.delete(X1; X2, Ys) X1 = [X jXs], X2 = Z, X = Z,delete(Xs, X, Ys).delete(X1; X2,[X jYs]) X1 = [X jXs], X2 = Z, X 6= Z,delete(Xs, Z, Ys).

The built-in predicates have a directional type which is induced by the well-typing condition, namely equality and inequality have directional type (+ :Any;+ : Any).We can determine tests predicates by composing the input equalities introducedby input-normalization with atoms in the clause bodies for which noFD condi-tions are not satis�ed. Namely we consider the tests:T1 = (X1 = [ ]; X2 = X),T2 = (X1 = [X j Xs]; X2 = Z;X = Z),T3 = (X1 = [X j Xs]; X2 = Z;X 6= Z).Let us consider an input-correct and simply moded instance of delete. Either X1is an empty list and the �rst test T1 is successful, or X1 is a non-empty list.In this second case X;Z 2 Any and, by what we know regarding uni�cationtests, one of the two atoms (X = Z); (X 6= Z) is successful. Hence the tests areexhaustive for deleteN .The other two (noFD) conditions are easy to verify on the recursive atoms. 24.3 Input-subsumptionIn order to make easier to prove the property of being exhaustive tests for apredicate, it is often useful to \simplify" the set of clauses we consider. To thispurpose we introduce the following de�nition.De�nition 11 (Clause input-subsumed by a fact or a clause). Let P bea well-typed program. Let c1 : A: be a fact, c2 : H B: and c3 : K A: beclauses in P which de�ne the same predicate, namely A = p(t1), H = p(t2) andK = p(t3).Clause c2 is input-subsumed by the fact c1 i� there exists an input substitution� such that A� = H.Clause c3 is input-subsumed by clause c2 i� there exists an input substitution �such that H� = K. 2Example 13. Let us consider the trivial program1: p(X, Y).2: p(a, Y) r(a), s(Y).3: p(X, b) r(X).4: p(a, b) r(a), p(a, Y).5: r(b).6: s(b).well-typed wrt the directional type p(+ : Const;� : Const); r(+ : Const); s(� :Const).Clause 2 is input-subsumed by fact 1; clause 4 by clause 3. 2We have extended the usual concept of subsumption to �t the veri�cation ofthe successful property. We are not interested in c.a.s. but in characterizing thepresence of at least one successful derivation for each well-typed input substitu-tion. A fact always produces a successful derivation, then it can input-subsume

a clause independently from its body. Similarly for two clauses, if the one ac-cepting a more general input produces a successful derivation, then the otherone becomes irrelevant. Input-subsumption can be used to prune the program.If we can prove that a pruned de�nition of a predicate is successful, then alsothe original de�nition is successful. This means that we may simplify the ver-i�cation of De�nition 8 by �rst pruning the program of some input-subsumedclauses. The simpli�cation phase must be applied before input-normalization;after input-normalization input-subsumption becomes trivial and useless.Example 14. let us consider:choose(Low, High, Low).choose(Low, High, X) Low < High, L is Low +1,choose(L, High, Low).with directional type choose(+ : Int;+ : Int;� : Int).This program is non-deterministic and the second clause is input-subsumed bythe �rst one which is a fact and then noFD. Hence we can conclude that alsochoose is successful. 2By pruning input-subsumed clauses we often succeed in reducing the non-trivialproblem of verifying that a predicate is successful, to the much simpler problemof verifying that the pruned predicate is noFD.4.4 Analysis strategyWe now propose a strategy for the failure/success analysis which allows us toexploit the simpli�cations already presented.Given a predicate p in P the analysis could proceed as follows:1. check that we are referring to accepted input types for p (with AbstractInterpretation);2. check if the predicate p is noFD;3. otherwise prune p by eliminating some input-subsumed clauses and check ifit is now noFD; in this case we can state that the predicate is successful;4. if not, for all predicates q in sDep(p) [ fpg:{ input-normalize;{ single out the tests in the bodies of the de�nition clauses (the input equal-ities plus the body atoms which do not satisfy the noFD conditions);{ prove that they are exhaustive (with some prede�ned knowledge);{ prove that the noFD conditions in De�nition 8 are veri�ed;in this case we can state that the predicate is successful.With this strategy the veri�cation of the successful condition is done only whenthe noFD property is not su�cient.Step (1) is optional, but it can help to verify the next conditions.The pruning step (3) can be performed in many ways in general. We shouldexplore this nondeterminism in order to �nd a solution. The simplest solution iswhen we succeed in reducing our initial problem of verifying that a predicate issuccessful to the much simpler one of verifying that it is noFD.

4.5 ApplicationsThe property of beeing successful can be useful in the �eld of program veri�ca-tion. Let us assume to have a program which is partially correct wrt a speci�ca-tion and a query which is both universally terminating and partially correct wrtthe speci�cation. Then, if we prove that the query is noFD and the predicatesin the query are successful, Theorem 2 guarantees the existence of at least onecorrect c.a.s. This corresponds to give a proof of completeness with respect toboth the Herbrand semantics and the S-semantics (the c.a.s. semantics). In factfor a ground query we are exactly proving completeness, and in general we areproving that the model of the program is not empty wrt the query.Also in the �eld of program transformations being successful can be useful inparticular for switching atoms in the clause bodies. In [11] we consider left-terminating programs [6] and we de�ne a su�cient condition for switching atomswhile preserving left-termination. This condition for switching the atom A withB in a clause c : H J; A;B;K: depends on the property of A of being\non-failing", namely for each grounding substitution �, such that Dom(�) =V ar(In(H);J; In(A)) and J� 2 MP , there exists such that A� 2 MP . Thisintuitively means that if A is the selected atom in an LD-derivation, becausec was used as input clause in a previous derivation step, then the computationof A will eventually succeed. This is a \semantic" condition which is not easyto verify in general. But if we prove that the query A is universally terminatingand noFD and the predicate in A is successful, then the non-failing condition isguaranteed.Example 15. Let us consider an example of transformation given in [11]. Thefollowing program de�nes the predicate goodpath(X;Xs) which relates a nodeX with a list Xs of \good" nodes which are connected to X .1: path(X, [X]).2: path(X, [X jXs]) arc(X, Y), path(Y, Xs).3: goodlist([]).4: goodlist([X jXs]) good(X), goodlist(Xs).d: goodpath(X, Xs) path(X, Xs), goodlist(Xs).The directional type is path(+ : Const;� : List); goodlist(+ : List); goodpath(+ :Const;� : List), arc(+ : Const;� : Const), good(+ : Const).The predicates good and arc are test predicates de�ned in the program.In [11] we consider a transformation which repeatedly unfold the body atoms ind until we get to:d1:goodpath(X, [X]) good(X).d2:goodpath(X, [X jXs]) arc(X, Y),path(Y, Xs), good(X),goodlist(Xs).In order to optimize the program by folding with d, we need to switch path(Y;Xs)and good(X) in d2.

Hence we need to prove that path(Y;Xs) is non-failing in d2, namely thata) for each grounding substitution �, such that Dom(�) = fX;Y g andY � 2 Const, path(Y;Xs)� is a noFD query andb) path is a successful predicate.(a) is trivial. For (b) let us consider the de�nition of path given by clauses 1 and2. We can prune 2, since it is input-subsumed by the fact 1. Hence we obtain anoFD program given by a single fact, which implies that path is successful. 25 ConclusionIn program veri�cation and transformation it is important to identify both thequeries which have successful LD-derivations and those which have also �nitelyfailing LD-derivations.In a previous work we have de�ned the class of noFD programs and queries [10]which have the property of not having �nitely failing derivations. In this paperwe extend our previous work by de�ning the wider class of successful predicateswhich includes also programs using tests. We prove that noFD queries for suc-cessful predicates have the property of having at least one successful derivation,if they are universally terminating. This property is more complex to verify thanthe noFD one, hence we suggest some techniques, based on program transfor-mations, for simplifying the failure/success analysis.Our work is clearly related to those on cardinality analysis, for example in [20,17]. In these works an approximation of the number of c.a.s. for a query is esti-mated by means of Abstract Interpretation.Success analysis is interesting also for parallel execution optimization. In [18]a technique is proposed for detecting programs and queries which produce atleast one solution or do not terminate. The technique deals with programs con-taining tests and it is based on a di�erent notion of mode and type informationfrom ours. An algorithm is given for uni�cation and arithmetic tests. The algo-rithm can decide if they \cover" a type by using Abstract Interpretation. Thetechnique is implemented and a report on its implementation is also given. Thetechnique proposed in [18] is applicable to some of our examples: 8 and, afterinput-normalization, 2. Since they do not consider the simple case when thereare noFD, their rather sophisticated algorithm is applied also to noFD programssuch as 1.In the Mercury language [22] a nondeterminism analysis is implemented whichis related with our work. Given a predicate p with mode m, there are six deter-minism categories for describing the result of any query for p and m. The sixcategories are: det (exactly one success), multi (at least one success), semidet(fail or exactly one success), nondet (fail or at least one success), failure (fail)and erroneous (run-time error). Mercury can infer a category for p and m whichis an approximation of the real one and can use such information for optimizingprograms. The category multi corresponds to our successful class, while there isno Mercury category corresponding to our noFD class. It is not so easy to give acomparizon with Mercury since no formal semantics is given, but we can make

a few observations. The determinism analysis in Mercury is richer than our fail-ure/success analysis, but it gives no information on the presence/absence of FDs.It infers an approximation of the real determinism category and it could thenbe not precise. The inference of multi cannot be simpli�ed by �rst pruning theprogram and then verifying the noFD property as we propose, nevertheless alsoin Mercury there are explicit ways to eliminate nondeterminism and to prune aprogram. In Mercury well-moding, and then well-typing, are not wrt a leftmostselection rule (Prolog rule). For Mercury it is su�cient that there exists an orderof body atoms for which clauses are well-typed.Anyway the major di�erence between our work and related ones, is in purpose.The techniques based on Abstract Interpretation are generally meant for opti-mization in compilers, hence the emphasis is on automatizability and aproxima-tion. We are more interested in program veri�cation and transformation, hencegenerality and precision is our concern.AcknowledgementsThis work was supported partly by Italian MURST with the National ResearchProject 9701248444-004 on \Tecniche formali per la speci�ca, l'analisi, la veri�ca,la sintesi e la trasformazione di sistemi software" and partly by Italian C.N.R.with the \Progetto Coordinato - Programmazione Logica: Strumenti per Analisie Trasformazione di Programmi; Tecniche di Ingegneria del Software; Estensionicon Vincoli, Concorrenza, Oggetti".References1. K. R. Apt. Introduction to Logic Programming. In J. van Leeuwen, editor, Hand-book of Theoretical Computer Science, volume B: Formal Models and Semantics.Elsevier, Amsterdam and The MIT Press, Cambridge, 1990.2. K. R. Apt. Declarative programming in Prolog. In D. Miller, editor, Proceedings ofthe 1993 International Symposium on Logic Programming, pages 12{35. The MITPress, 1993.3. K. R. Apt. From Logic Programming to Prolog. Prentice Hall International Seriesin Computer Science, 1997.4. K. R. Apt and S. Etalle. On the uni�cation free Prolog programs. InA. Borzyszkowski and S. Sokolowski, editors, Proceedings of the Conference onMathematical Foundations of Computer Science (MFCS 93), Lecture Notes inComputer Science, pages 1{19, Berlin, 1993. Springer-Verlag.5. K. R. Apt and E. Marchiori. Reasoning about Prolog programs: from modesthrough types to assertions. Formal Aspects of Computing, 6(6A):743{765, 1994.6. K. R. Apt and D. Pedreschi. Studies in Pure Prolog: termination. In J.W. Lloyd, ed-itor, Proceedings of the Simposium in Computational Logic, pages 150{176, Berlin,1990. Springer-Verlag.7. K. R. Apt and D. Pedreschi. Reasoning about termination of pure Prolog programs.Information and Computation, 106(1):109{157, 1993.8. A. Bossi and N. Cocco. Verifying correctness of logic programs. In J. Diaz andF. Orejas, editors, TAPSOFT '89, Barcelona, Spain, March 1989, (Lecture Notesin Computer Science, vol. 352), pages 96{110. Springer-Verlag, 1989.

9. A. Bossi and N. Cocco. Preserving Universal Termination through Unfold/Fold.In G. Levi and M.Rodriguez-Artalejo, editors, Algebraic and Logic Programming- Proceedings ALP'94, volume 850 of Lecture Notes in Computer Science, pages269{286. Springer-Verlag, Berlin, 1994.10. A. Bossi and N. Cocco. Programs without Failures. In N. Fuchs, editor, ProceedingsLOPSTR'97, Lecture Notes in Computer Science. Springer-Verlag, Berlin, 1997.11. A. Bossi, N. Cocco, and S. Etalle. Transformation of Left Terminating Programs:The Reordering Problem. In M. Proietti, editor, Proceedings LOPSTR'95, volume1048 of Lecture Notes in Computer Science, pages 33{45. Springer-Verlag, Berlin,1996.12. A. Bossi, N. Cocco, and M. Fabris. Norms on terms and their use in provinguniversal termination of a logic program. Theoretical Computer Science, 124:297{328, 1994.13. J. Boye and J. Maluszynski. Two Aspects of Directional Types. In Sterling, editor,Proc. Int'l Conf. on Logic Programming, pages 747{761. MIT Press, 1995.14. F. Bronsard, T. K. Lakshman, and U. S. Reddy. A framework of directionalitiesfor proving termination of logic programs. In K. R. Apt, editor, Proceedings ofthe Joint International Conference and Symposium on Logic Programming, pages321{335. The MIT Press, 1992.15. M. Bruynooghe and G. Janssens. An Instance of Abstract Interpretation: Inte-grating Type and Mode Inferencing. In Proc. Int'l Conf. on Logic Programming,pages 669{683. MIT Press, 1988.16. R. Chadha and D. A. Plaisted. Correctness of uni�cation without occur check inProlog. Journal of Logic Programming, 18(2):99{122, 1994.17. B. Le Charlier, C. Leclere, S. Rossi, and A. Cortesi. Automated Veri�cation ofBehavioural Properties of Prolog Programs. In Advances in Computing Science -ASIAN'97, Katmandu, Nepal, Lecture Notes in Computer Science, pages 225{237,1997.18. S. Debray, P. Lopez-Garcia, and M.Hermenegildo. Non-Failure Analysis for LogicPrograms. In Proceedings of the International Symposium on Logic Programming,pages 48{62, 1997.19. S.K. Debray. Static inference of modes and data dependencies in logic programs.ACM Transactions on Programming Languages and Systems, 11(3):419{450, 1989.20. S.K. Debray and N. Lin. Cost analysis of logic programs. ACM Transactions onProgramming Languages and Systems, 15(5):826{875, 1993.21. W. Drabent and J. Maluszynski. Inductive assertion method for logic programs.Theoretical Computer Science, 59:133{155, 1988.22. F. Henderson, T. Conway, Z.Somogyi, and D. Je�ery. The Mercury language ref-erence manual. Technical Report TR 96/10, Dep. of Computer Science, Universityof Melbourne, 1996.23. J. W. Lloyd. Foundations of Logic Programming. Springer-Verlag, Berlin, 1987.Second edition.24. D. De Schreye and S. Decorte. Termination of Logic Programs: the never-endingstory. Journal of Logic Programming, 19-20:199{260, 1994.