scieee AI-readable full text Open interactive document viewer

Closed Types for Logic Programming

João Luís Alves Barbosa

Full text

Closed Types for Logic Programming João Luís Alves Barbosa Master’s degree in Computer Science Computer Science Department 2016 Supervisor Mário Florido, Associate Professor, Faculty of Science, University of Porto Co-Supervisor Vítor Santos Costa, Associate Professor, Faculty of Science, University of Porto All corrections determined by the jury, and only those, were incorporated. The President of the Jury, Porto, ______/______/_________ Acknowledgments I want to thank both my supervisors for the help they provided in the making of this work as well as insisting on me not to stop working and always being available to help solving all the problems that appeared. I also want to thank my parents for supporting me in my academic choices and providing everything I needed and wanted to finish this course. Without them it would not be possible. To all my friends a huge thank you for being there for me and encouraging me to work and study as well as providing a lot of fun time that gave me strength and distracted me when I needed to. Abstract In this work, we present a new type system for logic programming and a type inference algorithm that we prove to be sound with respect to the type system. The types inferred by our algorithm are closed, meaning that some programs will not be accepted because they will be too general. The programs that are not accepted by our type system include those where there is a single occurrence of a free variable in the head of a clause defining a predicate and programs that implicitly define open data types. When a program is accepted by the algorithm and we infer types for the predicates in the program, then those types will be closed and, as such, a closure step is needed to ensure that. The closure step is the final step of our algorithm and we believe it is not too restrictive nor too broad so that the final types are closer to the intended types of the programmer than they were before this step. The semantics we present for types is quite different from the traditional semantics for types in logic programs, as types do not represent sets of terms, but sets of predicates. This relates to the functional programming view of types and it has an important role in our work, since parametric polymorphism comes naturally from this interpretation. Resumo Neste trabalho, apresentamos um novo sistema de tipos para program¸c˜ao l´ogica e um algoritmo de inferˆencia de tipos que provamos ser correto em rela¸c˜ao ao sistema de tipos. Os tipos inferidos pelo algoritmo s˜ao fechados, o que significa que alguns programas n˜ao s˜ao aceites por serem demasiado gerais. Os programas que n˜ao s˜ao aceites incluem os em que existe uma ´unica ocorrˆencia de uma vari´avel livre na cabe¸ca de uma cl´ausula que define um predicado e os que explicitamente definem tipos de dados abertos. Quando um programa ´e aceite pelo algoritmo e tipos s˜ao inferidos para os predicados do programa, ent˜ao esses tipos s˜ao fechados e, como tal, um passo de fecho ´e necess´ario para assegurar isso. O passo de fecho ´e o ´ultimo passo do nosso algoritmo e n´os acreditamos que n˜ao ´e demasiado restritivo nem demasiado abrangente, para que os tipos finais estejam mais pr´oximos dos tipos pretendidos pelo programador. A semˆantica que apresentamos para tipos de predicados ´e bastante diferente da semˆantica tradicional para tipos em programa¸c˜ao l´ogica, uma vez que os tipos n˜ao representam conjuntos de termos, mas conjuntos de predicados. Esta vis˜ao est´a relacionada com o ponto de vista da programa¸c˜ao funcional e ´e uma interpreta¸c˜ao importante no nosso trabalho, j´a que o polimorfismo param´etrico surge naturalmente dessa interpreta¸c˜ao. In more detail, the argument is that logic programs are very expressive, and in general the use of the logic variables may cause the acceptance of more terms than intended in a successful computation. We argue that such programs are overly generous and that in a fully typed Prolog we should have type constraints over all variables. Thus it is proposed that all uses of the logic variables in a program should be type constrained, where by constraints it is meant that either the type of the variable is strictly smaller than the set of all possible terms, or that there is an equality constraint between different types. The types in which all variables are constrained are named closed types. Consider the following example: Example 1. Let τi append denote the type of the i-th argument of the Prolog append predicate and + denote a disjunction of types in a type definition. append([ ],X,X). append([X|L1],L2,[X|L3]) : −append(L1,L2,L3). Then: τ1 append = [ ] + [α|τ1 append] τ2 append =β τ3 append =β+ [α|τ3 append] is a (semantically valid) open type for append and: τ1 append = [ ] + [α|τ1 append] τ2 append = [ ] + [α|τ2 append] τ3 append = [ ] + [α|τ3 append] is a closed type for append. The predicate in the example above is also typed in the traditional way, requiring the first argument to be a list, but the second argument is not typed constrained, whereas closed types, having a more restrict type discipline, require the second and third argument to be type constrained and as such to be a list as well. The second point is based on the principle of self-contained definitions: given that we have a set of constants Cand function symbols Foccurring in a predicate p, a type τmust either have a principal functor in F, a constant type generalizing C, 2 or be a sum type, which is a disjunction of the previous types, that is, it should be context-independent. In what follows, a polymorphic type discipline for logic programming is developed based on these two principles. The goal is to achieve some important features of previous work on types for logic programming (and programming in general): •Type checking at compile time. This work defines a type inference algorithm that can also be used to type check declarations explicitly given by the programmer. The types defined are closed types, which, like regular types can be described by tree automata [CDG+07]. Type checking can be done dynamically (at run-time) using a well-known relation between regular types, which are types that can be described by a regular term grammar, and a class of monadic logic programs [YFS92, FSVY91, FD92]. •The programmer may not declare types at all, because the type inference algorithm will automatically infer a type for a given untyped program. •Polymorphism. For now, we deal with parametric polymorphism [PR89, Zob87]. The main advantage of using closed types instead of regular types is that closed types can describe polymorphic types that are connected between them, for instance, the type list(α)×list(α) will be the type for a predicate with two lists as arguments, such that the lists contain terms of the same type on both predicate arguments. This differs from monomorphic regular types because it is not possible to define a monomorphic type that acts the same way, since α, in the example, is describing any term and as such one of the lists could be a list of integers and the other a list of strings. In the future work section, there is a discussion about overloading and coercion. The major novel contributions of the type system include: •Closed types: as discussed above, closed types mean that one has a bound on all objects valid in a typed program. The motivation stems from experience in both functional and logic programming languages. First, functional languages have a similar challenge in union types, and require a similar restriction on union types to enable type inference. A second motivation stems from Datalog [UZ90]. Consider the following program: i(X,Y) :- e(X). 3 This program is not allowed because Ymatches any object in the database. Datalog implementations address this problem by explicitly disallowing unconstrained head free variables as they match the full Herbrand base. We argue that such a program should not be considered well typed. •Type information. The motivation is to get closer to the programmer’s ‘intended’ definitions [Nai92]. Zobel said about previous type inference algorithms “inferred types may have no relation to a predicate’s ‘intended’ types, and are simply cartesian products, of sets of ground terms, that contain all tuples of ground terms that can occur in the predicate’s success set” [DZ92]. Using the assumptions about what is not a too-generous program, we develop an approximation to the programmer’s ‘intended’ types for a predicate. •A new type system. The type system is the link between inference and semantics as we will show and it assumes an attribution of types to variables and a set of type rules in Zobel style [Zob87]. It is a different type system from others developed by other authors. •Semantics. Previously, types in logic programming have been described as an approximation to the success set of a program. This work takes a different approach on types, where their interpretation is that they correspond to all the predicates that can have such type, in a more functional programming way of thinking. We would like to see this proposal as following in the line of Lee Naish’s “Specification = Program +Types” [Nai92]. In this case, our type system can be seen as a declarative way to complement control, by restricting programs in order to facilitate the development of large applications, while preserving the flavor of logic programming. In Chapter 2, we will discuss some work from other authors, related to types in logic programming, showing different approaches to the subject and presenting the main definitions that are important and influential in the type system and type inference algorithm we defined. In Chapter 3, we will present the type system and discuss some of the reasons behind the definitions, as well as define all the necessary properties we want in types defined by the type system. In Chapter 4, we will present the type inference algorithm as well as a proof of its soundness regarding the type system. 4 In Chapter 5, we will show the core of the implementation of the type inference algorithm. In Chapter 6, conclusions will be presented and some future work topics will be discussed. 5 Chapter 2 Type Systems for Declarative Languages Type systems have been used as a paradigmatic method to ensure program correctness. One of the most obvious benefit of using type checking is error detection. When a language is richly typed, the type checker often captures bugs that would be very hard to detect later. The effectiveness of the type checker depends as much on the expressiveness of the type system as on the use the programmer gives it. For instance, if a programmer encodes all his data structures as ListOfPaths, then he will not benefit as much from the type checker as if he had used different data types for each structure. There are many other reasons to use type systems as a tool for a programming language such as abstraction of a program by modules in a safer way or as a helpful way to understand a program, by reading the types, as well as the safety that type systems provide. There have been two major ways of introducing types in logic programming. One is by approximation to the success set of the program. The other is to follow functional languages and more often a Hindley-Milner like type system, where the interpretation of types is not a superset of the program success set, but filters it by defining a set of well-typed programs. In this work, we are going to talk about both of them a little in this section. Since the early works on the area [YFS92, FSVY91, BJ88, DZ92, Mis84], type systems for logic programming describe types as recursive sets of ground terms. Often, these approaches are based on the notion of regular types1. For this type the intersection of 1The meaning of regular types is different across literature. In this work, we assume that regular 6 two types and type comparison are decidable [Zob87]. Regular types can be written as logic programs, namely monadic logic programs themselves as types for logic programs [FSVY91], using unary-predicate programs to describe types in a natural way. Both type verification and type inference algorithms have been proposed [Zob87, YFS92, BJ88, HJ92, SBG08, GdW94]. Approaches differ on whether types are considered approximations of the success set of a logic program, or whether one wants to ensure that a type signature will be respected. 2.1 Hindley-Milner-Damas Type System The Hindley-Milner-Damas type system [Mil78, DM82] is a type system for functional languages that treats types as sets of functions from input to output. In this type system, we also have type variables, representing any type, and basic types such as Bool,Int,Char, etc. Types are built from type operators such as →to form types for functions and a definition of type scheme, which is a type quantified for every variable appearing in it. Example 2. Let id be the identity function defines as follows: id x =x The type for this function is ∀α.α →α. This type system is the basis for many other type systems for either functional programming or logic programming. It is the foundation for a lot of different variations of what is actually implemented on languages such as Haskell, ML, Curry and Mercury [AH16], etc. Another definition from Damas and Milner in [DM82] is the type assignment algorithm W, that receives as input a set Aof assumptions of the form x:σand an expression eand either fails or returns a substitution Sand a type τ. They proved that the substitution Sand the type τreturned by the algorithm are the most general. Type inference relies on the unification algorithm that given two types, either fails or returns a substitution Vthat is the most general unifier. types are types that can be described by regular trees 7 Let A(τ) be the type closure, i.e. A(τ) = ∀α1. . . αnτ, where α1. . . αnare occurring free in τbut not in A. The algorithm itself is defined as follows: W(A, e) = (S, τ),where 1. If eis xand there is an assumption x:∀α1. . . αnτ0in Athen S=Id and τ= [βi /αi]τ0, where βis are new variables. 2. If eis e1e2then let W(A, e1)=(S1, τ1) and W(S1A, e2) = (S2, τ2) and U(S2τ1, τ2→ β) = Vwhere βis new; then S=V S2S1and τ=V β. 3. If eis λx.e1then let βbe a new type variable and W(Ax∪{x:β}, e1) = (S1, τ1); then S=S1and τ=S1β→τ1. 4. If eis let x =e1in e2then let W(A, e1)=(S1, τ1) and W(S1Ax∪ {x: S1A(τ1)}, e2)=(S2, τ2); then S=S2S1and τ=τ2. Damas and Milner also proved that Wis sound and complete with respect to the Hindley-Milner type system. 2.2 Regular Types Zobel’s work is one of the first examples of type inference based on the success set of a logic program [Zob87]. Zobel used regular types, which are types that can be described with a regular term grammar, as types for logic programs. Type terms can be: •A type variable (X,Y, . . . ) •A type symbol (defined in a set of type rules) (α,β, . . . ) •A type constant (1, a, . . . ) •A function symbol with arity n, applied to an n-tuple of regular types (f(τ1, . . . , τn)) It is assumed that every type constant can be typed by a base type, for instance, 1can be typed with the base type int. There is a set Tof type rules, each of them defining a type symbol. Zobel also introduces two types representing every term (µ) or no term 8 (φ). We can associate a definite program ΦTto this set consisting of the definitions for µ,φ, any base type and the set of clauses associated with the type rules defined in T. For example, the logic program corresponding to the type τ→ {[ ],[α|τ]}is: t([ ]). t([X|R]) : −α(X),t(R). The interpretation of a type symbol according to T, [α]Tis the set of terms occurring as arguments of the unary predicate αin the least model MΦTof the program ΦT. This association is defined not only for type symbols but also variable-free type terms and it is defined as follows: [τ]T=          {c}if τis a constant symbol c {t|α(t)∈MΦT}if τis a type symbol α {f(t1, . . . , tn)|ti∈[τi],1≤i≤n}if τis a variable-free type term f(τ1, . . . , τn) Regular types correspond to tree automata [CDG+07], which is a class of languages where intersection, subset and unification are decidable. Types are defined through type rules T. Example 3. Let αbe a type symbol. The following is a type rule defining a list of β with the list constructor ‘.’: α→ {nil, .(β, α)} where αand βare type symbols, and there should be a another rule defining β. One important characteristic of this algorithm is that the regular types infered are tuple distibutive [LC98], which means that inter-argument dependencies are ignored when inferring the types. For instance, if we have a set of terms that use the same function symbol such as {g(a, b), g(c, d)}, then with the tuple distributivity property, we can ensure g(c, b) and g(a, d) have the same type. This is an essential property for the correctness and completeness of the algorithm [LC98]. To build a type inference algorithm using regular types, Zobel also defined four main functions [Zob87, DZ92]. The empty function is given a variable-free type term and a set of type rules defining all necessary type symbols and returns true if the type term is empty, and false otherwise. For a type term to be empty, either it is the empty type φ, or it is a function 9 symbol applied to an empty type among its arguments, or it is a type symbol, whose definition is empty. The subset function takes as input type terms τ1and τ2and a set of type rules defining all necessary type symbols and returns true if τ1is a subset of τ2. There is a number of possibilities, either they are the same, or τ1is a constant type and τ2is the base type of that constant, or they have the same function symbol and the arguments of τ1are a subset of the arguments of τ2. It may also be that τ1is the empty type or τ2is µ, or τ1is a type symbol whose definition is a subset of τ2. Example 4. Let κbe a base type symbol denoting the base type atomic and let T= {α→ {nil, f(a, f(a, α))}, β → {nil, f(κ, β)}. Consider the comparison subset(α, β). As we can see, αdenotes the set of structures of even lengths of aand βdenotes the set of structures of atomic symbols. So the result of the comparison is true, since, in fact, [α]T⊆[β]T. The function intersect takes two variable-free type terms τ1and τ2and a set of type rules defining all necessary type symbols occurring in both input type terms and returns a type term that represents the intersection of the sets represented by τ1and τ2. It also returns a new set of type rules, since intersection of some types may create new type symbols, with rules associated. Example 5. Let us consider T={α→ {s(0), s(s(α))}, β → {0, s(s(β))}}, where αrepresents the set of odd length structures with the function symbol sand βthe even ones. The result of applying intersection(α, β, T) is the pair (γ, T0), where T0=T∪ {γ→ {s(s(γ))}}, which is now an empty type, as can be verified by empty(γ) = true. The last function and the one which is used on the type inference algorithm is unify. The unify function takes two type terms τ1and τ2and, again, a set of type rules and returns a type corresponding to the unification of τ1and τ2(given a substitution S, τ1S=τ2S), a new set of type rules, since new type symbols may be necessary for the unification, as well as a substitution for the variables appearing on both types. The unify function calls intersect when both type terms are variable-free, since the unification makes no sense with two variable-free type terms because τ1S=τ1and τ2S=τ2. Here, we present the full algorithm as defined in [Zob87]: unify(τ1, τ2, T, Θ) = 10 1. Suppose τ1and τ2are identical, return (τ1, T, Θ). 2. Suppose one of τ1or τ2is µ. If τ1is µ, return (τ2, T, Θ), otherwise return (τ1, T, Θ). 3. Suppose at least one of τ1and τ2is a variable. If τ1< τ2, let τ1 /ωbe the type binding for τ1in Θ. If τ1occurs in τ2, return (φ, T, Θ), otherwise, let (ω0, Tf,Θ0) := unify(ω, τ2, T, Θ). Replace τ1 /ωin Θ0by τ1 /ω0giving Θfand return (τ1, Tf,Θf). Conversely for τ2. 4. Suppose both τ1and τ2are variable-free type terms. Let (τf, Tf) :=intersect(τ1, τ2, T) and return (τf, Tf,Θ). 5. Suppose one of τ1and τ2is a type symbol defined in T. Suppose τ1is a type symbol defined in T,τ1→Υ, and τ2has top-level n-ary function symbol f,n≥0. Let (τ, T0) :=intersect(α, τ1, T ∪ {α→ {f(µ, . . . , µ)}}). Then τis a type symbol, τ→Υ∈T0, and each ω∈Υ is of the form f(ω1, . . . , ωn). Let T00 be T0∪ {αk→ {ωk|f(...,ωk, . . . )∈Υ}|1≤k≤n} where each αkis a new type symbol. Let (τf, Tf,Θf) := unify(τ2, f(α1, . . . , αn), T00,Θ) and return (τf, Tf,Θf). (conversely if τ2is a type symbol defined in T). 6. Suppose τ1is f(τ1 1, . . . , τ1 n) and τ2is f(τ2 1, . . . , τ2 n). For each i, 1 ≤i≤n, let (τf i, T, Θ) := unify(τ1 i, τ2 i, T, Θ). Return (f(τf 1, . . . , τf n), T, Θ). 7. Otherwise, τ1and τ2are type terms with distinct top-level function symbols, or one of τ1or τ2is a complex term and the other is a base type symbol. Return (φ, T, Θ). Example 6. Let T={α→ {f(a, b), f(c, d)}}. The call unify(f(x, y), α, T, ∅) returns the triple (f(x, y), Tf,Θf), where Tf=T∪ {β→ {a, c}, γ → {b, d}} and Θf={β/x,γ/y}. So, [f(x, y)Θf]Tfis {f(a, b), f(a, d), f(c, b), f(c, d)}and the result given by the function is the most general type unifier of αand f(x, y). Here we can see the tuple distributivity property of this algorithm. 11 Example 9. These are examples of possible argument types according to our syntax: τ1=int +atom, τ2=f(α) + g(α), τ3=τ1 g+h(τ1 f) The operands of a sum type are called summands. Notice that in a sum type, or as an argument for a functor, we can have some other argument type. 3.2 Closed Types Closed types are, intuitively, types that are constrained in some way. If a type is open, then its possibilities extend to any term constructed from any type constructor, including type constructors not present in the program defining that predicate. This is what we want to avoid and by forcing types to be closed, we get control on which function symbols and base types are accepted by the program. The definition follows: Definition 4 (Closed Types). A type for a predicate argument τis closed with respect to a set Θdefining all types for the predicate if: 1. τ6=α+ Φ, for any non-empty Φ 2. τ=α∈Θiff αoccurs in Θ\ {τ=α} The first case of this definition avoid open data types while the second case avoids unconstrained type variables which could be instantiated by the whole Herbrand universe. Example 10. τ1=α+f(β) is not a closed type with respect to any Θ, since it does not respect the first case of our definition. τ2=int +f(α) is a closed type with respect to any set Θ, since it does not have variables as summands. Closed types create a controlled environment, meaning that if we were to build the Herbrand model of a logic program, the terms given to variables would not be instantiated with function symbols and constant symbols that were not present in the 18 program. Or, if they were, there would be some restriction to the possibilities of such types. This is our motivation, coming from the following intuition: closed types can only contain terms built from function and constant symbols defined in the program, or in the case they are represented by a variable, there is a constraint on that variable. 3.3 Type Intersection Type intersection is fundamental in the type system in order to type the conjunction of two goals that share at least one variable. This was previously defined for regular types [DZ92] and discussed in Section 2.2. Here we discuss in depth the definition of the operation with the alterations we made for our type system. Let Tbe a set of type rules defining a certain number of type symbols and I, a set of triples hτ1, τ2, τithat stores information on the result of intersecting two types to guarantee termination (Ialways starts as the empty set). intersection(τ1, τ2, T, I) = 1. Suppose τ1and τ2are identical. Return (τ1, T). 2. Suppose one of τ1and τ2is a variable. If τ1is a variable, return (τ2, T), otherwise, return (τ1, T). 3. Suppose there exists αsuch that hτ1, τ2, αi ∈ I. Return (α, T). 4. Suppose at least one of τ1and τ2is a type symbol defined in T. If τ1is defined in T, then let Υ1be such that τ1→Υ1, else let Υ1:= {τ1}. Define Υ2similarly for τ2. Let (Υf, T) := cpi(Υ1,Υ2, T, I ∪{hτ1, τ2, αfi}), where cpi calculates the intersection of every term of Υ1with every term of Υ2, and return (αf, T ∪{αf→Υf}). 5. Suppose τ1is f(τ1 1, . . . , τ1 n) and τ2is f(τ2 1, . . . , τ2 n), k≥0. For each i, 1 ≤i≤n, let (τf i, T) := intersection(τ1 i, τ2 i, T, I). Return (f(τf 1, . . . , τf n), T). 6. Otherwise, either τ1and τ2are different base types or have different function symbols of one is a complex term and the other is a base type, in that case fail the intersection. 19 We can see that the intersection of two base types is themselves if they are equal, and it fails if they are different and the intersection of two type symbols is the intersection of the summands in their definition. The intersection of a type symbol and a term type is another type symbol whose definition is the intersection of the summands in the previous type symbol’s definition and the term. The intersection of two complex type terms with the same function symbol is the complex type term built by intersecting argument by argument the initial type terms. It may happen that a variable is used to intersect with another type term in some cases, for instance, if a variable is present in the definition of a type symbol, in which case the intersection is always the less general type term. Example 11. The intersection of types: τ1 f=int +f(int) and τ1 h=int +atom is: τ0=int It is important to note that type intersection was previously only defined for ground type terms, but we needed to extend such definition, since the type any does not exist in this syntax as it existed in [Zob87], from where this definition was based. We defined the intersection of a variable (which will only happen when this variable represents the type any) with any other type to be the type itself. It may happen that both are variables and in that case it is indifferent which one is chosen. 3.4 Type System The type system defines a relation Θ,Γ`p:τ, where Θ is a set of type definitions, defining all type symbols, Γ = {X1:τ1, . . . , Xn:τn}is the environment of type declarations for logic variables, pis an expression (a term, a goal, or a predicate definition), and τis a type. This relation should be read as expression phas type τdefined in Θ, given the type environment Γ. We write Θ(α) for the type τsuch that α=τis in Θ, Γ(X) for the type paired with Xin Γ and ΓXfor the type environment Γ with any pair for the variable Xremoved. We also write def (Θ) for the set {α|∃τ.α =τ∈Θ}. Let us now define two auxiliary operations on type definitions. 20 If Θ1and Θ2are two sets of type definitions, we define Θ1⊕Θ2and Θ1⊗Θ2as follows: for each α∈def(Θ1)∪def(Θ2) (Θ1⊕Θ2)(τ) =          Θ1(τ), τ 6∈ def(Θ2) Θ2(τ), τ 6∈ def(Θ1) Θ1(τ)+Θ2(τ), otherwise and (Θ1⊗Θ2)(τ) =          Θ1(τ), τ 6∈ def(Θ2) Θ2(τ), τ 6∈ def(Θ1) intersect(Θ1(τ),Θ2(τ)), otherwise One can easily show that ⊕and ⊗are commutative and associative operators. To simplify the presentation of the type system let us assume that all predicates are defined in a single definition in disjunctive normal form. Note that it is always possible to transform a logic program consisting of several clauses into this form by substituting every comma with a ∧and separating each body in the same destination body by a ∨. Example 12. In the case of the predicate add: add(0,X,X). add(s(X),Y,s(Z)) : −add(X,Y,Z). The normal form is: add(X1,X2,X3) : −(X1=0∧X2=X3)∨(X1=s(X)∧X2=Y∧X3=s(Z)∧ ∧Y1=X∧Y2=Y∧Y3=Z∧add(Y1,Y2,Y3)). We can see the rules of the type system in Figure 3.1. Let Σ represent a sum type as the sum of parcels that represents the disjunction of the several possibilities of the type and let h(~x) be the abbreviation of the predicate h(x1, . . . , xn). The VAR rule types a variable by seeing the definition of the type that is declared in Γ and either giving as a type the attributed type itself or a subset of the summands defining it. The operator vrepresents that the sum type on the left side has either some or all the summands that are on the right side sum type. The CONS rule types a constant assuming that its types are given by a built-in function. The TERM, GOAL and 21 V AR Θτ∪ {τ= Σ},Γx∪ {x:τ} ` x: Σ0,where Σ0vΣ or Σ0=τ CONS Θ,Γ`c:τ , where τis the base type for c TERM Θ,Γ`t1:τ1,...,Θ,Γ`tn:τn Θ,Γ`f(t1, . . . , tn) : f(τ1, . . . , τn) UNIF Θ,Γ`t1:τΘ,Γ`t2:τ Θ,Γ`t1=t2:τ GOAL Θ,Γ`t1:τ1,...,Θ,Γ`tn:τn Θ,Γ`p(t1, . . . , tn) : τ1× · · · × τn CONJ Θ1,Γ`t1:τ1Θ2,Γ`t2:τ2 Θ1⊗Θ2,Γ`t1∧t2:τ1∗τ2 DISJ Θ1,Γ`t1:τ1Θ2,Γ`t2:τ2 Θ1⊕Θ2,Γ`t1∨t2:τ1+τ2 CLS Θ,Γx∪ {~x :~τ} ` h(~x) : ~τ Θ,Γx∪ {~x :~τ} ` b:τ1 Θ,Γx`(h(~x) : −b) : ~τ Figure 3.1: Type rules 22 UNIF rules are straightforward. In the CONJ and DISJ rules, typing respectively conjunctions and disjunctions of conjunctions of goals, the symbols ∗and + on the types are used only as infix type constructors. The clause rule, CLS, propagates the type of the head of the clause to the main predicate definition and discards the types used for its arguments from the environment, given that the body of the clause can be typed with some type with the same sets Γ and Θ (note the similarity with the usual abstraction rule to type lambda-terms or functions in functional languages) [DM82]. Example 13. Here we present a derivation tree for the type of the predicate list, defined as follows: list([ ]). list([X|Xs]) : −list(Xs). The derivation tree assumes a set of attributions of types to variables and a set of type rules defining the types attributed to those variables. To simplify the presentation of the tree, we will assume that along it, the set of attributions will be Γ = {X1:τ, X : σ, Xs :τ}and the set of type rules, Θ = {τ=nil + [σ|τ], σ =α}. Let Tree1be: Θ,Γ`X1:nil Θ,Γ`[ ] : nil Θ,Γ`X1= [ ] : nil And Tree2be: Θ,Γ`X:σΘ,Γ`Xs :τ Θ,Γ`[X|Xs] : [σ|τ] Θ,Γ`X1: [σ|τ] Θ,Γ`X1= [X|Xs]:[σ|τ] Θ,Γ`Xs :τ Θ,Γ`list(Xs) : τ Θ,Γ`(X1= [X|Xs]∧list(Xs)) : ([σ|τ]∧τ) The full derivation tree is: Θ,Γ`X1:τ Θ,Γ`list(X1) : τ . . . Tree1 . . . Tree2 Θ,Γ`(X1= [ ]) ∨(X1= [X|Xs]∨list(Xs)) : (nil ∨([σ|τ]∧τ)) Θ,Γ`list(X1) : −(X1= [ ]) ∨(X1= [X|Xs]∧list(Xs)) : τ 23 3.5 Semantics Usually types for logic programming are interpreted as a conservative approximation to the program semantics. This is not the case of the type system defined in this work. In fact, for instance, the append predicate may have type list(int) for its three arguments although it can be applied to lists of other types. We thus follow the view of types as descriptions of program properties and not as approximations of the program semantics. The semantics of base types and argument types are defined (as usual in previous works on types for logic programming), as a set of terms, meaning [[int]] = [0,1,2, . . . ] and [[int +atom]] = [[int]] ∪[[atom]]. However, the semantics defined for a predicate type is quite different from the ones in other literature on types for logic programs. Instead of interpreting a type as an approximation to the success set of a program, a descriptive view of types is taken (details about the descriptive versus prescriptive view of types can be found in [Bar92]), interpreting them as all the predicates that can be described by the type. So, for a ground predicate type the semantics is: [[τ1×· · ·×τn]] = {p| ∃k1. . . kn.p(k1, . . . , kn)succeeds and k1∈[[τ1]], . . . , kn∈[[τn]]} This is close to the view of descriptive type systems for functional languages. For example, in a descriptive functional the type Int →Int types every function from integer to integer, regardless of what the function is. Likewise, in this system, the type int ×int is a type for every predicate that relates two integers. 3.5.1 Polymorphism Given a parametric type τ(α), where αis a type variable occurring in τ, its semantics can be seen as follows: [[τ(α)]] = \ ∀k [[τ(k)]] With this interpretation, a type such as τ=list(α)×list(α) describes all the predicates with two arguments that are lists of a parameter, such as reverse,sublist, etc., but not those that work on specific lists of integers or strings as they will not belong to 24 the intersection with other types: lists of integers do not belong to the semantics of the type list(string) or vice-versa. A consequence of this interpretation is that it can now easily be defined the notion of most general type. For instance, the predicate reverse, can have type τ1=list(int)× list(int), but also τ2=list(atom)×list(atom) and τ3=list(α)×list(α). The type τ3is the most general type, as it is the one that for any type σthat we can give to the predicate reverse, [[τ3]] ⊆[[σ]]. This is true since if there is a predicate that only accepts lists of integers, it will not have type τ3, but if a predicate uses general polymorphic lists, in particular it will have all the types of instantiated lists, such as types τ1and τ2. The focus of this work is automatic type inference, mainly the definition of a descriptive type system for logic programming and a type inference algorithm which is sound with respect to the type system. In [LR91] a semantic relation between programs and types was presented using a type-theoretical model semantics for Typed Prolog based on many-sorted logic. There, the semantics of base types was viewed as sorts and the usual definitions of model semantics for logic programming (interpretations, minimal models and the immediate consequence operator TP) were extended for typed predicates. We conjecture that this should also hold for our type system and we leave it to future work. 25 Chapter 4 Type Inference 4.1 Stratification The type system of the previous chapter relates programs with types but it does not provide a method for finding, given a program p, a type τ, a set of type definitions Θ and a type environment Γ such that Θ,Γ`p:τ. We now present an algorithm for this purpose. The algorithm assumes that input programs are in normal form. This normal form is the one presented in Section 3.4 and illustrated in Example 12 and was used in implementation settings for logic programming, being called flatten form [AK91]. It represents a general definition or call of a predicate p(t1, . . . , tn) by p(X1, . . . , Xn) and a conjunction of equations of the form X1=t1, . . . , Xn=tn. We use type unification and type intersection algorithms similar to the ones defined in [Zob87]. Another assumption we make is that the input program of our algorithm is stratified [Ull88]. To understand the meaning of stratified programs, let us define a dependency directed graph of a program as the graph that has one node representing each predicate in the program and an edge from p0to pfor each call from a predicate pto a predicate p0. Definition 5 (Stratified Program). A stratified program Pis such that the dependency directed graph of Phas no cycles of size more than one. What this means is that programs that have some predicate pthat depends on a predicate qand vice versa will not be typed by our algorithm. The same holds for other cycles of sizes of length greater than two. Stratification is relevant because for stratified programs we can infer types for each predicate, beginning by the ones whose 26 definition consists of facts or is self-recursive, and step-by-step infer types for predicates that only depend on types from previous steps and, possibly, are self-recursive as well. 4.2 Type Constraints Our algorithm relies on solving type equations corresponding to type unification constraints. The constraint for a predicate pwith arity non argument iwill be τi p=term, where term is the content of the predicate in that argument in some clause and logic variables are replaced by type variables. The algorithm follows the program according to its dependency graph: we start by inferring types for predicates that only depend on themselves or on no predicate at all (a predicate whose definition consists of facts only) and then we progressively infer types for predicates whose predicates they depend already have a type. We will use the type constraints present on the body due to the flatten form and get a substitution for the type variables on the head of the clause. Example 14. The constraints we get for the following clause: p(X,Y) : −f(X),g(X),q(1,Y). are: τ1 f=α,τ1 g=α,τ1 q=int,τ2 q=β Some of these constraints, such as τ1 q=int will be a simple type checking for the first argument of predicate q, the other constraints will generate a substitution for the variables on the head of the clause. As we mentioned before, we can assume that all predicates on the body are typed since the program is stratified. 4.3 Open vs Closed Type Inference In some cases, when the definition of a predicate has a single occurrence of a variable in the heads of all the clauses defining the predicate, then type will be open. This happens because there is no information on the type of possible instances of the variable, since it is free. 27 4.5.3 Closure Step The last step in our algorithm is the closure of types. We perform the closure after all clauses of the definition of each predicate are analyzed and before a type is inferred for the next predicate. Example 22. For instance the type for the append predicate arguments: τ1 append = [ ] + [α|τ1 append] τ2 append =β τ3 append =β+ [α|τ3 append] will be closed, and the result will be: τ1 append = [ ] + [α|τ1 append] τ2 append = [ ] + [α|τ2 append] τ3 append = [ ] + [α|τ3 append] Example 23. The types we infer for the predicate: length([],0). length([X|Xs],N) : −length(Xs,N1),NisN1 +1. are as follows: τ1 length = [] + [α|τ1 length] τ2 length =int Example 24. For the predicate add defined as follows: add(0,X,X). add(s(X),Y,s(Z)) : −add(X,Y,Z). The open types would be: τ1 add =int +s(τ1 add) 34 τ2 add =α τ3 add =α+s(τ3 add) And when we apply the closure, we get: τ1 add =int +s(τ1 add) τ2 add =int +s(τ2 add) τ3 add =int +s(τ3 add) Example 25. Let flatten be the predicate whose first argument is a nested list of lists and the second is the flat version of that nested list, defined as follows: flatten([],[]). flatten([L|R],Flat) : −flatten(L,F1),flatten(R,F2),append(F1,F2,Flat). flatten(L,[L]). The output of our algorithm before closure is: flatten =flatten.1×flatten.2 flatten.1=[flatten.1|flatten.1] + [ ] + x1. flatten.2 = append.3+[]+[x1]. The type for the first argument is open and we can see that with the closure, we will not have the case were the nested list has an integer. This problem can be solved by changing the predicate definition as follows: flatten([],[]). flatten([L|R],Flat) : −flatten(L,F1),flatten(R,F2),append(F1,F2,Flat). flatten(elem(L),[elem(L)]). Now, the types are: flatten =flatten.1×flatten.2 flatten.1=[flatten.1|flatten.1] + [ ] + elem(x1). flatten.2 = append.3+[]+[elem(x1)]. which are closed types. The closure step ensures that the resulting types will be closed, so they will not have free variables or that if they have, then those variables are type constrained. This is 35 visible in the predicate first that is defined as follows: first((X,Y),X). The types we get for that predicate arguments are: τ1 first = (α, β). τ2 first =α. Although the type for the second argument is a variable, the variable occurs in the type for the first argument and as such, the types are closed. On the other hand, a predicate first defined like this: first(X,Y,X). Is not accepted by our algorithm because now the second argument, Y, is a free variable with a single occurrence, which means it can be representing any term, so the type τ2 first is open and it is not possible to close it, since we have no more constraints for that argument. 4.5.4 Soundness Here we show that our algorithm is sound, i.e., infers types derived by our type system. Theorem 1 (Soundness) If infer(p) = (Θ,Γ, τ), then there are Θ1⊇Θand Γ1⊇Γsuch that Θ1,Γ1`p:τ Proof: By structural induction on p. Base cases: VAR: infer(X) = ({α=β},{X:α}, β). Let Θ1= Θ and Γ1= Γ, then Θ1,Γ1`X:β. CONS: infer(c) = (∅,∅, τ), where basetype(c) = τ. Let Θ1= Θ and Γ1= Γ, then Θ1,Γ1`c:τ, where basetype(c) = τ. Induction step: TERM: infer(f(t1, . . . , tn)) = (Θ1∪. . . ∪Θn,Γ1∪. . . ∪Γn, f(α1, . . . , αn)). 36 By the induction hypothesis there are Θ10,...,Θn0,Γ10,...,Γn0such for 1 ≤i≤n, Γi0 ⊇ Γiand Θi0 ⊇ Θisuch that Θi0,Γi0 ` t:αi. Then, by the TERM rule, for Θ = Θ10∪. . .∪Θn0and Γ = Γ10∪. . .∪Γn0, it follows Θ,Γ`f(t1, . . . , tn) : f(α1, . . . , αn). UNIF: infer(t1=t2)=(S(Θ),Γ1∪Γ2, τ). By the induction hypothesis, there are Θ0,Γ10and Γ20such that Θ0 ⊇ Θ, Γ10 ⊇ Γ1 and Γ20 ⊇ Γ2such that Θ0,Γ10 ` t1:τand Θ0,Γ2`t2:τ. Then, by the rule UNIF, Proposition 1 and Proposition 2, for Θ1=S(Θ) and Γ = Γ1∪Γ2, then Θ1,Γ`t1=t2:τ. (Note that according to the definition of unify, S(τ) = τ) GOAL: infer(p(X1, . . . , Xn)) = (Θ = {α1=τ1 p, . . . , αn=τn p},Γ = {X1:α1, . . . , Xn: αn}, α1×. . . ×αn)). By the induction hypothesis, there are Θ10,...,Θn0,Γ10,...,Γn0such for 1 ≤i≤n, Γi0 ⊇ Γiand Θi0 ⊇ Θisuch that Θi0,Γi0 ` Xi:αi. Then, by the GOAL rule, for Θ = Θ10∪. . .∪Θn0and Γ = Γ10∪. . .∪Γn0, it follows Θ,Γ`p(X1, . . . , Xn) : α1×· · ·×αn. CONJ: infer(p1∧p2) = (Θ1⊕Θ2,Γ1∪Γ2, τ1∗τ2). By the induction hypothesis, there are Θ10,Θ20,Γ10and Γ20, such that Θ10 ⊇ Θ1, Θ20 ⊇ Θ2, Γ10 ⊇ Γ1and Γ20 ⊇ Γ2such that Θ10,Γ10 ` p1:τ1and Θ20,Γ20 ` p2:τ2. Then, by the CONJ rule, for Θ = Θ10⊕Θ20and Γ = Γ10∪Γ20, it follows Θ,Γ`p1∧p2:τ1∗τ2. DISJ: infer(p1∨p2) = (Θ1⊗Θ2,Γ1∪Γ2, τ1+τ2). By the induction hypothesis, there are Θ10,Θ20,Γ10and Γ20, such that Θ10 ⊇ Θ1, Θ20 ⊇ Θ2, Γ10 ⊇ Γ1and Γ20 ⊇ Γ2such that Θ10,Γ10 ` p1:τ1and Θ20,Γ20 ` p2:τ2. Then, by the DISJ rule, for Θ = Θ10⊗Θ20and Γ = Γ10∪Γ20, it follows Θ,Γ`p1∨p2:τ1+τ2. CLS: infer(h(~ X) : −body) = (Θ,ΓX,~τ). By the induction hypothesis, there are Θ0and Γ0, such that Θ0 ⊇ Θ and Γ0 ⊇ Γ for which Θ0,Γ0 ` body :τ1and Θ0,Γ0 ` h(~ X) : ~τ. Then, by the CLS rule, it follows Θ0,Γ0 ` (h(~ X) : −body) : ~τ. 37 Chapter 5 Implementation In this chapter, we give an overview of the implementation and practical examples of the results obtained by our implementation. We will also show some top level functions and explain the components that are called from those main functions. 5.1 Overview The implementation of the type inference algorithm follows almost directly from the definition. In Figure 5.1 we can see the different modules of the algorithm. The output of our algorithm represents type symbols that are not associated with a predicate argument as terms of the form type(n), where nis an integer. The method we chose for printing the result is similar to how we represented types in our syntax during this work. A type for a predicate will be the tuple of the types for its arguments and the type for each argument will be defined bellow by a type equation, followed by any type symbols that may be used in the equations for that predicate. 5.2 Top-Level Predicates Here we will now present the top-level predicate in the implementation of the type inference algorithm: type program(InputName,Types) : − open(InputName,read,InputStream), 38 Input Program Ordering of Predicates Normalization and Constraint Generation Contraint Solving Closure Simplification Output Types Figure 5.1: Modules of the type inference algorithm’s implementation type program input(InputStream,[],Rules), order(Rules,Order), typing(Rules,Order,[],Types), close(InputStream), print aux types(Types), write(0EndTypes!0),nl. The predicate open reads the input file and gets our program, then the predicate type program input devides the program in several rules, each corresponding to a Prolog clause. The predicate order will find the order that the rest of the algorithm will follow according to the dependency graph of the program. After this, the typing predicate will do most of the work on the actual inference of types, including the normalization component as well as the constraint generation, constraint solving and the closure step. Then we use close to close the file we opened before and the predicate print prints the types that were not printed in the typing predicate. We will know show more in detail the predicate typing since it does most of the work on the actual inference of types: typing(,[],Tf,Tf). typing(Clauses,[Pred|Ps],Ac,Types) : − take pred only(Clauses,Pred,CP), 39 take facts(CP,Facts,Rest), build types(Facts,[],Types1), append(Ac,Types1,Types2), type clauses(Rest,Types2,AcNovo), final simplification(AcNovo,Types3), closure(Types3,Types3,[],Types4), pretty printing(Types4,Pred), typing(Clauses,Ps,Types4,Types). It is clear now how the algorithm works, we first take the clauses that define the predicate on the current position of the ordering list, then we use the facts to immediately get a summand for the types of the arguments of the predicates and we infer types from the clauses that have bodies in type clauses. In the end, we apply our closure heuristics and after that we just print the resulting types for that predicate. Here, we argue that taking the facts first instead of changing the definition of a predicate to flatten form does not change the result, since all constraints that come from facts on the flatten form will end up just adding a summand to the type of each argument, which is what we do in the first place. 5.3 Examples We will now present the results we got from testing our implementation on some more predicates. Example 26. Let Pbe the following program: f(1). h(1). h(a). p(X) : −f(X),h(X). The output of our algorithm follows: f:: f.1 f.1 = num. h:: h.1 40 h.1 = num +atom. p:: p.1 p.1 = type(0). type(0) = num. As we can see, we just substitute the τas a symbol for the types and put the predicate name with its arity and position as symbol. It will be unique because even if two predicates have the same name, they will not have the same arity. If a predicate has more than one argument, the types for the predicate arguments are presented in order and the type for the predicate will have the types for the arguments separated by ×. Example 27. Let Pbe a program that defines the predicate append as it has been defined in other places in this work. The resulting types from our implementation follow: append =append.1×append.2×append.3 append.1 = [x0|append.1] + [ ]. append.2 = [x0|append.2] + [ ]. append.3 = [x0|append.3] + [ ]. Our implementation deals with equality, inequality, and the is/2 predicate. For the inequality, both sides have type num. For the equality, the type for both terms must be equal, and for the attribution, the constraint is that the left-side argument has type num. We will improve the constraints obtained from attributions by including constraints for every variable with type num. Example 28. Let pbe the predicate defined as follows: p(0). p(X) : −X1 is X −1,p(X1). The types inferred are the following: p=p.1 p.1 = num. 41 This is an example where we show how we deal with the constraints for the predicate is/2. The type num is attributed to X1 and that is the result we get for the type of the whole predicate argument, since 0 also has type num. 42 Chapter 6 Conclusions On this thesis, we defined a type system for logic programming that accepts programs typed by closed types. We also defined a type inference algorithm that is sound according to the type system. Both the type system and the algorithm followed our definition of closed types that says types must be constrained in order for a program to be well-typed. Our definition of closed types corresponds to what we understand by not too overgenerous programs and the results we got from the tests performed on several programs are what we intended. One of the advantages of our type system is that the types will have better approximation to terms that should be accepted by the program than open types, according to the programmer’s intention. Analyzing the results obtained by the implementation of our algorithm, we would like to point out some characteristics. First of all, we were very pleased with the results for the tests we performed as they matched the intended types for our definitions. Secondly, we think the results obtained are easy to understand and although they constrain the terms accepted by the program, we think that they are not toorestrictive. In the future we will work on proving the type system is sound with respect to the logic programming semantics we defined and that the type inference algorithm is complete with respect to the type system. We also want to increase the number of typed Prolog built-ins. 43