Véronique Benzaken

Giuseppe Castagna

Kim Nguyễn

Jérôme Siméon

Kim Nguy Ễn

Static and dynamic semantics of NoSQL languages

come

Introduction

The emergence of Cloud computing, and the ever growing importance of data in applications, has given birth to a whirlwind of new data models [START_REF]Javascript object notation[END_REF][START_REF] Odata | [END_REF] and languages. Whether they are developed under the banner of "NoSQL" [START_REF]Jsoniq[END_REF][START_REF] Unql | [END_REF], for BigData Analytics [START_REF] Beyer | Jaql: A scripting language for large scale semistructured data analysis[END_REF][START_REF] Jaql | [END_REF][START_REF] Olston | Pig latin: a not-so-foreign language for data processing[END_REF], for Cloud computing [START_REF] Behm | Asterix: towards a scalable, semistructured data platform for evolvingworld models[END_REF], or as domain specific languages (DSL) embedded in a host language [START_REF] Meijer | The world according to LINQ[END_REF][START_REF] Ohori | Making standard ML a practical database programming language[END_REF][START_REF]Squeryl: A Scala ORM and DSL for talking with Databases with minimum verbosity and maximum type safety[END_REF], most of them share a common subset of SQL and the ability to handle semistructured data. While there is no consensus yet on the precise boundaries of this class of languages, they all share two common traits: (i) an emphasis on sequence operations (eg, through the popular MapReduce paradigm) and (ii) a lack of types for both data and programs (contrary to, say, XML programming or relational databases where data schemas are pervasive). In [START_REF] Meijer | The world according to LINQ[END_REF][START_REF] Meijer | A co-relational model of data for large shared data banks[END_REF], Meijer argues that such languages can greatly benefit from formal foundations, and suggests comprehensions [START_REF] Buneman | Comprehension syntax[END_REF][START_REF] Tannen | Naturally embedded query languages[END_REF][START_REF] Trinder | Improving list comprehension database queries[END_REF] as a unifying model. Although we agree with Meijer for the need to provide unified, formal foundations to those new languages, we argue that such foundations should account for novel features critical to various application domains that are not captured by comprehensions. Also, most of those languages provide limited type checking, or ignore it altogether. We believe type checking is essential for many applications, with usage ranging from error detection to optimization. But we understand the designers and programmers of those languages who are averse to any kind of type definition or annotation. In this paper, we propose a calculus which is expressive enough to capture languages that go beyond SQL or comprehensions. We show how the calculus adapts to various data models while retaining a precise type checking that can exploit in a flexible way limited type information, information An extended abstract of this work is included in the proceeding of POPL 13, 40th ACM Symposium on Principles of Programming Languages, ACM Press, 2013.

that is deduced directly from the structure of the program even in the absence of any explicit type declaration or annotation.

Example. We use Jaql [START_REF] Beyer | Jaql: A scripting language for large scale semistructured data analysis[END_REF][START_REF] Jaql | [END_REF], a language over JSON [START_REF]Javascript object notation[END_REF] developed for BigData analytics, to illustrate how our proposed calculus works. Our reason for using Jaql is that it encompasses all the features found in the previously cited query languages and includes a number of original ones, as well. Like Pig [START_REF] Olston | Pig latin: a not-so-foreign language for data processing[END_REF] it supports sequence iteration, filtering, and grouping operations on non-nested queries. Like AQL [START_REF] Behm | Asterix: towards a scalable, semistructured data platform for evolvingworld models[END_REF] and XQuery [START_REF] Boag | XQuery 1.0: An XML query language[END_REF], it features nested queries. Furthermore, Jaql uses a rich data model that allows arbitrary nesting of data (it works on generic sequences of JSON records whose fields can contain other sequences or records) while other languages are limited to flat data models, such as AQL whose data-model is similar to the standard relational model used by SQL databases (tuples of scalars and of lists of scalars). Lastly, Jaql includes SQL as an embedded sub-language for relational data. For these reasons, although in the present work we focus almost exclusively on Jaql, we believe that our work can be adapted without effort to a wide array of sequence processing languages.

The following Jaql program illustrates some of those features. It performs co-grouping [START_REF] Olston | Pig latin: a not-so-foreign language for data processing[END_REF] between one JSON input, containing information about departments, and one relational input containing information about employees. The query returns for each department its name and id, from the first input, and the number of high-income employees from the second input. A SQL expression is used to select the employees with income above a given value, while a Jaql filter is used to access the set of departments and the elements of these two collections are processed by the group expression (in Jaql "$" denotes the current element).

group

(depts -> filter each x (x.size > 50)) by g = $.depid as ds, (SELECT * FROM employees WHERE income > 100) by g = $.dept as es into { dept: g, deptName: ds[0].name, numEmps: count(es) };

The query blends Jaql expressions (eg, filter which selects, in the collection depts, departments with a size of more than 50 employees, and the grouping itself) with a SQL statement (selecting employees in a relational table for which the salary is more than 100). Relations are naturally rendered in JSON as collections of records. In our example, one of the key difference is that field access in SQL requires the field to be present in the record, while the same operation in Jaql does not. Actually, field selection in Jaql is very expressive since it can be applied also to collections with the effect that the selection is recursively applied to the components of the collection and the collection of the results returned, and similarly for filter and other iterators. In other words, the expression filter each x (x.size > 50) above will work as much when

x is bound to a record (with or without a size field: in the latter case the selection returns null), as when x is bound to a collection of records or of arbitrary nested collections thereof. This accounts for the semistructured nature of JSON compared to the relational model. Our calculus can express both, in a way that illustrates the difference in both the dynamic semantics and static typing.

In our calculus, the selection of all records whose mandatory field income is greater than 100 is defined as: let Sel = 'nil => 'nil | ({income: x, .. } as y , tail) => if x > 100 then (y,Sel(tail)) else Sel(tail) (collections are encoded as lists à la Lisp) while the filtering among records or arbitrary nested collections of records of those where the (optional) size field is present and larger than 50 is:

let Fil =
'nil => 'nil | ({size: x, .. } as y,tail) => if x > 50 then (y,Fil(tail)) else Fil(tail) | ((x,xs),tail) => (Fil(x,xs),Fil(tail)) | (_,tail) => Fil(tail) The terms above show nearly all the basic building blocks of our calculus (only composition is missing), building blocks that we dub filters. Filters can be defined recursively (eg, Sel(tail) is a recursive call); they can perform pattern matching as found in functional languages (the filter p ⇒ ⇒ ⇒ f executes f in the environment resulting from the matching of pattern p); they can be composed in alternation (f1| | |f2 tries to apply f1 and if it fails it applies f2), they can spread over the structure of their argument (eg, ( ( (f1,f2) ) ) -of which (x,Sel(tail)) is an instance-requires an argument of a product type and applies the corresponding fi component-wise).

For instance, the filter Fil scans collections encoded as lists à la Lisp (ie, by right associative pairs with 'nil denoting the empty list). If its argument is the empty list, then it returns the empty list; if it is a list whose head is a record with a size field (and possibly other fields matched by ". ."), then it captures the whole record in y, the content of the field in x, the tail of the list in tail, and keeps or discards y (ie, the record) according to whether x (ie, the field) is larger than 50; if the head is also a list, then it recursively applies both on the head and on the tail; if the head of the list is neither a list, nor a record with a size field, then the head is discarded. The encoding of the whole grouping query is given in Section 5.3.

Our aim is not to propose yet another "NoSQL/cloud computing/bigdata analytics" query language, but rather to show how to express and type such languages via an encoding into our core calculus. Each such language can in this way preserve its execution model but obtain for free a formal semantics, a type inference system and, as it happens, a prototype implementation. The type information is deduced via the encoding (without the need of any type annotation) and can be used for early error detection and debugging purposes. The encoding also yields an executable system that can be used for rapid prototyping. Both possibilities are critical in most typical usage scenarios of these languages, where deployment is very expensive both in time and in resources. As observed by Meijer [START_REF] Meijer | The world according to LINQ[END_REF] the advent of big data makes it more important than ever for programmers (and, we add, for language and system designers) to have a single abstraction that allows them to process, transform, query, analyze, and compute across data presenting utter variability both in volume and in structure, yielding a "mind-blowing number For the sake of precision, to comply with Jaql's semantics the last pattern should rather be ({..},tail) => Fil(tail): since field selection e.size fails whenever e is not a record or a list, this definition would detect the possibility of this failure by a static type error.

of new data models, query languages, and execution fabrics" [START_REF] Meijer | The world according to LINQ[END_REF] . The framework we present here, we claim, encompasses them all. A long-term goal is that the compilers of these languages could use the type information inferred from the encoding and the encoding itself to devise further optimizations.

Types. Pig [START_REF] Olston | Pig latin: a not-so-foreign language for data processing[END_REF], Jaql [START_REF] Jaql | [END_REF][START_REF] Özcan | Emerging trends in the enterprise data analytics: connecting Hadoop and DB2 warehouse[END_REF], AQL [START_REF] Behm | Asterix: towards a scalable, semistructured data platform for evolvingworld models[END_REF] have all been conceived by considering just the map-reduce execution model. The type (or, schema) of the manipulated data did not play any role in their design. As a consequence these languages are untyped and, when present, types are optional and clearly added as an afterthought. Differences in data model or type discipline are particularly important when embedded in a host language (since they yield the so-called impedance mismatch). The reason why types were/are disregarded in such languages may originate in an alleged tension between type inference and heterogeneous/semistructured data: on the one hand these languages are conceived to work with collections of data that are weakly or partially structured, on the other hand current languages with type inference (such as Haskell or ML) can work only on homogeneous collections (typically, lists of elements of the same type).

In this work we show that the two visions can coexist: we type data by semantic subtyping [START_REF] Frisch | Semantic subtyping: Dealing set-theoretically with function, union, intersection, and negation types[END_REF], a type system conceived for semistructured data, and describe computations by our filters which are untyped combinators that, thanks to a technique of weak typing introduced in [START_REF] Castagna | Typed iterators for XML[END_REF], can polymorphically type the results of data query and processing with a high degree of precision. The conception of filters is driven by the schema of the data rather than the execution model and we use them (i) to capture and give a uniform semantics to a wide range of semi structured data processing capabilities, (ii) to give a type system that encompasses the types defined for such languages, if any, notably Pig, Jaql and AQL (but also XML query and processing languages: see Section 5.3), (iii) to infer the precise result types of queries written in these languages as they are (so without the addition of any explicit type annotation/definition or new construct), and (iv) to show how minimal extensions/modifications of the current syntax of these languages can bring dramatic improvements in the precision of the inferred types.

The types we propose here are extensible record types and heterogeneous lists whose content is described by regular expressions on types as defined by the following grammar:

Types t ::= v (singleton) | { { {ℓ:t, . . . , ℓ:t} } } (closed record) | { { {ℓ:t, . . . , ℓ:t , .. .. ..} } } (open record) | [r] (sequences) | int | char (base) | any | empty | null (special) | t| | |t (union) | t\ \ \t (difference) Regexp r ::= ε | t | r* | r+ | r? | r r | r| | |r
where ε denotes the empty word. The semantics of types can be expressed in terms of sets of values (values are either constants -such as 1, 2, true, false, null, '1', the latter denoting the character 1-, records of values, or lists of values). So the singleton type v is the type that contains just the value v (in particular null is the singleton type containing the value null). These types can express all the types of Pig, Jaql and AQL, all XML types, and much more. So for instance, AQL includes only homogeneous lists of type t, that can be expressed by our types as [ t* ]. In Jaql's documentation one can find the type [ long(value=1), string(value="a"), boolean* ] which is the type of arrays whose first element is 1, the second is the string "a" and all the other are booleans. This can be easily expressed in our types as [1 "a" bool*]. But while Jaql only allows a limited use of regular expressions (Kleene star can only appear in tail position) our types do not have such restrictions. So for example [char* '@' char* '.' (('f' 'r')|('i' 't'))] is the type of all strings (ie, sequences of chars) that denote email addresses ending by either .fr or .it. We use some syntactic sugar to make terms as the previous one more readable (eg, [ .* '@' .* ('.fr'|'.it')]). Likewise, henceforth we use { { {a?:t} } } to denote that the field a of type t is optional; this is just syntactic sugar for stating that either the field is undefined or it contains a value of type t (for the formal definition see Appendix G).

Coming back to our initial example, the filter Fil defined before expects as argument a collection of the following type: type Depts = [ ( {size?: int, ..} | Depts )* ] that is a, possibly empty, arbitrary nested list of records with an optional size field of type int: notice that it is important to specify the optional field and its type since a size field of a different type would make the expression x > 50 raise a run-time error. This information is deduced just from the structure of the filter (since Fil does not contain any type definition or annotation).

We define a type inference system that rejects any argument of Fil that has not type Depts, and deduces for arguments of type [({size: int, addr: string}| {sec: int} | Depts)+] (which is a subtype of Depts) the result type [({size: int, addr: string}|Depts)*] (so it does not forget the field addr but discards the field sec, and by replacing * for + recognizes that the test may fail).

By encoding primitive Jaql operations into a formal core calculus we shall provide them a formal and clean semantics as well as precise typing. So for instance it will be clear that applying the following dot selection [ [{a:3}] {a:5, b:true} ].a the result will be [ [START_REF] Behm | Asterix: towards a scalable, semistructured data platform for evolvingworld models[END_REF] 5 ] and we shall be able to deduce that _.a applied to arbitrary nested lists of records with an optional integer a field (ie, of type t = { { {a?:int} } } | [ t * ] ) yields arbitrary nested lists of int or null values (ie, of type

u = int | null | [ u * ]).
Finally we shall show that if we accept to extend the current syntax of Jaql (or of some other language) by some minimal filter syntax (eg, the pattern filter) we can obtain a huge improvement in the precision of type inference.

Contributions.

The main contribution of this work is the definition of a calculus that encompasses structural operators scattered over NoSQL languages and that possesses some characteristics that make it unique in the swarm of current semi-structured data processing languages. In particular it is parametric (though fully embeddable) in a host language; it uniformly handles both width and deep nested data recursion (while most languages offer just the The only exception are the "bags" types we did not include in order to focus on essential features. former and limited forms of the latter); finally, it includes first-class arbitrary deep composition (while most languages offer this operator only at top level), whose power is nevertheless restrained by the type system.

An important contribution of this work is that it directly compares a programming language approach with the tree transducer one. Our calculus implements transformations typical of top-down tree transducers but has several advantages over the transducer approach: (1) the transformations are expressed in a formalism immediately intelligible to any functional programmer; (2) our calculus, in its untyped version, is Turing complete; (3) its transformations can be statically typed (at the expenses of Turing completeness) without any annotation yielding precise result types (4) even if we restrict the calculus only to well-typed terms (thus losing Turing completeness), it still is strictly more expressive than wellknown and widely studied deterministic top-down tree transducer formalisms.

The technical contributions are (i) the proof of Turing completeness for our formalism, (ii) the definition of a type system that copes with records with computable labels (iii) the definition of a static type system for filters and its correctness, (iv) the definition of a static analysis that ensures the termination (and the proof thereof) of the type inference algorithm with complexity bounds expressed in the size of types and filters and (iv) the proof that the terms that pass the static analysis form a language strictly more expressive than top-down tree transducers.

Outline. In Section 2 we present the syntax of the three components of our system. Namely, a minimal set of expressions, the calculus of filters used to program user-defined operators or to encode the operators of other languages, and the core types in which the types we just presented are to be encoded. Section 3 defines the operational semantics of filters and a declarative semantics for operators. The type system as well as the type inference algorithm are described in Section 4. In Section 5 we present how to handle a large subset of Jaql. Section 8 reports on some subtler design choices of our system. We compare related works in Section 9 and conclude in Section 10. In order to avoid blurring the presentation, proofs, secondary results, further encodings, and extensions are moved into a separate appendix.

Syntax

In this section we present the syntax of the three components of our system: a minimal set of expressions, the calculus of filters used to program user-defined operators or to encode the operators of other languages, and the core types in which the types presented in the introduction are to be encoded.

The core of our work is the definition of filters and types. The key property of our development is that filters can be grafted to any host language that satisfies minimal requirements, by simply adding filter application to the expressions of the host language. The minimal requirements of the host language for this to be possible are quite simple: it must have constants (typically for types int, char, string, and bool), variables, and either pairs or record values (not necessarily both). On the static side the host language must have at least basic and products types and be able to assign a type to expressions in a given type environment (ie, under some typing assumptions for variables). By the addition of filter applications, the host language can acquire or increase the capability to define polymorphic user-defined iterators, query and processing expressions, and be enriched with a powerful and precise type system.

Expressions

In this work we consider the following set of expressions Intuitively, these expressions represent the syntax supplied by the host language -though only the first two and one of the next two are really needed-that we extend with (the missing expressions and) the expression of filter application. Expressions are formed by constants, variables, pairs, records, and operation on records: record concatenation gives priority to the expression on the right. So if in r1 + r2 both records contains a field with the same label, it is the one in r2 that will be taken, while field deletion does not require the record to contain a field with the given label (though this point is not important). The metavariable op ranges over operators as well as functions and other constructions belonging to or defined by the host language. Among expressions we single out a set of values, intuitively the results of computations, that are formally defined as follows:

v ::= c | (v, v) | {ℓ:v; . . . ; ℓ:v}
We use "foo" for character string constants, 'c' for characters, 1 2 3 4 5 and so on for integers, and backquoted words, such as 'foo, for atoms (ie, user-defined constants). We use three distinguished atoms 'nil, 'true, and 'false. Double quotes can be omitted for strings that are labels of record fields: thus we write {name:"John"} rather than {"name":"John"}. Sequences (aka, heterogeneous lists, ordered collections, arrays) are encoded à la LISP, as nested pairs where the atom 'nil denotes the empty list. We use [e1 . . . en] as syntactic sugar for (e1, . . . , (en, 'nil)...).

Types

Expressions, in particular filter applications, are typed by the following set of types (typically only basic, product, recursive and -some form of-record types will be provided by the host language): where every recursion is guarded, that is, every type variable is separated from its binder by at least one application of a type constructor (ie, products, records, or Op).

Most of these types were already explained in the introduction. We have basic types (int, bool, ....) ranged over by b and singleton types v denoting the type that contains only the value v.

Record types come in two flavors: closed record types whose values are records with exactly the fields specified by the type, and open record types whose values are records with at least the fields specified by the type. Product types are standard and we have a complete set of type connectives, that is, finite unions, intersections and negations. We use empty, to denote the type that has no values and any for the type of all values (sometimes denoted by "_" when used in patterns). We added a term for recursive types, which allows us to encode both the regular expression types defined in the introduction and, more generally, the recursive type definitions we used there. Finally, we use Op (capitalized to distinguish it from expression operators) to denote the host language's type operators (if any). Thus, when filter applications return values whose type belongs just to the foreign language (eg, a list of functions) we suppose the typing of these functions be given by some type operators. For instance, if succ is a user defined successor function, we will suppose to be given its type in the form Arrow(int,int) and, similarly, for its application, say apply(succ,3) we will be given the type of this expression (presumably int). Here Arrow is a type operator and apply an expression operator.

The denotational semantics of types as sets of values, that we informally described in the introduction, is at the basis of the definition of the subtyping relation for these types. We say that a type t1 is a subtype of a type t2, noted t1 ≤ t2, if and only if the set of values denoted by t1 is contained (in the set-theoretic sense) in the set of values denoted by t2. For the formal definition and the decision procedure of this subtyping relation the reader can refer to the work on semantic subtyping [START_REF] Frisch | Semantic subtyping: Dealing set-theoretically with function, union, intersection, and negation types[END_REF].

Patterns

Filters are our core untyped operators. All they can do are three different things: (1) they can structurally decompose and transform the values they are applied to, or (2) they can be sequentially composed, or (3) they can do pattern matching. In order to define filters, thus, we first need to define patterns. Patterns are essentially types in which capture variables (ranged over by x, y, . . . ) may occur in every position that is not under a negation or a recursion. A pattern is used to match a value. The matching of a value v against a pattern p, noted v/p, either fails (noted Ω) or it returns a substitution from the variables occurring in the pattern, into values. The substitution is then used as an environment in which some expression is evaluated. If the pattern is a type, then the matching fails if and only if the pattern is matched against a value that does not have that type, otherwise it returns the empty substitution. If it is a variable, then the matching always succeeds and returns the substitution that assigns the matched value to the variable. The pair pattern ( ( (p1, , ,p2) ) ) succeeds if and only if it is matched against a pair of values and each sub-pattern succeeds on the corresponding projection of the value (the union of the two substitutions is then returned). Both record patterns are similar to the product pattern with the specificity that in the open record pattern ".." matches all the fields that are not specified in the pattern. An intersection pattern p1& & &p2 succeeds if and only if both patterns succeed (the union of the two substitutions is then returned). The union pattern p1| | |p2 first tries to match the pattern p1 and if it fails it tries the pattern p2.

For instance, the pattern ( ( (int& & &x, , ,y) ) ) succeeds only if the matched value is a pair of values (v1, v2) in which v1 is an integer -in which case it returns the substitution {x/v1, y/v2}and fails otherwise. Finally notice that the notation "p as x" we used in the examples of the introduction, is syntactic sugar for p& & &x.

This informal semantics of matching (see [START_REF] Frisch | Semantic subtyping: Dealing set-theoretically with function, union, intersection, and negation types[END_REF] for the formal definition) explains the reasons of the restrictions on capture variables in Definition 3: in intersections, pairs, and records all patterns must be matched and, thus, they have to assign distinct variables, while in union patterns just one pattern will be matched, hence the same set of variables must be assigned, whichever alternative is selected.

The strength of patterns is their connections with types and the fact that the pattern matching operator can be typed exactly. This is entailed by the following theorems (both proved in [START_REF] Frisch | Semantic subtyping: Dealing set-theoretically with function, union, intersection, and negation types[END_REF]):

Theorem 4 (Accepted type [START_REF] Frisch | Semantic subtyping: Dealing set-theoretically with function, union, intersection, and negation types[END_REF]). For every pattern p, the set of all values v such that v/p = Ω is a type. We call this set the accepted type of p and note it by p .

The fact that the exact set of values for which a matching succeeds is a type is not obvious. It states that for every pattern p there exists a syntactic type produced by the grammar in Definition 2 whose semantics is exactly the set of all and only values that are matched by p. The existence of this syntactic type, which we note p , is of utmost importance for a precise typing of pattern matching. In particular, given a pattern p and a type t contained in (ie, subtype of) p , it allows us to compute the exact type of the capture variables of p when it is matched against a value in t:

Theorem 5 (Type environment [START_REF] Frisch | Semantic subtyping: Dealing set-theoretically with function, union, intersection, and negation types[END_REF]). There exists an algorithm that for every pattern p, and t ≤ p returns a type environment

t/p ∈ Vars(p) → Types such that (t/p)(x) = {(v/p)(x) | v : t}.

Filters Definition 6 (filters).

A filter is a term generated by:

Filters f ::= e (expression) | p ⇒ ⇒ ⇒ f (pattern) | ( ( (f ,f) ) ) (product) | { { {ℓ:f, . . . , ℓ:f , ..} } } (record) | f| | |f (union) | µ µ µX. . .f (recursion) | Xa (recursive call) | f ;f (composition) | o (declarative operators) Operators o ::= groupby f (filter grouping) | orderby f (filter ordering) Arguments a ::= x (variables) | c (constants) | ( ( (a,a) ) ) (pairs) | { { {ℓ:a, ..., ℓ:a} } } (record)
such that for every subterm of the form f ;g, no recursion variable is free inf .

Filters are like transducers, that when applied to a value return another value. However, unlike transducers they possess more "programming-oriented" constructs, like the ability to test an input and capture subterms, recompose an intermediary result from captured values and a composition operator. We first describe informally the semantics of each construct.

The expression filter e always returns the value corresponding to the evaluation of e (and discards its argument). The filter p ⇒ ⇒ ⇒ f applies the filter f to its argument in the environment obtained by matching the argument against p (provided that the matching does not fail). This rather powerful feature allows a filter to perform two critical actions: (i) inspect an input with regular pattern-matching before exploring it and (ii) capture part of the input that can be reused during the evaluation of the subfilter f . If the argument application of fi to vi returns v ′ i then the application of the product filter ( ( (f1,f2) ) ) to an argument (v1, v2) returns (v ′ 1 , v ′ 2 ); otherwise, if any application fails or if the argument is not a pair, it fails. The record filter is similar: it applies to each specified field the corresponding filter and, as stressed by the ". .", leaves the other fields unchanged; it fails if any of the applications does, or if any of the specified fields is absent, or if the argument is not a record. The filter f1| | |f2 returns the application of f1 to its argument or, if this fails, the application of f2. The semantics of a recursive filter is given by standard unfolding of its definition in recursive calls. The only real restriction that we introduce for filters is that recursive calls can be done only on arguments of a given form (ie, on arguments that have the form of values where variables may occur). This restriction in practice amounts to forbid recursive calls on the result of another recursively defined filter (all other cases can be easily encoded). The reason of this restriction is technical, since it greatly simplifies the analysis of Section 4.5 (which ensures the termination of type inference) without hampering expressiveness: filters are Turing complete even with this restriction (see Theorem 7). Filters can be composed: the filter f1;f2 applies f2 to the result of applying f1 to the argument and fails if any of the two does. The condition that in every subterm of the form f ;g, f does not contain free recursion variables is not strictly necessary. Indeed, we could allow such terms. The point is that the analysis for the termination of the typing would then reject all such terms (apart from trivial ones in which the result of the recursive call is not used in the composition). But since this restriction does not restrict the expressiveness of the calculus (Theorem 7 proves Turing completeness with this restriction), then the addition of this restriction is just a design (rather than a technical) choice: we prefer to forbid the programmer to write recursive calls on the left-hand side of a composition, than systematically reject all the programs that use them in a non-trivial way.

Finally, we singled out some specific filters (specifically, we chose groupby and orderby ) whose semantics is generally specified in a declarative rather than operational way. These do not bring any expressive power to the calculus (the proof of Turing completeness, Theorem 7, does not use these declarative operators) and actually they can be encoded by the remaining filters, but it is interesting to single them out because they yield either simpler encodings or more precise typing.

Semantics

The operational semantics of our calculus is given by the reduction semantics for filter application and for the record operations. Since the former is the only novelty of our work, we save space and omit the latter, which are standard anyhow.

Big step semantics

We define a big step operational semantics for filters. The definition is given by the inference rules in Figure 1 for judgements of the form δ;γ ⊢eval f (a) r and describes how the evaluation of the application of filter f to an argument a in an environment γ yields an object r where r is either a value or Ω. The latter is a special value which represents a runtime error: it is raised by the rule (error) either because a filter did not match the form of its argument (eg, the argument of a filter product was not a pair)

(expr) δ;γ ⊢eval e(v) r r = eval(γ, e) (prod) δ;γ ⊢eval f 1 (v 1 ) r 1 δ;γ ⊢eval f 2 (v 2 ) r 2 δ;γ ⊢eval ( ( (f 1 ,f 2 ) ) )(v 1 , v 2 ) (r 1 , r 2 ) if r 1 = Ω and r 2 = Ω (patt) δ;γ , v/p ⊢eval f (v) r δ;γ ⊢eval (p ⇒ ⇒ ⇒ f )(v) r if v/p = Ω (comp) δ;γ ⊢eval f 1 (v) r 1 δ;γ ⊢eval f 2 (r 1 ) r 2 δ;γ ⊢eval (f 1 ;f 2 )(v) r 2 if r 1 = Ω (union1) δ;γ ⊢eval f 1 (v) r 1 δ;γ ⊢eval (f 1 | | |f 2 )(v) r 1 if r 1 = Ω (union2) δ;γ ⊢eval f 1 (v) Ω δ;γ ⊢eval f 2 (v) r 2 δ;γ ⊢eval (f 1 | | |f 2 )(v) r 2 (rec) δ, (X → f );γ ⊢eval f (v) r δ;γ ⊢eval (µ µ µX. . .f )(v) r (rec-call) δ;γ ⊢eval (δ(X))(a) r δ;γ ⊢eval (Xa)(v) r (error) δ;γ ⊢eval f (a) Ω if no other rule applies (recd) δ;γ ⊢eval f 1 (v 1 ) r 1 • • • δ;γ ⊢eval fn(vn) rn δ;γ ⊢eval { { {ℓ 1 :f 1 , ..., ℓn:fn , ..} } }({ { {ℓ 1 :v 1 , ..., ℓn:vn, ..., ℓ n+k :v n+k } } }) { { {ℓ 1 :r 1 , ..., ℓn:rn, ..., ℓ n+k :v n+k } } } if ∀i, r i = Ω Figure 1. Dynamic semantics of filters
or because some pattern matching failed (ie, the side condition of (patt) did not hold). Notice that the argument a of a filter is always a value v unless the filter is the unfolding of a recursive call, in which case variables may occurr in it (cf. rule rec-call).

Environment δ is used to store the body of recursive definitions.

The semantics of filters is quite straightforward and inspired by the semantics of patterns. The expression filter discards its input and evaluates (rather, asks the host language to evaluate) the expression e in the current environment (expr). It can be thought of as the right-hand side of a branch in a match_with construct.

The product filter expects a pair as input, applies its sub-filters component-wise and returns the pair of the results (prod). This filter is used in particular to express sequence mapping, as the first component f1 transforms the element of the list and f2 is applied to the tail. In practice it is often the case that f2 is a recursive call that iterates on arbitrary lists and stops when the input is 'nil. If the input is not a pair, then the filter fails (rule (error) applies).

The record filter expects as input a record value with at least the same fields as those specified by the filter. It applies each sub-filter to the value in the corresponding field leaving the contents of other fields unchanged (recd). If the argument is not a record value or it does not contain all the fields specified by the record filter, or if the application of any subfilter fails, then the whole application of the record filter fails.

The pattern filter matches its input value v against the pattern p. If the matching fails so the filter does, otherwise it evaluates its subfilter in the environment augmented by the substitution v/p (patt).

The alternative filter follows a standard first-match policy: If the filter f1 succeeds, then its result is returned (union-1). If f1 fails, then f2 is evaluated against the input value (union-2). This filter is particularly useful to write the alternative of two (or more) pattern filters, making it possible to conditionally continue a computation based on the shape of the input.

The composition allows us to pass the result of f1 as input to f2. The composition filter is of paramount importance. Indeed, without it, our only way to iterate (deconstruct) an input value is to use a product filter, which always rebuilds a pair as result.

Finally, a recursive filter is evaluated by recording its body in δ and evaluating it (rec), while for a recursive call we replace the recursion variable by its definition (rec-call).

This concludes the presentation of the semantics of nondeclarative filters (ie, without groupby and orderby). These form a Turing complete formalism (full proof in Appendix B):

Theorem 7 (Turing completeness). The language formed by constants, variables, pairs, equality, and applications of nondeclarative filters is Turing complete. Proof (sketch). We can encode untyped call-by-value λ-calculus by first applying continuation passing style (CPS) transformations and encoding CPS term reduction rules and substitutions via filters. Thanks to CPS we eschew the restrictions on composition.

Semantics of declarative filters

To conclude the presentation of the semantics we have to define the semantics of groupby and orderby. We prefer to give the semantics in a declarative form rather than operationally in order not to tie it to a particular order (of keys or of the execution):

Groupby: groupby f applied to a sequence [v1 . . . vm] reduces to a sequence [ (k1, l1) . . . (kn, ln) ] such that: 1. ∀i, 1 ≤ i ≤ m, ∃j, 1 ≤ j ≤ n, s.t. kj = f (vi) 2. ∀j, 1 ≤ j ≤ n, ∃i, 1 ≤ i ≤ m, s.t. kj = f (vi) 3. ∀j, 1 ≤ j ≤ n, lj is a sequence: [ v j 1 . . . v j n j ] 4. ∀j, 1 ≤ j ≤ n, ∀k, 1 ≤ k ≤ nj , f (v j k ) = kj 5. ki = kj ⇒ i = j 6. l1, . . . , ln is a partition of [v1 . . . vm ] Orderby: orderby f applied to [v1 . . . vn] reduces to [v ′ 1 . . . v ′ n ] such that: 1. [v ′ 1 . . . v ′ n ] is a permutation of [v1 . . . vn], 2. ∀i, j s.t. 1 ≤ i ≤ j ≤ n, f (vi) ≤ f (vj )
Since the semantics of both operators is deeply connected to a notion of equality and order on values of the host language, we give them as "built-in" operations. However we will illustrate how our type algebra allows us to provide very precise typing rules, specialized for their particular semantics. It is also possible to encode co-grouping (or groupby on several input sequences) with a combination of groupby and filters (cf. Appendix H).

Syntactic sugar

Now that we have formally defined the semantics of filters we can use them to introduce some syntactic sugar.

Expressions. The reader may have noticed that the productions for expressions (Definition 1) do not define any destructor (eg, projections, label selection, . . . ), just constructors. The reason is that destructors, as well as other common expressions, can be encoded by filter applications: These are just a possible choice, but others are possible. For instance in Jaql dot selection is overloaded: when _.ℓ is applied to a record, Jaql returns the content of its ℓ field; if the field is absent or the argument is null, then Jaql returns null and fails if the argument is not a record; when applied to a list ('array' in Jaql terminology) it recursively applies to all the elements of the list. So Jaql's "_.ℓ" is precisely defined as

µ µ µX. . .({ { {ℓ:x , .. .. ..} } } ⇒ ⇒ ⇒ x | | | ({ { {..} } }| | |null) ⇒ ⇒ ⇒ null | | | ( ( (h, , ,t) ) ) ⇒ ⇒ ⇒ ( ( (Xh,Xt ) ) ))
Besides the syntactic sugar above, in the next section we will use t1 + t2 to denote the record type formed by all field types in t2 and all the field types in t1 whose label is not already present in t2.

Similarly t \ ℓ will denote the record types formed by all field types in t apart from the one labelled by ℓ, if present. Finally, we will also use for expressions, types, and patterns the syntactic sugar for lists used in the introduction. So, for instance, [p1 p2 ... pn] is matched by lists of n elements provided that their i-th element matches pi.

Type inference

In this section we describe a type inference algorithm for our expressions.

Typing of simple and foreign expressions

Variables, constants, and pairs are straightforwardly typed by

[VARS] Γ ⊢ x : Γ(x) [CONSTANT] Γ ⊢ c : c [PROD] Γ ⊢ e1 : t1 Γ ⊢ e2 : t2 Γ ⊢ (e1, e2) : ( ( (t1, , ,t2) ) )
where Γ denotes a typing environment that is a function from expression variables to types and c denotes both a constant and the singleton type containing the constant. Expressions of the host language are typed by the type function which given a type environment and a foreign expression returns the type of the expression, and that we suppose to be given for each host language.

[FOREIGN]

Γ ⊢ e1 : t1 • • • Γ ⊢ en : tn Γ ⊢ op(e1,..., en) : type((Γ, x1:t1, ..., xn:tn), op(x1,..., xn))

Since the various ei can contain filter applications, thus unknown to the host language's type system, the rule [FOREIGN] swaps them with variables having the same type.

Notice that our expressions, whereas they include filter applications, do not include applications of expressions to expressions. Therefore if the host language provides function definitions, then the applications of the host language must be dealt as foreign expressions, as well (cf. the expression operator apply in Section 2.2).

Typing of records

The typing of records is novel and challenging because record expressions may contain string expressions in label position, such as in { { {e1:e2} } }, while in all type systems for record we are aware of, labels are never computed. It is difficult to give a type to { { {e1:e2} } } since, in general, we do not statically know the value that e1 will return, and which is required to form a record type. All we can (and must) ask is that this value will be a string. To type a record expression { { {e1:e2} } }, thus, we distinguish two cases according to

Γ ⊢ e1 + e2 : t1 + t2 [RCD-DEL] Γ ⊢ e : t t ≤ { { {..} } } Γ ⊢ e \ ℓ : t \ ℓ
Records with multiple fields are handled by the rule [RCD-MUL] which "merges" the result of typing single fields by using the type operator + as defined in CDuce [START_REF] Benzaken | CDuce: an XML-friendly general purpose language[END_REF][START_REF] Frisch | Théorie, conception et réalisation d'un langage de programmation fonctionnel adapté à XML[END_REF], which is a right-priority record concatenation defined to take into account undefined and unknown fields: See Appendix G for formal definitions of all these type operators.

Notice that these rules do not ensure that a record will not have two fields with the same label, which is a run-time error. Detecting such an error needs sophisticated type systems (eg, dependent types) beyond the scope of this work. This is why in the rule [RCD-MUL] we used type operator "+" which, in case of multiple occurring labels, since records are unordered, corresponds to randomly choosing one of the types bound to these labels: if such a field is selected, it would yield a run-time error, so its typing can be ambiguous. We can fine tune the rule [RCD-MUL] so that when all the ti are finite unions of record types, then we require to have pairwise disjoint sets of labels; but since the problem would still persist for infinite types we prefer to retain the current, simpler formulation. relies on an auxiliary deduction system for judgments of the form Γ ;∆ ;M ⊢fil f (t) : s that states that if in the environments Γ, ∆, M (explained later on) we apply the filter f to a value of type t, then it will return a result of type s.

To define this auxiliary deduction system, which is the core of our type analysis, we first need to define f , the type accepted by a filter f . Intuitively, this type gives a necessary condition on the input for the filter not to fail: Definition 8 (Accepted type). Given a filter f , the accepted type of f , written f is the set of values defined by:

e = any p ⇒ ⇒ ⇒ f = p & & & f f1| | |f2 = f1 | | | f2 ( ( (f1,f2) ) ) = ( ( ( f1 , , , f2 ) ) ) f1;f2 = f1 Xa = any µ µ µX. . .f = f groupby f = [any*] orderby f = [any*] { { {ℓ1:f1,.., ℓn:fn , ..} } } = { { {ℓ1: f1 ,.., ℓn: f2 , .. .. ..} } }
It is easy to show that an argument included in the accepted type is a necessary (but not sufficient, because of the cases for composition and recursion) condition for the evaluation of a filter not to fail: Lemma 9. Let f be a filter and v be a value such that v / ∈ f . For every γ, δ, if δ;γ ⊢eval f (v) r, then r ≡ Ω.

The proof is a straightforward induction on the structure of the derivation, and is detailed in Appendix C. The last two auxiliary definitions we need are related to product and record types. In the presence of unions, the most general form for a product type is a finite union of products (since intersections distribute on products). ) ) is less precise, since it also allows pairs whose first projection is an int and second projection is a string and vice versa. We see that it is necessary to manipulate finite unions of products (and similarly for records), and therefore, we introduce the following notations:

Lemma 10 (Product decomposition). Let t ∈ Types such that t ≤ ( ( (any, , ,any) ) ). A product decomposition of t, denoted by π π π(t) is a set of types: π π π(t) = {( ( (t 1 1 , , ,t 1 2 ) ) ), . . . , ( ( (t n 1 , , ,t n 2 ) ) )} such that t = t i ∈π π π(t) ti. For a given product decomposition, we say that n is the rank of t, noted rank(t), and use the notation π π π j i (t) for the type t j i . There exist several suitable decompositions whose details are out of the scope of this paper. We refer the interested reader to [START_REF] Frisch | Théorie, conception et réalisation d'un langage de programmation fonctionnel adapté à XML[END_REF] and [START_REF] Nguy Ễn | Language of Combinators for XML: Conception, Typing, Implementation[END_REF] for practical algorithms that compute such decompositions for any subtype of ( ( (any, , ,any) ) ) or of { { {.. .. ..} } }. These notions of decomposition, rank and projection can be generalized to records: Lemma 11 (Record decomposition). Let t ∈ Types such that t ≤ { { {..} } }. A record decomposition of t, denoted by ρ ρ ρ(t) is a finite set of types ρ ρ ρ(t)={r1, . . . , rn} where each ri is either of the form

{ { {ℓ i 1 :t i 1 , . . . , ℓ i n i :t i n i } } } or of the form { { {ℓ i 1 :t i 1 , . . . , ℓ i n i :t i n i , .. .. ..} } }
and such that t = r i ∈ρ ρ ρ(t) ri. For a given record decomposition, we say that n is the rank of t, noted rank(t), and use the notation ρ ρ ρ j ℓ (t) for the type of label ℓ in the j th component of ρ ρ ρ(t).

In our calculus we have three different sets of variables. The set Vars of term variables, ranged over by x, y, ..., introduced in patterns and used in expressions and in arguments of calls of recursive filters. The set RVars of term recursion variables, ranged over by X, Y, ... and that are used to define recursive filters. The set TVars of type recursion variables, ranged over by T, U, ... used to define recursive types. In order to use them we need to define three different environments: Γ : Vars → Types denoting type environments that associate term variables with their types; ∆ : RVars → Filters denoting definition environments that associate each filter recursion variable with the body of its definition; M : RVars × Types → TVars denoting memoization environments which record that the call of a given recursive filter on a given type yielded the introduction of a fresh recursion type variable. Our typing rules, thus work on judgments of the form Γ ;∆ ;M ⊢ f (t) : t ′ stating that applying f to an expression of type t in the environments Γ, ∆, M yields a result of type t ′ . This judgment can be derived with the set of rules given in Figure 2.

These rules are straightforward, when put side by side with the dynamic semantics of filters, given in Section 3. It is clear that this type system simulates at the level of types the computations that are carried out by filters on values at runtime. For instance, rule [FIL-EXPR] calls the typing function of the host language to determine the type of an expression e. Rule [FIL-PROD] applies a product filter recursively on the first and second projection for each member of the product decomposition of the input type and returns the union of all result types. Rule [FIL-REC] for records is similar, recursively applying sub-filters label-wise for each member of the record decomposition and returning the union of the resulting record types. As for the pattern filter (rule [FIL-PAT]), its subfilter f is typed in the environment augmented by the mapping t/p of the input type against the pattern (cf. Theorem 5). The typing rule for the union filter, [FIL-UNION] reflects the first match policy: when typing the second branch, we know that the first was not taken, hence that at runtime the filtered value will have a type that is in t but not in f1 . Notice that this is not ensured by the definition of accepted typewhich is a rough approximation that discards grosser errors but, as we stressed right after its definition, is not sufficient to ensure that evaluation of f1 will not fail-but by the type system itself: the premises check that f1(t1) is well-typed which, by induction, implies that f1 will never fail on values of type t1 and, ergo, that these values will never reach f2. Also, we discard from the output type the contribution of the branches that cannot be taken, that is, branches whose accepted type have an empty intersection with the input type t. Composition (rule [FIL-COMP]) is straightforward. In this rule, the restriction that f1 is a filter with no open recursion variable ensures that its output type s is also a type without free recursion variables and, therefore, that we can use it as input type for f2. The next three rules work together. The first, [FIL-FIX] introduces for a recursive filter a fresh recursion variable for its output type. It also memoize in ∆ that the recursive filter X is associated with a body f and in M that for an input filter X and an input type t, the output type is the newly introduced recursive type variable. When dealing with a recursive call X two situations may arise. One possibility is that it is the first time the filter X is applied to the input type t. We therefore introduce a fresh type variable T and recurse, replacing X by its definition f . Otherwise, if the input type has already been encountered while typing the filter variable X, we can return its memoized type, a type variable T . Finally, Rule [FIL-ORDBY] and Rule [FIL-GRPBY] handle the special cases of groupby and orderby filters. Their typing is explained in the following section.

Typing of orderby and groupby

While the "structural" filters enjoy simple, compositional typing rules, the ad-hoc operations orderby and groupby need specially crafted rules. Indeed it is well known that when transformation languages have the ability to compare data values type-checking (and also type inference) becomes undecidable (eg, see [START_REF] Alon | XML with data values: typechecking revisited[END_REF][START_REF] Alon | Typechecking XML views of relational databases[END_REF]). We therefore provide two typing approximations that yield a good The item set of t denoted by item(t) is defined by:

i m , .. .. ..} } } [FIL-UNION] i = 1, 2 Γ ;∆ ;M ⊢fil f i (t i ) : s i t ≤ f1 | | | f2 t1 = t& & & f1 t2 = t& & &¬ f1 Γ ;∆ ;M ⊢fil f 1 | | |f 2 (t) : {i|s i =empty} s i [FIL-COMP] Γ ;∆ ;M ⊢fil f 1 (t) : s Γ ;∆ ;M ⊢fil f 2 (s) : s ′ Γ ;∆ ;M ⊢fil f 1 ;f 2 (t) : s ′ [FIL-FIX] Γ ;∆, (X → f ) ;M, ((X, t) → T ) ⊢fil f (t) : s T fresh Γ ;∆ ;M ⊢fil (µ µ µX. . .f )(t) : µ µ µT . . .s [FIL-CALL-NEW] Γ ;∆ ;M, ((X, t) → T ) ⊢fil ∆(X)(t) : t ′ t = type(Γ, a) (X, t) ∈ dom(M) T fresh Γ ;∆ ;M ⊢fil (Xa)(s) : µ µ µT . . .t ′ [FIL-CALL-MEM] t = type(Γ, a) (X, t) ∈ dom(M) Γ ;∆ ;M ⊢fil (Xa)(s) : M (X, t) [FIL-ORDBY] ∀t i ∈ item(t) Γ ;∆ ;M ⊢fil f (t i ) : s i t ≤ [any*] i si is ordered Γ ;∆ ;M ⊢fil (orderby f )(t) : OrderBy(t) [FIL-GRPBY] ∀t i ∈ item(t) Γ ;∆ ;M ⊢fil f (t i ) : s i t ≤ [any*] Γ ;∆ ;M ⊢fil (groupby f )(t) : [( ( (( i s i ),OrderBy(t)) ) )*]
item(empty) = ∅ item(t) = item(t& & &( ( (any,any) ) )) if t ≤ ( ( (any,any) ) ) item( 1≤i≤rank(t)
( ( (t 1 i , , ,t 2 i ) ) )) = 1≤i≤rank(t) ({t 1 i } ∪ item(t 2 i ))
The first and second line in the definition ensure that item() returns the empty set for sequence types that are not products, namely for the empty sequence. The third line handles the case of non-empty sequence type. In this case t is a finite union of products, whose first components are the types of the "head" of the sequence and second components are recursively the types of the tails. Note also that this definition is well-founded. Since types are regular trees the number of distinct types accumulated by item() is finite. We can now defined typing rules for the orderby and groupby operators.

orderby f : The orderby filter uses its argument filter f to compute a key from each element of the input sequence and then returns the same sequence of elements, sorted with respect to their key. Therefore, while the types of the elements in the result are still known, their order is lost. We use item() to compute the output type of an orderby application:

OrderBy(t) = [( t i ∈item(t) ti) * ]
groupby f : The typing of orderby can be used to give a rough approximation of the typing of groupby as stated by rule [FIL-GRPBY]. In words, we obtain a list of pairs where the key component is the result type of f applied to the items of the sequence, and use OrderBy to shuffle the order of the list. A far more precise typing of groupby that keeps track of the relation between list elements and their images via f is given in Appendix E.

Soundness, termination, and complexity

The soundness of the type inference system is given by the property of subject reduction for filter application Theorem 13 (subject reduction). If ∅ ;∅ ;∅ ⊢fil f (t) : s, then for all v : t, ∅;∅ ⊢eval f (v) r implies r : s.

whose full proof is given in Appendix C. It is easy to write a filter for which the type inference algorithm, that is the deduction of ⊢fil, does not terminate: µ µ µX. . .x ⇒ ⇒ ⇒ X( ( (x,x) ) ). The deduction of Γ ;∆ ;M ⊢fil f (t) : s simulates an (abstract) execution of the filter f on the type t. Since filters are Turing complete, then in general it is not possible to decide whether the deduction of ⊢fil for a given filter f will terminate for every input type t. For this reason we define a static analysis Check(f ) for filters that ensures that if f passes the analysis, then for every input type t the deduction of Γ ;∆ ;M ⊢fil f (t) : s terminates. For space reasons the formal definition of Check(f ) is relegated to Appendix A, but its behavior can be easily explained. Imagine that a recursive filter f is applied to some input type t. The algorithm tracks all the recursive calls occurring in f ; next it performs one step of reduction of each recursive call by unfolding the body; finally it checks in this unfolding that if a variable occurs in the argument of a recursive call, then it is bound to a type that is a subtree of the original type t. In other words, the analysis verifies that in the execution of the derivation for f (t) every call to s/p for some type s and pattern p always yields a type environment where variables used in recursive calls are bound to subtrees of t. This implies that the rule [FIL-CALL-NEW] will always memoize for a given X, types that are obtained from the arguments of the recursive calls of X by replacing their variables with a subtree of the original type t memoized by the rule [FIL-FIX]. Since t is regular, then it has finitely many distinct subtrees, thus [FIL-CALL-NEW] can memoize only finitely many distinct types, and therefore the algorithm terminates. More precisely, the analysis proceeds in two passes. In the first pass the algorithm tracks all recursive filters and for each of them it (i) marks the variables that occur in the arguments of its recursive calls, (ii) assigns to each variable an abstract identifier representing the subtree of the input type to which the variable will be bound at the initial call of the filter, and (iii) it returns the set of all types obtained by replacing variables by the associated abstract identifier in each argument of a recursive call. The last set intuitively represents all the possible ways in which recursive calls can shuffle and recompose the subtrees forming the initial input type. The second phase of the analysis first abstractly reduces by one step each recursive filter by applying it on the set of types collected in the first phase of the analysis and then checks whether, after this reduction, all the variables marked in the first phase (ie, those that occur in arguments of recursive calls) are still bound to subtrees of the initial input type: if this checks fails, then the filter is rejected. It is not difficult to see that the type inference algorithm converges if and only if for every input type there exists a integer n such that after n recursive calls the marked variables are bound only to subtrees of the initial input type (or to something that does not depend on it, of course). Since deciding whether such an n exists is not possible, our analysis checks whether for all possible input types a filter satisfies it for n=1, that is to say, that at every recursive call its marked variables satisfy the property; otherwise it rejects the filter.

Theorem 14 (Termination). If Check(f ), then for every type t the deduction of Γ ;∅ ;∅ ⊢fil f (t) : s is in 2-EXPTIME. Furthermore, if t is given as a non-deterministic tree automaton (NTA) then Γ ;∅ ;∅ ⊢fil f (t) : s is in EXPTIME, where the size of the problem is |f | × |t|.

(for proofs see Appendix A for termination and Appendix D for complexity). This complexity result is in line with those of similar formalisms. For instance in [START_REF] Martens | Typechecking top-down uniform unranked tree transducers[END_REF], it is shown that type-checking non deterministic top-down tree transducers is in EXPTIME when the input and output types are given by a NTA.

All filters defined in this paper (excepted those in Appendix B) pass the analysis. As an example consider the filter rotate that applied to a list returns the same list with the first element moved to the last position (and the empty list if applied to the empty list): µ µ µX. . . ( ( ( (x,( ( (y,z

) ) )) ) ) ⇒ ⇒ ⇒ ( ( (y,X( ( (x,z) ) )) ) ) | | | w ⇒ ⇒ ⇒ w )
The analysis succeeds on this filter. If we denote by ιx the abstract subtree bound to the variable x, then the recursive call will be executed on the abstract argument ( ( (ιx,ιz) ) ). So in the unfolding of the recursive call x is bound to ιx, whereas y and z are bound to two distinct subtrees of ιz. The variables in the recursive call, x and z, are thus bound to subtrees of the original tree (even though the argument of the recursive call is not a subtree of the original tree), therefore the filter is accepted . In order to appreciate the precision of the inference algorithm consider the type [int+ bool+], that is, the type of lists formed by some integers (at least one) followed by some booleans (at least one). For the application of rotate to an argument of this type our algorithm statically infers the most precise type, that is, Generic filters are Turing complete. However, requiring that Check() holds -meaning that the filter is typeable by our systemrestricts the expressive power of our filters by preventing them from recomposing a new value before doing a recursive call. For instance, it is not possible to typecheck a filter which reverses the elements of a sequence. Determining the exact class of transformations that typeable filters can express is challenging. However it is possible to show (cf. Appendix F) that typeable filters are strictly more expressive than top-down tree transducers with regular lookahead, a formalism for tree transformations introduced in [START_REF] Engelfriet | Top-down tree transducers with regular look-ahead[END_REF]. The intuition about this result can be conveyed by and example. Consider the tree: a(u1(. . . (un()))v1(. . . (vm()))) that is, a tree whose root is labeled a with two children, each being a monadic tree of height n and m, respectively. Then it is not possible to write a top-down tree transducer with regular look-ahead that creates the tree a(u1(. . . (un(v1(. . . vm()))))) which is just the concatenation of the two children of the root, seen as sequences, a transformation that can be easily programmed by typeable filters. The key difference in expressive power comes from the fact that filters are evaluated with an environment that binds capture variables to sub-trees of the input. This feature is essential to encode sequence concatenation and sequence flattening -two pervasive operations when dealing with sequences-that cannot be expressed by top-down tree transducers with regular look-ahead.

Jaql

In this Section, we show how filters can be used to capture some popular languages for processing data on the Cloud. We consider Jaql [START_REF] Jaql | [END_REF], a query language for JSON developed by IBM. We give translation rules from a subset of Jaql into filters.

Definition 15 (Jaql expressions). We use the following simplified grammar for Jaql (where we distinguish simple expressions, ranged over by e, from "core expressions" ranged over by k). (expand) | group ((each x)? by x = e (as x)?)? into e (grouping)

Built-in filters

In order to ease the presentation we extend our syntax by adding "filter definitions" (already informally used in the introduction) to filters and "filter calls" to expressions: e ::= let filter F [F1, . . . , Fn] = f in e (filter defn.)

f ::= F [f, . . . , f ] (call)
where F ranges over filter names. The mapping for most of the language we consider rely on the following built-in filters. (( ( (x,,,xs (( ( (x,,,xs) ) ), , ,tl) ) ) ⇒ ⇒ ⇒ ( ( (x,X(xs, tl)) ) )

) ) ), , ,tl) ) ) ⇒ ⇒ ⇒ ( ( (X(x, xs),X(tl)) ) ) | | | ( ( (x, , ,tl) ) ) ⇒ ⇒ ⇒ ( ( (F x, X(tl)) ) ) let filter Expand = µ µ µX. . . 'nil ⇒ ⇒ ⇒ 'nil | | | ( ( ('nil, , ,tl) ) ) ⇒ ⇒ ⇒ X(tl) | | | ( (

Mapping

Jaql expressions are mapped to our expressions as follows (where $ is a distinguished expression variable interpreting Jaql's $ ): ( (y,g) ) ) ⇒ ⇒ ⇒ e2 ] This translation defines the (first, in our knowledge) formal semantics of Jaql. Such a translation is all that is needed to define the semantics of a NoSQL language and, as a bonus, endow it with the type inference system we described without requiring any modification of the original language. No further action is demanded since the machinery to exploit it is all developed in this work.

c = c x = x $ = $ {e1:e ′ 1 ,
As for typing, every Jaql expression is encoded into a filter for which type-checking is ensured to terminate: Check() holds for Filter[], Transform[], and Expand (provided it holds also for their arguments) since they only perform recursive calls on recombinations of subtrees of their input; by its definition, the encoding does not introduce any new recursion and, hence, it always yields a composition and application of filters for which Check() holds.

Examples

To show how we use the encoding, let us encode the example of the introduction. For the sake of the concision we will use filter definitions (rather than expanding them in details). We use Fil and Sel defined in the introduction, Expand and Transform[] defined at the beginning of the section, the encoding of Jaql's field selection as defined in Section 3.3, and finally Head that returns the first element of a sequence and a family of recursive filters Rgrpi with i ∈ N + both defined below: In words, we perform the selection on employees and filter the departments (lines 1-2); we tag each element by 1 if it comes from employees, and by 2 if it comes from departments (line 3); we merge the two collections (line 4); we group the heterogeneous list according to the corresponding key (line 5); then for each element of the result of grouping we capture in g the key (line 6), split the group into employees and depts (line 7), capture each subgroup into the corresponding variable (ie, es and ds) (line 8) and return the expression specified in the query after the "into" (lines 8-10). The general definition of the encoding for the co-grouping is given in Appendix H.

Let us now illustrate how the above composition of filters is typed. Consider an instance where: Note how null is retained in the output type (since there may be employees without a department, then Head may be applied to an empty list returning null, and the selection of name of null returns null). For instance suppose to pipe the Jaql grouping defined in the introduction into the following Jaql expression, in order to produce a printable representation of the records of the result transform each x ( (x.deptName)@":"@(to_string x.dep)@":"@(x.numEmps)) where @ denotes string concatenation and to_string is a conversion operator (from any type to string). The composition is ill-typed for three reasons: the field dept is misspelled as dep, x.numEmps is of type int (so it must be applied to to_string before concatenation), and the programmer did not account for the fact that the value stored in the field deptName may be null. The encoding produces the following lines to be appended to the previous code:

Transform[ x => 12 (x.deptName)@":"@(to_string x.dep)@":"@(x.numEmps)] 13 in which all the three errors are detected by our type system. A subtler example of error is given by the following alternative code Transform[ 12 { dept : d, deptName: n&String, numEmps: e } => 13 n @ ":" @ (to_string d) @ ":" @ (to_string e) which corrects all the previous errors but adds a new one since, as detected by our type system, the last branch can be never selected. As we can see, our type-system ensures soundness, forcing the programmer to handle exceptional situations (as in the null example above) but is also precise enough to detect that some code paths can never be reached.

In order to focus on our contributions we kept the language of types and filters simple. However there already exists several contributions on the types and expressions used here. Two in particular are worth mentioning in this context: recursive patterns and XML.

Definition 3 defines patterns inductively but, alternatively, we can consider the (possibly infinite) regular trees coinductively generated by these productions and, on the lines of what is done in CDuce, use the recursive patterns so obtained to encode regular expressions patterns (see [START_REF] Benzaken | CDuce: an XML-friendly general purpose language[END_REF]). Although this does not enhance ex-pressiveness, it greatly improves the writing of programs since it makes it possible to capture distinct subsequences of a sequence by a single match. For instance, when a sequence is matched against a pattern such as [ (int as x | bool as y | _)* ], then x captures (the list of) all integer elements (capture variables in regular expression patterns are bound to lists), y captures all Boolean elements, while the remaining elements are ignored. By such patterns, co-grouping can be encoded without the Rgrp. For instance, the transform in lines 6-11 can be more compactly rendered as: For what concerns XML, the types used here were originally defined for XML, so it comes as a no surprise that they can seamlessly express XML types and values. For example CDuce uses the very same types used here to encode both XML types and elements as triples, the first element being the tag, the second a record representing attributes, and the third a heterogeneous sequence for the content of the element. Furthermore, we can adapt the results of [START_REF] Castagna | Typed iterators for XML[END_REF] to encode forward XPath queries in filters. Therefore, it requires little effort to use the filters presented here to encode languages such as JSONiq [START_REF]Jsoniq[END_REF] designed to integrate JSON and XML, or to precisely type regular expressions, the import/export of XML data, or XPath queries embedded in Jaql programs. This is shown in the section that follows.

JSON, XML, Regex

There exist various attempts to integrate JSON and XML. For instance JSONiq [START_REF]Jsoniq[END_REF] is a query language designed to allow XML and JSON to be used in the same query. The motivation is that JSON and XML are both widely used for data interchange on the Internet. In many applications, JSON is replacing XML in Web Service APIs and data feeds, while more and more applications support both formats. More precisely, JSONiq embeds JSON into an XML query language (XQuery), but it does it in a stratified way: JSONiq does not allow XML nodes to contain JSON objects and arrays. The result is thus similar to OCamlDuce, the embedding of CDuce's XML types and expressions into OCaml, with the same drawbacks.

Our type system is derived from the type system of CDuce, whereas the theory of filters was originally designed to use CDuce as an host language. As a consequence XML types and expressions can be seamlessly integrated in the work presented here, without any particular restriction. To that end it suffices to use for XML elements and types the same encoding used in the implementation of CDuce, where an XML element is just a triple formed by a tag (here, an expression), a record (whose labels are the attributes of the element), and a sequence (of characters and or other XML elements) denoting its content. So for instance the following element <product system="US-size"> <number>557</number> <name>Blouse</name> </product> is encoded by the following triple:

("product" , { system : "US-size" } , [ ("number" , {} , [ 557 ]) ("name", {}, "Blouse") ] )

and this latter, with the syntactic sugar defined for CDuce, can be written as:

<product system="US-size">[ <number>[ 557 ] <name>[ Blouse ] ]
Clearly in our system there are no restrictions in merging and nesting JSON and XML and no further extension is required to our system to define XML query and processing expressions. Just, the introduction of syntactic sugar to make the expressions readable, seems helpful: e ::= <e e>e f ::= <f f >f The system we introduced here is already able to reproduce (and type) the same transformations as in JSONiq, but without the restrictions and drawbacks of the latter (this is why we argue that it is better to extend NoSQL languages with XML primitives directly derived from our system rather than to use our system to encode JSONiq). For instance, the example given in the JSONiq draft to show how to render in Xhtml the following JSON data:

{ "col labels" : ["singular", "plural"], "row labels" : ["1p", "2p", "3p"], "data" : [ ["spinne", "spinnen"], ["spinnst", "spinnt"], ["spinnt", "spinnen"] ] } can be encoded in the filters presented in this work (with the new syntactic sugar) as:

{ "col labels" : cl , "row labels" : rl , "data" : dl

} => <table border="1" cellpadding="1" cellspacing="2">[ <tr>[ <th>[ ] !(cl; Transform[ x -> <th>x ]) ] !(rl; Transform[ h -> <tr>[ <th>h !(dl; Transform[ x -> <td>x ]) ] ] ) ]
(where ! expands a subsequence in the containing sequence). The resulting Xhtml document is rendered in a web browser as: Similarly, Jaql built-in libraries include functions to convert and manipulate XML data. So for example as it is possible in Jaql to embed SQL queries, so it is possible to evaluate XPath expressions, by the function xpath() which takes two arguments, an XML document and a string containing an xpath expression-eg, xpath(read(seq(("conf/addrs.xml")) , "content/city") -. Filters can encode forward XPath expressions (see [START_REF] Nguy Ễn | Language of Combinators for XML: Conception, Typing, Implementation[END_REF]) and precisely type them. So while in the current implementation there is no check of the type of the result of an external query (nor for XPath or for SQL) and the XML document is produced independently from Jaql, by encoding (forward) XPath into filters we can not only precisely type calls to Jaql's xpath() function but also feed them with documents produced by Jaql expressions.

Finally, the very same regular expressions types that are used to describe heterogeneous sequences and, in particular, the content of XML elements, can be used to type regular expressions. Functions working on regular expressions (regex for short) form, in practice, yet another domain specific language that is embedded in general purpose languages in an untyped or weakly typed (typically, every result is of type string) way. Recursive patterns can straightforwardly encode regexp matching. Therefore, by combining the pattern filter with other filters it is possible to encode any regexp library, with the important advantage that, as stated by Theorem 4, the set of values (respectively, strings) accepted by a pattern (respectively, by a regular expression), can be precisely computed and can be expressed by a type. So a function such as the built-in Jaql's function regex_extract(), which extracts the substrings that match a given regex, can be easily implemented by filters and precisely typed by our typing rules. Typing will then amount to intersect the type of the string (which can be more precise than just string) with the type accepted by the pattern that encodes the regex at issue.

Programming with filters

Up to now we have used the filters to encode operators hardcoded in some languages in order to type them. Of course, it is possible to embed the typing technology we introduced directly into the compilers of these language so as to obtain the flexible typing that characterizes our system. However, an important aspect of filters we have ignored so far is that they can be used directly by the programmer to define user-defined operators that are typed as precisely as the hard-coded ones. Therefore a possibility is extend existing NoSQL languages by adding to their expressions the filter application f e expression.

The next problem is to decide how far to go in the definition of filters. A complete integration, that is taking for f all the definitions given so far, is conceivable but might disrupt the execution model of the host language, since the user could then define complex iterators that do not fit map-reduce or the chosen distributed compilation policy. A good compromise could be to add to the host language only filters which have "local" effects, thus avoiding to affect the map-reduce or distributed compilation execution model. The minimal solution consists in choosing just the filters for patterns, unions, and expressions:

f ::= e | p => f | f |f
Adding such filters to Jaql (we use the "=>" arrow for patterns in order to avoid confusion with Jaql's "->" pipe operator) would not allow the user to define powerful operators, but their use would already dramatically improve type precision. For instance we could define the following Jaql expression transform ( { { {a:x,..} } } as y => { { {y.*, sum:x+x} } } | y => y ) (with the convention that a filter occurring as an expression denotes its application to the current argument $ ). With this syntax, our inference system is able to deduce that feeding this expression with an argument of type [{ { {a?:int, c:bool} } }*] returns a result of type [({ { {a:int, c:bool, sum:int} } } | | | { { {c:bool} } })*]. This precision comes from the capacity of our inference system to discriminate between the two branches of the filter and deduce that a sum field will be added only if the a field is present. Similarly by using pattern matching in a Jaql "filter" expression, we can deduce that filter ( int => true | _ => false ) fed with any sequence of elements always returns a (possibly empty) list of in-tegers. An even greater precision can be obtained for grouping expressions when the generation of the key is performed by a filter that discriminates on types: the result type can keep a precise correspondence between keys and the corresponding groups. As an example consider the following (extended) Jaql grouping expression: group e by({town: ("Roma"|"Pisa"), ..} => "Italia" |{town: "Paris", ..} => "France" | _ => "?") if e has type [{town:string, addr:string}*], then the type inferred by our system for this groupby expression is [( ("Italia", [{town:"Roma"|"Pisa", addr:string}+])

|("France", [{town:"Paris", addr:string}+]) |("?", [{town:string/("Roma"|"Pisa"|"Paris"), addr:string}+]) )*] which precisely associates every key to the type of the elements it groups.

Finally, in order to allow a modular usage of filters, adding just filter application to the expression of the foreign language does not suffice: parametric filter definitions are also needed.

Commentaries

Finally, let us explain some subtler design choices for our system.

Filter design: The reader may wonder whether products and record filters are really necessary since, at first sight, the filter ( ( (f1,f2) ) ) could be encoded as (x, y) ⇒ ⇒ ⇒ (f1x, f2y) and similarly for records. The point is that f1x and f2y are expressions -and thus their pair is a filter-only if the fi's are closed (ie, wihtout free term recursion variables). Without an explicit product filter it would not be possible to program a filter as simple as the identity map, µ µ µX. . .'nil ⇒ ⇒ ⇒ 'nil| | |(h, t) ⇒ ⇒ ⇒ ( ( (h,Xt) ) ) since Xt is not an expression (X is a free term recursion variable). Similarly, we need an explicit record filter to process recursively defined record types such as µ µ µX. . .({ { {head:int, tail:X} } }| | |'nil).

Likewise, one can wonder why we put in filters only the "open" record variant that copy extra fields and not the closed one. The reason is that if we want a filter to be applied only to records with exactly the fields specified in the filter, then this can be simply obtained by a pattern matching. So the filter { { {ℓ1:f1, . . . , ℓn:fn} } } (ie, without the trailing ". .") can be simply introduced as syntactic sugar for { { {ℓ1:any, . . . , ℓn:any} } } ⇒ ⇒ ⇒ { { {ℓ1:f1, . . . , ℓn:fn , ..} } } Constructors: The syntax for constructing records and pairs is exactly the same in patterns, types, expressions, and filters. The reader may wonder why we did not distinguish them by using, say, × for product types or = instead of : in record values. This, combined with the fact that values and singletons have the same syntax, is a critical design choice that greatly reduces the confusion in these languages, since it makes it possible to have a unique representation Syntactically we could write µ µ µX. .

.'nil ⇒ ⇒ ⇒ 'nil| | |(h, t) ⇒ ⇒ ⇒ ( ( (h,(Xt)v) ) )
where v is any value, but then this would not pass type-checking since the expression (Xt)v must be typeable without knowing the ∆ environment (cf. rule [FILTER-APP] at the beginning of Section 4.3). We purposedly stratified the system in order to avoid mutual recursion between filters and expressions.

for constructions that are semantically equivalent. Consider for instance the pattern ( ( (x, , ,( ( (3, , ,'nil) ) )) ) ). With our syntax ( ( (3, , ,'nil) ) ) denotes both the product type of two singletons 3 and 'nil, or the value ( ( (3, , ,'nil) ) ), or the singleton that contains this value. According to the interpretation we choose, the pattern can then be interpreted as a pattern that matches a product or a pattern that matches a value. If we had differentiated the syntax of singletons from that of values (eg, {v}) and that of pairs from products, then the pattern above could have been written in five different ways. The point is that they all would match exactly the same sets of values, which is why we chose to have the same syntax for all of them. We opted to use the redundant definition for the sake of clarity. In order to type records with computed labels we distinguished two cases according to whether the type of a record label is finite or not. Although such a distinction is simple, it is not unrealistic. Labels with singleton types cover the (most common) case of records with statically fixed labels. The dynamic choice of a label from a statically known list of labels is a usage pattern seen in JavaScript when building an object which must conform to some interface based on a run-time value. Labels with infinite types cover the fairly common usage scenario in which records are used as dictionaries: we deduce for the expression computing the label the type string, thus forcing the programmer to insert some code that checks that the label is present before accessing it.

The rationale behind the typing of records was twofold. First and foremost, in this work we wanted to avoid type annotations at all costs (since there is not even a notion of schema for JSON records and collections -only the notion of basic type is definedwe cannot expect the Jaql programmer to put any kind of type information in the code). More sophisticated type systems, such as dependent types, would probably preclude type reconstruction: dependent types need a lot of annotations and this does not fit our requirements. Second, we wanted the type-system to be simple yet precise. Making the finite/infinite distinction increases typing precision at no cost (we do not need any extra machinery since we already have singleton types). Adding heuristics or complex analysis just to gain some precision on records would have blurred the main focus of our paper, which is not on typing records but on typing transformations on records. We leave such additions for future work.

Record polymorphism: The type-oriented reader will have noticed that we do not use row variables to type records, and nevertheless we have a high degree of polymorphism. Row variables are useful to type functions or transformations since they can keep track of record fields that are not modified by the transformation. In this setting we do not need them since we do not type transformations (ie, filters) but just the application of transformations (filters are not first-class terms). We have polymorphic typing via filters (see how the first example given in Section 7 keeps track of the c field) and therefore open records suffice.

Record selection: Some languages -typically, the dynamic ones such as Javascript, Ruby, Python-allow the label of a field selection to be computed by an expression. We considered the definition of a fine-grained rule to type expressions of the form e1. . .e2: whenever e2 is typed by a finite unions of strings, the rule would give a finite approximation of the type of the selection. However, such an extension would complex the definition of the type system, just to handle few interesting cases in which a finite union type can be deduced. Therefore, we preferred to omit its study and leave it for future work.

Related Work

In the (nested) relational (and SQL) context, many works have studied the integration of (nested)-relational algebra or SQL into general purpose programming languages. Among the first attempts was the integration of the relational model in Pascal [START_REF] Schmidt | [END_REF] or in Smalltalk [START_REF] Copeland | Making smalltalk a database system[END_REF]. Also, monads or comprehensions [START_REF] Buneman | Comprehension syntax[END_REF][START_REF] Tannen | Naturally embedded query languages[END_REF][START_REF] Trinder | Improving list comprehension database queries[END_REF] have been successfully used to design and implement query languages including a way to embed queries within host languages. Significant efforts have been done to equip those languages with type systems and type checking disciplines [START_REF] Buneman | A Practical Functional Programming System for Databases[END_REF][START_REF] Ohori | Type Inference in a Database Programming Language[END_REF][START_REF] Ohori | Database Programming in Machiavelli -a Polymorphic Language with Static Type Inference[END_REF] and more recently [START_REF] Ohori | Making standard ML a practical database programming language[END_REF] for integration and typing aspects. However, these approaches only support homogeneous sequences of records in the context of specific classes of queries (practically equivalent to a nested relational algebra or calculus), they do not account for records with computable labels, and therefore they are not easily transposable to a setting where sequences are heterogeneous, data are semi-structured, and queries are much more expressive.

While the present work is inspired and stems from previous works on the XML iterators, targeting NoSQL languages made the filter calculus presented here substantially different from the one of [START_REF] Castagna | Typed iterators for XML[END_REF][START_REF] Nguy Ễn | Language of Combinators for XML: Conception, Typing, Implementation[END_REF] (dubbed XML filters in what follows), as well in syntax as in dynamic and static semantics. In [START_REF] Castagna | Typed iterators for XML[END_REF] XML filters behave as some kind of top-down tree transducers, termination is enforced by heavy syntactic restrictions, and a less constrained use of the composition makes type inference challenging and requires sometimes cumbersome type annotations. While XML filters are allowed to operate by composition on the result of a recursive call (and, thus, simulate bottom-up tree transformations), the absence of explicit arguments in recursive calls makes programs understandable only to well-trained programmers. In contrast, the main focus of the current work was to make programs immediately intelligible to any functional programmer and make filters effective for the typing of sequence transformations: sequence iteration, element filtering, one-level flattening. The last two are especially difficult to write with XML filters (and require type annotations). Also, the integration of filters with record types (absent in [START_REF] Castagna | Typed iterators for XML[END_REF] and just sketched in [START_REF] Nguy Ễn | Language of Combinators for XML: Conception, Typing, Implementation[END_REF]) is novel and much needed to encode JSON transformations.

Conclusion

Our work addresses two very practical problems, namely the typing of NoSQL languages and a comprehensive definition of their semantics. These languages add to list comprehension and SQL operators the ability to work on heterogeneous data sets and are based on JSON (instead of tuples). Typing precisely each of these features using the best techniques of the literature would probably yield quite a complex type-system (mixing row polymorphism for records, parametric polymorphism, some form of dependent typing,...) and we are skeptical that this could be achieved without using any explicit type annotation. Therefore we explored the formalization of these languages from scratch, by defining a calculus and a type system. The thesis we defended is that all operations typical of current NoSQL languages, as long as they operate structurally (ie, without resorting on term equality or relations), amount to a combination of more basic bricks: our filters. On the structural side, the claim is that combining recursive records and pairs by unions, intersections, and negations suffices to capture all possible structuring of data, covering a palette ranging from comprehensions, to heterogeneous lists mixing typed and untyped data, through regular expressions types and XML schemas. Therefore, our calculus not only provides a simple way to give a formal semantics to, reciprocally compare, and combine operators of different NoSQL languages, but also offers a means to equip these languages, in they current definition (ie, without any type definition or annotation), with precise type inference.

As such we accounted for both components that, according to Landin, constitute the design of a language: operators and data structures. But while Landin considers the design of terms and types as independent activities we, on the contrary, advocate an approach in which the design of former is driven by the form of latter. Although other approaches are possible, we tried to convey the idea that this approach is nevertheless the only one that yields a type system whose precision, that we demonstrated all the work long, is comparable only to the precision obtained with hard-coded (as opposed to user-defined) operators. As such, our type inference yields and surpasses in precision systems using parametric polymorphism and row variables. The price to pay is that transformations are not first class: we do not type filters but just their applications. However, this seems an advantageous deal in the world of NoSQL languages where "selects" are never passed around (at least, not explicitly), but early error detection is critical, especially in the view of the cost of code deployment.

The result are filters, a set of untyped terms that can be easily included in a host language to complement in a typeful framework existing operators with user-defined ones. The requirements to include filters into a host language are so minimal that every modern typed programming language satisfies them. The interest resides not in the fact that we can add filter applications to any language, rather that filters can be used to define a smooth integration of calls to domain specific languages (eg, SQL, XPath, Pig, Regex) into general purpose ones (eg, Java, C#, Python, OCaml) so as both can share the same set of values and the same typing discipline. Likewise, even though filters provide an early prototyping platform for queries, they cannot currently be used as a final compilation stage for NoSQL languages: their operations rely on a Lisp-like encoding of sequences and this makes the correspondence with optimized bulk operations on lists awkward. Whether we can derive an efficient compilation from filters to map-reduce (recovering the bulk semantics of the high-level language) is a challenging question.

Future plans include practical experimentation of our technique: we intend to benchmark our type analysis against existing collections of Jaql programs, gauge the amount of code that is ill typed and verify on this how frequently the programmer adopted defensive programming to cope with the potential type errors.

1. It builds a substitution σ : Vars → Ids from expression variables to variables identifiers, thus associating each capture variable occurring in a pattern of the filter to a fresh identifier for the abstract subtree of the input type it will be bound to.

2. It uses the substitution σ to compute the set of symbolic arguments of recursive calls of X.

In other words, if n recursive calls of X occur in the filter f , then TreesX (σ, f ) returns the set {A1, ..., An} of the n symbolic arguments of these calls, obtained under the hypothesis that the free variables of f are associated to subtrees as specified by σ. The formal definition is as follows:

TreesX (σ, e) = ∅ TreesX (σ, p ⇒ ⇒ ⇒ f ) = TreesX (σ ∪ x i ∈vars(p) {xi → ιi}, f ) (ιi fresh) TreesX (σ, ( ( (f1,f2) ) )) = TreesX (σ, f1) ∪ TreesX (σ, f2) TreesX (σ, f1| | |f2) = TreesX (σ, f1) ∪ TreesX (σ, f2) TreesX (σ, µ µ µX. . .f ) = ∅ TreesX (σ, µ µ µY . . .f ) = TreesX (σ, f ) (X = Y ) TreesX (σ, Xa) = {aσ} TreesX (σ, f1;f2) = TreesX (σ, f2) TreesX (σ, of ) = TreesX (σ, f ) (o = groupby , orderby ) TreesX (σ, { { {ℓi:fi , ..} } }i∈I ) = i∈I TreesX (σ, fi)
where aσ denotes the application of the substitution σ to a.

The definition above is mostly straightforward. The two important cases are those for the pattern filter where the substitution σ is updated by associating every capture variable of the pattern with a fresh variable identifier, and the one for the recursive call where the symbolic argument is computed by applying σ to the actual argument.

Second phase. The second phase is implemented by the function Check(). The intuition is that Check(f ) must "compute" the application of f to all the symbolic arguments collected in the first phase and then check whether the variables occurring in the arguments of recursive calls (ie, the "marked" variables) are actually bound to subtrees of the original type (ie, they are bound either to variable identifiers or to subparts of variable identifiers). If we did not have filter composition, then this would be a relatively easy task: it would amount to compute substitutions (by matching symbolic arguments against patterns), apply them, and finally verify that the marked variables satisfy the sought property. Unfortunately, in the case of a composition filter f1;f2 the analysis is more complicated than that. Imagine that we want to check the property for the application of f1;f2 to a symbolic argument A. Then to check the property for the recursive calls occurring in f2 we must compute (or at least, approximate) the set of the symbolic arguments that will be produced by the application of f1 to A and that will be thus fed into f2 to compute the composition. Therefore Check(f ) will be a function that rather than returning just true or false, it will return a set of symbolic arguments that are the result of the execution of f , or it will fail if any recursive call does not satisfy the property for marked variables.

More precisely, the function Check() will have the form

CheckV (σ, f, {A1, ..., An})
where V ⊆ Vars stores the set of marked variables, f is a filter, σ is a substitution for (at least) the free variables of f into Ids, and Ai are symbolic arguments. It will either fail if the marked variables do not satisfy the property of being bound to (subcomponents of) variable identifiers or return an over-approximation of the result of applying f to all the Ai under the hypothesis σ. This approximation is either a set of new symbolic arguments, or ⊥. The latter simply indicates that Check() is not able to compute the result of the application, typically because it is the result of some expression types that are in the item(t). This however is not enough since we would not use the information of the descriminant domains for the filter. For instance if the filter gives two different result types for positive and negative numbers and the input is a list of integers, we want to compute two different result types for positive and negatives and not just to compute the result of the filter application on generic integers (indeed item([int*]) = {int}). So the idea is to add to the set that must be normalized all the types of the set of discriminant types. This however is not precise enough, since these domains may be much larger than the item types of the input list. For this reason we just take the part of the domain types that intersects at least some possible value of the list. In other terms we consider the normal form of the following set

item(t) ∪ {σi ∧ ∧ ∧ t i ∈D(f ) ti | σi ∈ item(t)}
The idea is then that if {ti}i∈I is the normalized set of the set above, then the type of grouby is the type [ i∈I ( ( (f (ti), , ,[ti+]) ) )*] with the optimization that we can replace the * by a + if we know that the input list is not empty.

F. Comparison with top-down tree transducers

We first show that every Top-down tree transducers with regular look-ahead can be encoded by a filter. We use the definition of [START_REF] Engelfriet | Top-down tree transducers with regular look-ahead[END_REF] for top-down tree transducers: Definition 20 (Top-down Tree transducer with regular look-ahead). A top-down tree transducer with regular look-ahead (TDTTR) is a 5-tuple < Σ, ∆, Q, Q d , R > where Σ is the input alphabet, ∆ is the output alphabet, Q is a set of states, Q d the set of initial states and R a set of rules of the form:

q(a(x1, . . . , xn)), D → b(q1(xi 1 ), . . . , qm(xi m ))
where a ∈ Σn, b ∈ ∆m, q, q1,. . . , qm ∈ Q, ∀j ∈ 1..m, ij ∈ 1..n and D is a mapping from {x1, . . . , xn} to 2 T Σ (TΣ being the set of regular tree languages over alphabet Σ). A TDTTR is deterministic if Q d is a singleton and the left-hand sides of the rules in R are pairwise disjoint.

Since our filters encode programs, it only make sense to compare filters and deterministic TDTTR. We first show that given such a deterministic TDTTR we can write an equivalent filter f and, furthermore, that Check(f ) does not fail. First we recall the encoding of ranked labeled trees into the filter data-model: Definition 21 (Tree encoding). Let t ∈ TΣ. We define the treeencoding of t and we write t the value defined inductively by: a = ('a,[]) ∀a ∈ Σ0 a(t1, . . . , tn) = ('a,[ t1 ... tn ]) ∀a ∈ Σn where the list notation [ v1 ... vn ] is a short-hand for (v1, ..., (vn, 'nil)). We generalize this encoding to tree languages and types. Let S ⊆ Tσ, we write S the set of values such that ∀t ∈ S, t ∈ S .

In particular it is clear than when S is regular, S is a type.

Lemma 22 (TDTTR → filters). Let T =< Σ, ∆, Q, {q0}, R > be a deterministic TDTTR. There exists a filter fT such that:

∀t ∈ dom(T ), T (t) ≡ fT t

Proof. The encoding is as follows. For every state qi ∈ Q, we will introduce a recursion variable Xi. The fact that ∀t ∈ dom(T ), T (t) ≡ TR(∅, q0) t is proved by a straightforward induction on t. The only important point to remark is that since T is deterministic, there is exactly one branch of the alternate filter f1| | | . . . | | |fn that can be selected by pattern matching for a given input v. For as to why Check(fT ) holds, it is sufficient to remark that each recursive call is made on a strict subtree of the input which guarantees that Check(fT ) returns true.

Lemma 23 (TDTTR ← filters). Filters are strictly more expressive than TDTTRs.

Proof. Even if we restrict filters to have the same domain as TDT-TRs (meaning, we used a fixed input alphabet Σ for atomic types) we can define a filter that cannot be expressed by a TDTTR. For instance consider the filter: This filter works on monadic trees of the form u1(. . . un-1(un) . . .) where ui ∈ {a, b}, and essentially replaces the leaf un of a tree t by a copy of t itself. This cannot be done by a TDTTR. Indeed, TDTTR have only two ways to "remember" a subtree and copy it. One is of course by using variables; but their scope is restricted to a rule and therefore an arbitrary subtree can only be copied at a fixed distance of its original position. For instance in a rule of the form q(a(x)), D → a(q1(x), b(b(q1(x)))), assuming than q1 copies its input, the copy of the original subtree is two-levels down from its next sibling but it cannot be arbitrary far. A second way to copy a subtree is to remember it using the states. Indeed, states can encode the knowledge that the TDTTR has accumulated along a path. However, since the number of states is finite, the only thing that a TDTTR can do is copy a fixed path. For instance for any given n, there exists a TDTTR that performs the transformation above, for trees of height n (it has essentially 2 n -1 states which remember every possible path taken). For instance for n = 2, the TDTTR is: where Σ = ∆ = {a, b}, Q = {q0, q1, q2}, Q d = {q0} and D = {x → TΣ}. It is however impossible to write a TDTTR that replaces a leaf with a copy of the whole input, for inputs of arbitrary size. A similar example is used in [START_REF] Engelfriet | Bottom-up and Top-down Tree Transformations -A comparison[END_REF] to show that TDTTR and bottom-up tree transducers are not comparable.

G. Operators on record types.

We use the theory of records defined for CDuce. We summarize here the main definitions. These are adapted from those given in Chapter 9 of Alain Frisch's PhD thesis [START_REF] Frisch | Théorie, conception et réalisation d'un langage de programmation fonctionnel adapté à XML[END_REF] where the interested reader can also find detailed definitions of the semantic interpretation of record types and of the subtyping relation it induces, the modifications that must be done to the algorithm to decide it, finer details on pattern matching definition and compilation techniques for record types and expressions. Let Z denote some set, a function r : L → Z is quasi-constant if there exists z ∈ Z such that the set {ℓ∈L | r(ℓ) = z} is finite; in this case we denote this set by dom(r) and the element z by def(r). We use L Z to denote the set of quasi-constant functions from L to Z and the notation {ℓ1 = z1, . . . , ℓn = zn, _ = z} to denote the quasi-constant function r : L Z defined by r(ℓi) = zi for i = 1..n and r(ℓ) = z for ℓ ∈ L \ {ℓ1, . . . , ℓn}. Although this notation is not univocal (unless we require zi = z), this is largely sufficient for the purposes of this section.

Let ⊥ be a distinguished constant, then the sets string Types ∪ {⊥} and string

Values ∪ {⊥} denote the set of all record types expressions and of all record values, respectively. The constant ⊥ represents the value of the fields of a record that are "undefined". To ease the presentation we use the same notation both for a constant and the singleton type that contains it: so when ⊥ occurs in L Values ∪ {⊥} it denotes a value, while in string Types ∪ {⊥} it denotes the singleton type that contains only the value ⊥.

Given the definitions above, it is clear that the record types in Definition 2 are nothing but specific notations for some quasiconstant functions in string Types ∪ {⊥}. More precisely, the open record type expression { { {ℓ1:t1, . . . , ℓn:tn , .. .. ..} } } denotes the quasi-constant function {ℓ1 = t1, . . . , ℓn = tn, _ = any} while the closed record type expression { { {ℓ1:t1, . . . , ℓn:tn} } } denotes the quasi-constant function {ℓ1 = t1, . . . , ℓn = tn, _ = ⊥}. Similarly, the optional field notation { { {..., ℓ?:t, ...} } } denotes the record type expressions in which ℓ is mapped either to ⊥ or to the type t, that is, {..., ℓ = t | | |⊥, ...}.

Let t be a type and r1, r2 two record type expressions, that is r1, r2 : string Types ∪ {⊥}. The merge of r1, and r2 with respect to t, noted ⊕t and used infix, is the record type expression defined as follows: Finally, all the operators we used for the typing of records in the rules of Section 4.2 are defined in terms of the merge operator:

t1 + t2 def = t2 ⊕ ⊥ t1 (1)
t \ ℓ def = {ℓ = ⊥, _ = c0} ⊕c 0 t ( 2
)
where c0 is any constant different from ⊥ (the semantics of the operator does not depend on the choice of c0 as long as it is different from ⊥). Notice in particular that the result of the concatenation of two record type expressions r1 + r2 may result for each field ℓ in three different outcomes:

1. if r2(ℓ) does not contain ⊥ (ie, the field ℓ is surely defined), then we take the corresponding field of r2: (r1 + r2)(ℓ) = r2(ℓ)

2. if r2(ℓ) is undefined (ie, r2(ℓ) = ⊥), then we take the corresponding field of r1: (r1 + r2)(ℓ) = r1(ℓ)

H. Encoding of Co-grouping

As shown in Section 5.2, our groupby operator can encode JaQL's group each x = e as y by e ′ , where e computes the grouping key, and for each distinct key, e ′ is evaluated in the environment where x is bound to the key and y is bound to the sequence of elements in the input having that key. Co-grouping is expressed by: group l1 by x = e1 as y1 . . . | _ => Rgrpi tail Essentially, the co-grouping encoding takes as argument a sequence of sequences of values (the n sequences to co-group). Each of these n sequence, is tagged with an integer i. Then we flatten this sequences of tagged values. We can on this single sequence apply our groupby operator and modify each key selector ei so that it is only applied to a value tagged with integer i. Once this is done, we obtain a sequence of pairs (k, l) where k is the commen grouping key and l a sequence of tagged values. We only have to apply the auxiliary Regrp filter which extracts the n subsequences from l (tagged with 1..n) and removes the integer tag for each value. Lastly we can call the recombining expression e which has in scope x bound to the current grouping key and y1,. . . ,yn bound to each of the sequences of values from input l1, . . . ,ln whose grouping key is x.

  { {ℓ:x , .. .. ..} } } ⇒ ⇒ ⇒ x)e fst(e) def = (( ( (x, , ,any) ) ) ⇒ ⇒ ⇒ x)e snd(e) def = (( ( (any, , ,x) ) ) ⇒ ⇒ ⇒ x)e let p = e1 in e2 def = (p ⇒ ⇒ ⇒ e2)e1 if e then e1 else e2 def = ('true ⇒ ⇒ ⇒ e1| | |'false ⇒ ⇒ ⇒ e2)e 6 2013/3/7 match e with p1 ⇒ ⇒ ⇒ e1|...|pn ⇒ ⇒ ⇒ en def = (p1 ⇒ ⇒ ⇒ e1| | | . . . | | |pn ⇒ ⇒ ⇒ en)e

  for instance, { { {a:int, b:int} } } + { { {a?:bool} } } = { { {a:int| | |bool, b:int} } }; unknown fields in the right-hand side may override known fields of the left-hand side, which is why, for instance, we have { { {a:int, b:bool} } } + { { {b:int , .. .. ..} } } = { { {b:int , .. .. ..} } }; likewise, for every record type t (ie, for every t subtype of { { {..} } }) we have t + { { {..} } } = { { {..} } }. Finally, [RCD-CONC] and [RCD-DEL] deal with record concatenation and field deletion, respectively, in a straightforward way: the only constraint is that all expressions must have a record type (ie, the constraints of the form ... ≤ { { {..} } }).

  For instance consider the type ( ( (int, , ,int) ) )| | |( ( (string, , ,string) ) ) This type denotes the set of pairs for which either both projections are int or both projections are string. A type such as ( ( (int| | |string, , ,int| | |string)

Figure 2 .

 2 Figure 2. Type inference algorithm for filter application compromise between precision and decidability. First we define an auxiliary function over sequence types: Definition 12 (Item set). Let t ∈ Types such that t ≤ [any*].The item set of t denoted by item(t) is defined by:

  [int* bool+ int]. If we apply it once more the inferred type is [int* bool+ int int]|[bool* int bool].

  ) | [e,... , e] (arrays) | { e:e,... , e:e } (records) | e.l (field access) | op(e,... ,e) (function call) | e -> k (pipe) k ::= filter (each x )? e (filter) | transform (each x)? e (transform) | expand ((each x)? e)?

  let filter Filter [F ] = µ µ µX. . . 'nil ⇒ ⇒ ⇒ 'nil | | | ( ( (( ( (x, , , xs) ) ), , ,tl) ) ) ⇒ ⇒ ⇒ ( ( (X(x, xs),X(tl)) ) ) | | | ( ( (x, , ,tl) ) ) ⇒ ⇒ ⇒ F x ;('true ⇒ ⇒ ⇒ ( ( (x, X(tl)) ) )| | |'false ⇒ ⇒ ⇒ X(tl)) let filter Transform [F ] = µ µ µX. . . 'nil ⇒ ⇒ ⇒ 'nil | | | ( (

  ...,en:e ′ n } = { { { e1 : e ′ 1 , ..., en : e ′ n } } } e.l = e .l op(e1, ..., en) = op( e1 , ..., en ) [e1,...,en] = ( e1 , ...( en , 'nil)...) e -> k = e ; k F Jaql core expressions are mapped to filters as follows: 10 2013/3/7 filter e F = filter each $ e F filter each x e F = Filter [x ⇒ ⇒ ⇒ e ] transform e F = transform each $ e F transform each x e F = Transform [x ⇒ ⇒ ⇒ e ] expand each x e F = expand F ; transform each x e F expand F = Expand group into e F = group by y=true into e F group by y=e1 into e2 F = group each $ by y=e1 into e2 F group each x by y=e1 into e2 F = group each x by y = e1 as $ into e2 F group each x by y = e1 as g into e2 F = groupby x ⇒ ⇒ ⇒ e1 ; Transform [(

  let filter Head = 'nil => null | (x,xs) => x let filter Rgrpi = 'nil => 'nil | ((i,x),tail) => (x , Rgrpi tail) | _ => Rgrpi tail Then, the query in the introduction is encoded as follows [employees depts]; [Sel Fil]; [Transform[x =>(1,x)] Transform[x =>(2,x)]]; Expand; groupby ( (1,$)=>$.dept | (2,$)=>$.depid ); Transform[(g,l)=>( [(l; Rgrp1) (l; Rgrp2)]; [es ds] => { dept: g, deptName: (ds ; Head).name), numEmps: count(es) } )]

14 |

 14 { deptName: null, .. } => "" 15 | _ => "Invalid department" ]

16

 16

  Transform[(g,[ ((1,es)|(2,ds))* ]) => { dept: g, deptName: (ds;Head).name, numEmps: count(es) }]

  e ::= f e | let filter F [F1, . . . , Fn] = f in e However, on the line of what we already said about the disruption of the execution model, recursive parametric filter definitions should be probably disallowed, since a compilation according to a mapreduce model would require to disentangle recursive calls.

  Record types: The definition of records is redundant (both for types and patterns). Instead of the current definition we could have used just { { {ℓ:t} } }, { { {} } }, and { { {..} } }, since the rest can be encoded by intersections. For instance, { { {ℓ1:t1, . . . , ℓn:tn , .. .. ..} } } = { { {ℓ1:t} } }& & &...& & &{ { {ℓn:tn} } }& & &{ { {..} } }.

  Formally, the translation is performed by the function TR : 2 Q × Q → Filters defined as:TR(S, qi) = x ⇒ ⇒ ⇒ Xi x if qi ∈ S TR(S, qi) = µXi.(f1| | | . . . | | |fn) if qi / ∈ Swhere every rule rj ∈ R rj ≡ qi(aj(x1, . . . , xn)), Dj → bj(qj 1 (xj k 1 ), . . . , qj m (xj km )) is translated into: ('aj , [ x1& & & Dj (x1) ... xn& & & Dj(xn) ]) ⇒ ⇒ ⇒ 'bj ,[] if bj ∈ ∆0 ('aj , [ x1& & & Dj (x1) ... xn& & & Dj(xn) ]) ⇒ ⇒ ⇒ ( ( ('bj,( ( (xj k 1 ;TR(S ′ , qj 1 ),( ( ( . . . ,( ( (xj km ;TR(S ′ , qj m ),'nil) ) )) ) )) ) )) ) ) whereS ′ = S ∪ {qi} otherwise

y

  ⇒ ⇒ ⇒(µX.( ( ('a, , ,'nil) ) ) ⇒ ⇒ ⇒ y | | |( ( ('b, , ,'nil) ) ) ⇒ ⇒ ⇒ y | | |( ( ('a, , ,[x]) ) ) ⇒ ⇒ ⇒ ('a, [ X x ])) | | |( ( ('b, , ,[x]) ) ) ⇒ ⇒ ⇒ ('b, [ X x ]))

  q0(a(x)), D → a(q1(x)) q1(a()), D → a(a) q1(b()), D → a(b) q0(b(x)), D → b(q2(x)) q2(a()), D → b(a) q2(b()), D → b(b)

(

  r1 ⊕t r2)(ℓ) def = r1(ℓ) if r1(ℓ)& & &t ≤ empty (r1(ℓ) \ t)| | |r2(ℓ) otherwiseRecall that by Lemma 11 a record type (ie, a subtype of {..}) is equivalent to a finite union of record type expressions (ie, quasiconstant functions in string Types ∪ {⊥}). So the definition of merge can be easily extended to all record types as follows ( (ri ⊕t r ′ j )

3 .

 3 if r2(ℓ) may be undefined (ie, r2(ℓ) = t| | |⊥ for some type t), then we take the union of the two corresponding fields since it can results either in r1(ℓ) or r2(ℓ) according to whether the record typed by r2 is undefined in ℓ or not:(r1 + r2)(ℓ) = r1(ℓ)| | |(r2(ℓ) \ ⊥).This explains all the examples we gave in the main text. In particular, { { {a:int, b:int} } } + { { {a?:bool} } } = { { {a:int| | |bool, b:int} } } since "a" may be undefined in the right hand-side record while "b" is undefined in it, and { { {a:int} } } + { { {..} } } = { { {..} } }, since "a" in the right hand-side record is defined (with a → any) and therefore has priority over the corresponding definition in the left hand-side record.

  ln by x = en as yn into e Co-grouping is encoded by the following composition of filters:[ l1 ... ln ]; [ Transform[x ⇒ ⇒ ⇒ (1, x)] ... Transform[x ⇒ ⇒ ⇒ (n, x)] ]; Expand; groupby (( ( (1, , ,$) ) ) ⇒ ⇒ ⇒ e1 | | | . . . | | |( ( (n, , ,$) ) ) ⇒ ⇒ ⇒ en ); Transform[ ( ( (x, , ,l) ) ) ⇒ ⇒ ⇒([(l;Rgrp1)...(l; Rgrpn)];[y1, . . . , yn] ⇒ ⇒ ⇒ e )] where let filter Rgrpi = 'nil => 'nil | ((i,x),tail) => (x , Rgrpi tail)

  The union type s| | |t contains all the values of s and of t, while the difference type s\ \ \t contains all the values of s that are not in t. We shall use bool as an abbreviation of the union of the two singleton types containing true and false: 'true| | |'false. any and empty respectively contain all and no values. Recursive type definitions are also used (see Section 2.2 for formal details).

The closed record type { { {a:int, b:int} } } contains all record values with exactly two fields a and b with integer values, while the open record type { { {a:int, b:int , .. .. ..} } } contains all record values with at least two fields a and b with integer values. The sequence type [r] is the set of all sequences whose content is described by the regular expression r; so, for example [char*] contains all sequences of characters (we will use string to denote this type and the standard double quote notation to denote its values) while [({ { {a:int} } } { { {a:int} } })+] denotes nonempty lists of even length containing record values of type { { {a:int} } }.

  employees has type [ Remp* ], where Remp ≡ { dept: int, income:int, ..} • depts has type [ (Rdep | Rbranch)* ], where Rdep ≡ {depid:int, name: string, size: int} Rbranch ≡ {brid:int, name: string} (this type is a subtype of Dept as defined in the introduction) Lastly the transform is typed exactly, yielding the final type [ {dept:int, deptName:string|null, numEmps:int }* ]

	The global input type is therefore (line 1)
	[ [ Remp* ] [ (Rdep | Rbranch)* ] ]
	which becomes, after selection and filtering (line 2)
	[ [ Remp* ] [ Rdep* ] ]
	(note how all occurrences of Rbranch are ignored by Fil). Tagging
	with an integer (line 3) and flattening (line 4) yields
	[ (1,Remp)* (2,Rdep)* ]
	which illustrates the precise typing of products coupled with sin-
	gleton types (ie, 1 instead of int). While the groupby (line 5) in-
	troduces an approximation the dependency between the tag and the
	corresponding type is kept
	[ (int, [ ((1,Remp) | (2,Rdep) )+ ]) * ]

•

2013/3/7

2013/3/7

2013/3/7

2013/3/7

2013/3/7

The function type must be able to handle type environments with types of our system. It can do it either by subsuming variable with specific types to the types of the host language (eg, if the host language does not support singleton types then the singleton type 3 will be subsumed to int) or by typing foreign expressions by using our types.whether the type t1 of e1 is finite (ie, it contains only finitely many values, such as, say, Bool) or not. If a type is finite, (finiteness of regular types seen as tree automata can be decided in polynomial time[START_REF] Comon | Tree automata techniques and applications[END_REF]), then it is possible to write it as a finite union of values (actually, of singleton types). So consider again { { {e1:e2} } } and let t1 be the type of e1 and t2 the type of e2. First, t1 must be a subtype of string (since record labels are strings). So if t1 is finite it can be expressed as ℓ1| | | • • • | | |ℓn which means that e1 will return the string ℓi for some i ∈ [1..n]. Therefore { { {e1:e2} } } will have type { { {ℓi : t2} } } for some i ∈ [1..n] and, thus, the union of all these types, as expressed by the rule [RCD-FIN] below. If t1 is infinite instead, then all we can say is that it will be a record with some (unknown) labels, as expressed by rule [RCD-INF].[RCD-FIN]Γ ⊢ e : ℓ1| | | • • • | | |ℓn Γ ⊢ e ′ : t Γ ⊢ {e:e ′ } : { { {ℓ1:t} } }| | | • • • | | |{ { {ℓn:t} } } [RCD-INF] Γ ⊢ e : t Γ ⊢ e ′ : t ′ t ≤ string t is infinite Γ ⊢ {e:e ′ } : { { {..} } } [RCD-MUL] Γ ⊢ {e1:e ′ 1 } : t1 • • • Γ ⊢ {en:e ′ n }: tn Γ ⊢ {e1:e ′ 1 , . . . , en:e ′ n } : t1 + • • • + tn [RCD-CONC] Γ ⊢ e1 : t1 Γ ⊢ e2 : t2 t 1 ≤ { { {..} } } t 2 ≤ { { {..} } }

4.3 Typing of filter applicationFilters are not first-class: they can be applied but not passed around or computed. Therefore we do not assign types to filters but, as for any other expression, we assign types to filter applications. The typing rule for filter application [FILTER-APP] Γ ⊢ e : t Γ ;∅ ;∅ ⊢fil f (t) : s Γ ⊢ f e : s 7 2013/3/7

2013/3/7

2013/3/7

2013/3/7

2013/3/7

2013/3/7

2013/3/7

2013/3/7

2013/3/7

2013/3/7

2013/3/7

2013/3/7

A. Termination analysis algorithm

In order to deduce the result type of the application of a filter to an expression, the type inference algorithm abstractly executes the filter on the type of the expression. As explained in Section 4, the algorithm essentially analyzes what may happen to the original input type (and to its subtrees) after a recursive call and checks that, in all possible cases, every subsequent recursive call will only be applied to subtrees of the original input type. In order to track the subtrees of the original input type, we use an infinite set Ids = {ι1, ι2, . . .} of variable identifiers (ranged over by, possible indexed, ι). These identifiers are used to identify the subtrees of the original input type that are bound to some variable after a recursive call. Consider for instance the recursive filter: The algorithm records that at the first call of this filter each variable xi is bound to a subtree ιi of the input type. The recursive call X( ( (x1,x3) ) ) is thus applied to the "abstract argument" ( ( (ι1,ι3) ) ). If we perform the substitutions for this call, then we see that x1 will be bound to ι1 and that x2 and x3 will be bound to two subtrees of the ι3 subtree. We do not care about x2 since it is not used in any recursive call. What is important is that both x1 and x3 are bound to subtrees of the original input type (respectively, to ι1 and to a subtree of ι3) and therefore, for this filter, the type inference algorithm will terminate for every possible input type.

The previous example introduces the two important concepts that are still missing for the definition of our analysis:

1. Recursive calls are applied to symbolic arguments, such as ( ( (ι1,ι3) ) ), that are obtained from arguments by replacing variables by variable identifiers. Symbolic arguments are ranged over by A and are formally defined as follows: 2. We said that we "care" for some variables and disregard others.

When we analyze a recursive filter µ µ µX. . .f the variables we care about are those that occur in arguments of recursive calls of X.

Given a filter f and a filter recursion variable X the set of these variables is formally defined as follows As an aside notice that the fact that for a given filter f the type inference algorithm terminates on all possible input types does not imply that the execution of f terminates on all possible input values. For instance, our analysis correctly detects that for the filter µ µ µX. . .(

terminates on all possible input types (by returning the very same input type) although the application of this same filter never terminates on arguments of the form ( ( (v1,v2) ) ).

We can now formally define the two phases of our analysis algorithm.

First phase. The first phase is implemented by the function Trees_(_, _). For every filter recursion variable X, this function explores a filter and does the following two things:

(where ι 1 and ι 2 are fresh)

(where all ι i are fresh) The full definition of Check_(_, _, _) is given in Figure 3. Let us comment the different cases in detail.

CheckV (σ, f, Ai) simply states that to compute the filter f on a set of symbolic arguments we have to compute f on each argument and return the union of the results. Of course, if any CheckV (σ, f, Ai) fails, so does CheckV (σ, f, {A1, ..., An}). The next case is straightforward: if we know that an argument of a given form makes the filter f fail, then we do not perform any check (the recursive call of f will never be called) and no result will be returned. For instance, if we apply the filter { { {ℓ:f , ..} } } to the symbolic argument ( ( (ι1,ι2) ) ), then this will always fail so it is useless to continue checking this case. Formally, what we do is to consider ⌉ ⌉ ⌉A⌈ ⌈ ⌈, the set of all values that have the form of A (this is quite simply obtained from A by replacing any for every occurrence of a variable identifier or of ⊥) and check whether in it there is any value accepted by f , namely, whether the intersection ⌉ ⌉ ⌉A⌈ ⌈ ⌈& & & f is empty. If it is so, we directly return the empty set of symbolic arguments, otherwise we have to perform a fine grained analysis according to the form of the filter.

If the filter is an expression, then there are two possible cases: either the expression has the form of an argument (≡ denotes syntactic equivalence), in which case we return it after having applied the substitution σ to it; or it is some other expression, in which case the function says that it is not able to compute a result and returns ⊥.

When the filter is a composition of two filters, f1;f2, we first call CheckV (σ, f1, A) to analyze f1 and compute the result of applying f1 to A, and then we feed this result to the analysis of f2:

When the filter is recursive or a recursive call, then we are not able to compute the symbolic result. However, in the case of a recursive filter we must check whether the type inference terminates on it. So we mark the variables of its recursive calls, check whether its definition passes our static analysis, and return ⊥ only if this analysis -ie, Check Mark X (f ) (σ, f, A)-did not fail. Notice that ⊥ is quite different from failure since it allows us to compute the approximation as long as the filter after the composition does not bind (parts of) the result that are ⊥ to variables that occur in arguments of recursive calls. A key example is the case of the filter Filter[F ] defined in Section 5.1. If the parameter filter F is recursive, then without ⊥ Filter[F ] would be rejected by the static analysis. Precisely, this is due to the composition

When F is recursive the analysis supposes that F x produces ⊥, which is then passed over to the pattern. The recursive call Xl is executed in the environment ⊥/'true, which is empty. Therefore

(where ι i are fresh)

(where ι i are fresh)

Pattern matching with respect to a set V of marked variables the result of the F x call, whatever it is, cannot affect the termination of the subsequent recursive calls. Even though the composition uses the result of F x, the form of this result cannot be such as to make typechecking of Filter[F ] diverge.

For the union filter f1| | |f2 there are three possible cases: f1 will always fail on A, so we return the result of f2; or f2 will never be executed on A since f1 will never fail on A, so we return just the result of f1; or we cannot tell which one of f1 or f2 will be executed, and so we return the union of the two results.

If the filter is a product filter ( ( (f1,f2) ) ), then its accepted type ( ( (f1,f2) ) ) is a subtype of ( ( (any,any) ) ). Since we are in the case where ⌉ ⌉ ⌉A⌈ ⌈ ⌈& & & ( ( (f1,f2) ) ) is not empty, then A can have just two forms: either it is a pair or it is a variable identifier ι. In the former case we check the filters component-wise and return as result the set-theoretic product of the results. In the latter case, recall that ι represents a subtree of the original input type. So if the application does not fail it means that each subfilter will be applied to a subtree of ι. We introduce two fresh variable identifiers to denote these subtrees of ι (which, of course are subtrees of the original input type, too) and, as in the previous case, apply the check component-wise and return the set-theoretic product of the results. The case for the record filter is similar to the case of the product filter.

Finally, the case of pattern filter is where the algorithm checks that the marked variables are indeed bound to subtrees of the initial input type. What Check() does is to match the symbolic argument against the pattern and update the substitution σ so as to check the subfilter f in an environment with the corresponding assignments for the capture variables in p. Notice however that the pattern matching A V / p receives as extra argument the set V of marked variables, so that while computing the substitutions for the capture variables in p it also checks that all capture variables that are also marked are actually bound to a subtree of the initial input type. A V / p is defined in Figure 4 (to enhance readability we omitted the V index since it matters only in the first case and it does not change along the definition). The check for marked variables is performed in the first case of the definition: when a symbolic argument A is matched against a variable x, if the variable is not marked (x ∈ V), then the substitution {x → A} is returned; if it is marked, then the matching (and thus the analysis) does not fail only if the symbolic argument is either a value (so it does not depend on the input type) or it is a variable identifier (so it will be exactly a subtree of the original input type). The other cases of the definition of A V / p are standard. Just notice that in the product and record patterns when A is a variable identifier ι, the algorithm creates fresh new variable identifiers to denote the new subtrees in which ι will be decomposed by the pattern. Finally, the reader should not confound Ω and fail. The former indicates that the argument does not match the value, while the latter indicates that a marked variable is not bound to a value or to exactly a subtree of the initial input type (notice that the case Ω cannot happen in the definition of Check()

The two phases together. Finally we put the two phases together. Given a recursive filter µ µ µX. . .f we run the analysis by marking the variables in the recursive calls of X in f , running the first phase and then and feeding the result to the second phase: Check Mark X (f ) (∅, f, TreesX (∅, f )). If this function does not fail then we say that µ µ µX. . .f passed the check:

For filters that are not recursive at toplevel it suffices to add a dummy recursion: Check(f

Theorem 16 (Termination). If Check(f ) then the type inference algorithm terminates for f on every input type t.

In order to prove the theorem above we need some auxiliary definitions:

Definition 17 (Plinth [START_REF] Frisch | Théorie, conception et réalisation d'un langage de programmation fonctionnel adapté à XML[END_REF]). A plinth ⊂ Types is a set of types with the following properties:

• is finite We define the plinth of t, noted (t), as the smallest plinth containing t.

Intuitively, the plinth of t is the set of types that can be obtained by all possible boolean combination of the subtrees of t. Notice that (t) is always defined since our types are regular: they have finitely many distinct subtrees, which (modulo type equivalence) can thus be combined in finitely many different ways.

Definition 18 (Extended plinth and support). Let t be a type and f a filter. The extended plinth of t and f , noted ˆ (f, t) is defined as (t ∨ v⊑f v) (where v ranges over values).

The support of t and f , noted as Support(f, t), is defined as

The extended plinth of t and f is the set of types that can be obtained by all possible boolean combination of the subtrees of t and of values that occur in the filter f . The intuition underlying the definition of support of t and f is that it includes all the possible types of arguments of recursive calls occurring in f , when f is applied to an argument of type t.

Lastly, let us prove the following technical lemma:

Lemma 19. Let f be a filter such that Check(f ) holds. Let t be a type. For every derivation D (finite or infinite) of Γ ;∆ ;M ⊢fil f (t) : s , for every occurrence of the rule [FIL-CALL-NEW]

Proof. By contradiction. Suppose that there exists an instance of the rule for which x ∈ vars(a) ∧ x / ∈ ˆ (f, t). This means that Γ ′ (x) is neither a singleton type occurring in f nor a type obtained from t by applying left projection, right projection or label selection (⋆). But since Check(f ) holds, x must be bound to either an identifier or a value v (see Figure 4) during the computation of Check Mark X (f ) (∅, f, TreesX (∅, f )). Since identifiers in Check(f ) are only introduced for the input parameter or when performing a left projection, right projection or label selection of another identifier, this ensure that x is never bound to the result of an expression whose type is not in ˆ (f, t), which contradicts (⋆).

We are now able to prove Theorem 16. Let t be a type and f a filter define

Notice that since Support(f, t) is finite and there are finitely many different recursion variables occuring in a filter, then D(f, t) is finite, too. Now let f and t be the filter and type mentioned in the statement of Theorem 16 and consider the (possibly infinite) derivation of Γ ;∆ ;M ⊢fil f (t) : s. Assign to every judgment

where |S| denotes the cardinality of the set S (notice that in the definition S is finite), dom(M ′ ) is the domain of M ′ , that is, the set of pairs (X, t) for which M ′ is defined, and size(f ′ ) is the depth of the syntax tree of f ′ .

Notice that the set of all weights lexicographically ordered form a well-founded order. It is then not difficult to prove that every application of a rule in the derivation of Γ ;∆ ;M ⊢fil f (t) : s strictly decreases Wgt, and therefore that this derivation must be finite. This can be proved by case analysis on the applied rule, and we must distinguish only three cases:

[FIL-FIX] Notice that in this case the first component of Wgt either decreases or remains constant, and the second component strictly decreases.

[FIL-CALL-NEW] In this case Lemma 19 ensures that the first component of the Wgt of the premise strictly decreases. Since this is the core of the proof let us expand the rule. Somewhere in the derivation of Γ ;∆ ;M ⊢fil f (t) : s we have the following rule:

Γ ′ ;∆ ′ ;M ′ ⊢fil (Xa)(s) : µ µ µT. . .t ′ and we want to prove that (D(f, t) \ dom(M ′ )) (D(f, t) \ (dom(M ′ ) ∪ (X, t ′′ )) and the containment must be strict to ensure that the measure decreases. First of all notice that (X, t ′′ ) ∈ dom(M ′ ), since it is a side condition for the application of the rule. So in order to prove that containment is strict it suffices to prove that (X, t ′′ ) ∈ D(t, f ). But this is a consequence of Lemma 19 which ensures that t ′′ ∈ Support(f, t), whence the result.

[FIL-*] With all other rules the first component of Wgt remains constant, and the second component strictly decreases.

A.1 Improvements

Although the analysis performed by our algorithm is already fine grained, it can be further refined in two simple ways. As explained in Section 4, the algorithm checks that after one step of reduction the capture variables occurring in recursive calls are bound to subtrees of the initial input type. So a possible improvement consists to try to check this property for a higher number of steps, too. For instance consider the filter: ( ('nil,,,( ( (y,,,y)

This filter does not pass our analysis since if ιy is the identifier bound to the capture variable y, then when unfolding the recursive call in the second branch the x in the first recursive call will be bound to ( ( (ιy, , ,ιy) ) ). But if we had pursued our abstract execution one step further we would have seen that ( ( (ιy, , ,ιy) ) ) is not used in a recursive call and, thus, that type inference terminates. Therefore, a first improvements is to modify Check() so that it does not stop A second and, in our opinion, more promising improvement is to enhance the precision of the test ⌉ ⌉ ⌉A⌈ ⌈ ⌈& & & f = ∅ in the definition of Check, that verifies whether the filter f fails on the given symbolic argument A. In the current definition the only information we collect about the type of symbolic arguments is their structure. But further type information, currently unexploited, is provided by patterns. For instance, in the following (admittedly stupid) filter

if in the first pass we associate y with ιy, then we know that ( ( (ιy, , ,ιy) ) ) has type ( ( (int, , ,int) ) ). If we record this information, then we know that in the second pass ( ( (ιy, , ,ιy) ) ) will always match the first pattern, and so it will never be the argument of a further recursive call. In other words, there is at most one nested recursive call. The solution is conceptually simple (but yields a cumbersome formalization, which is why we chose the current formulation) and amounts to modify Trees(,) so that when it introduces fresh variables it records their type information with them. It then just suffices to modify the definition of ⌉ ⌉ ⌉A⌈ ⌈ ⌈ so as it is obtained from A by replacing every occurrence of a variable identifier by its type information (rather than by any) and the current definition of Check() will do the rest.

B. Proof of Turing completeness (Theorem 7)

In order to prove Turing completeness we show how to define by filters an evaluator for untyped (call-by-value) λ-calculus. If we allowed recursive calls to occur on the left-hand side of composition, then the encoding would be straightforward: just implement β and context reductions. The goal however is to show that the restriction on compositions does not affect expressiveness. To that end we have to avoid context reductions, since they require recursive calls before composition. To do so, we first translate λ-terms via Plotkin's call-by-value CPS translation and apply Steele and Rabbit's administrative reductions to them obtaining terms in λcps. The latter is isomorphic to cbv λ-calculus (see for instance [START_REF] Sabry | A reflection on call-by-value[END_REF]) and defined as follows.

with the following reduction rules (performed at top-level, without any reduction under context).

In order to prove Turing completeness it suffices to show how to encode λcps terms and reductions in our calculus. For the sake of readability, we use mutually recursive types (rather than their encoding in µ-types), we use records (though pairs would have sufficed), we write just the recursion variable X for the filter x -> Xx, and use ¬t to denote the type any\t. Term productions are encoded by the recursive types given at the beginning of Figure 5.

Next we define the evaluation filter Eval. In its body it calls the filter Subst[c,F] which implements the capture free substitution and, when c denotes a constant, is defined as right below.

It is straightforward to see that the definitions in Figure 5 implement the reduction semantics of CPS terms. Of course the definition above would not pass our termination condition. Indeed while Subst would be accepted by our algorithm, Eval would fail since it is not possible to ensure that the recursive calls of Eval will receive from Subst subtrees of the original input type. This is expected: while substitution always terminate they may return trees that are not subtrees of the original term.

C. Proof of subject reduction (Theorem 13)

We first give the proof of Lemma 9, which we restate:

Let f be a filter and v be a value such that v / ∈ f . Then for every γ, δ, if δ;γ ⊢eval f (v) r, r ≡ Ω.

Proof. By induction on the derivation of δ;γ ⊢eval f (v) r, and case analysis on the last rule of the derivation:

(expr): here, e = any for any expression e, therefore this rule cannot be applied (since ∀v, v ∈ any). (prod): assume v / ∈ ( ( (f1,f2) ) ) ≡ ( ( ( f1 , , , f2 ) ) ). then either v / ∈ ( ( (any, , ,any) ) ), in which case only rule (error) applies and therefore r ≡ Ω. Or v ≡ (v1, v2) and v1 / ∈ f1 . Then by induction hypothesis on the first premise, δ;γ ⊢eval f1(v1) r1 and r1 ≡ Ω, which contradicts the side condition r1 = Ω (and We were a little bit sloppy in the notation and used a filter parameter as a pattern. Strictly speaking this is not allowed in filters and, for instance, the branch { var : c } -> F in Subst should rather be written as { var : y } -> ( (y=c); (true -> F | false -> { var : y }) ). Similarly, for the other two cases. We are now equipped to prove the subject reduction theorem which we restate in a more general manner:

For every Γ, ∆, M , γ, δ such that ∀x ∈ dom(γ), x ∈ dom(Γ) ∧ γ(x) : Γ(x), if Γ ;∆ ;M ⊢fil f (t) : s, then for all v : t, δ;γ ⊢eval f (v) r implies r : s. The proof is by induction on the derivation of δ;γ ⊢eval f (v) r, and by case analysis on the rule. Beside the basic case, the only rules which are not a straightforward application of induction are the rules union1 and union2 that must be proved simulatneously. Other cases being proved by a direct application of the induction hypothesis, we only detail the case of the product constructor.

(expr): we suppose that the host languages enjoys subject reduction, hence e(v) = r : s.

(prod): Here, we know that t ≡ i≤rank(t) (t i 1 , t i 2 ). Since v is a value, and v : t, we obtain that v ≡ (v1, v2). Since (v1, v2) is a value, ∃i ≤ rank(t) such that (v1, v2) : (t i 1 , t i 2 ). The observation that v is a value is crucial here, since in general given a type t ′ ≤ t with t

) ≤ (t1 i , t2 i ). However this property holds for singleton types and therefore for values. We have therefore that v1 : t i 1 and v2 : t i 1 . Furthermore, since we suppose that a typing derivation exists and the typing rules are syntax directed, then Γ ;∆ ;M ⊢fil f (t i 1 ) : s i 1 must be a used to prove our typing judgement. We can apply the induction hypothesis and deduce that δ;γ ⊢eval f (v1) r1 and similarly for v2. We have therefore that the filter evaluates to (r1, r2) which has type (s i 1 , s i 2 ) ≤ j≤rank(s) (s1 i , s2 i ) which proves this case. Ω (case union2) and we can apply the induction hypothesis on the second premise, which gives us δ;γ ⊢eval f (v1) r2 which allows us to conclude.

(error): this rule can never occur. Indeed, if v : t and Γ ;∆ ;M ⊢fil f (t) : s, that means in particular that t ≤ f and therefore that all of the side conditions for the rules prod, pat and recd hold.

D. Complexity of the typing algorithm

Proof. For clarity we restrict ourselves to types without record constructors but the proof can straihgtforwardly be extended to them. First remark that our types are isomorphic to alternating tree automata (ATA) with intersection, union and complement (such as those defined in [START_REF] Comon | Tree automata techniques and applications[END_REF][START_REF] Hosoya | Foundations of XML Processing: The Tree Automata Approach[END_REF]). From such an ATA t it is possible to compute a non-deterministic tree automaton t ′ of size O(2 |t| ).

When seeing t ′ in our type formalism, it is a type generated by the following grammar: where b ranges over negation and intersections of basic types. Intuitively each recursion variable X is a state in the NTA, a finite union of products is a set of non-deterministict transitions whose right-hand-side are each of the products and atom productions are leaf-states. Then it is clear than if Check(f ) holds, the algorithm considers at most |f | × |t ′ | distinct cases (thanks to the memoization set M ). Furthermore for each rule, we may test a subtyping problem (eg, t ≤ f ), which itself is EXPTIME thus giving the bound

E. Precise typing of groupby

The process of inferring a precise type for groupby f (t) is decomposed in several steps. First we have to compute the set D(f ) of discriminant domains for the filter f . The idea is that these domains are the types on which we know that f may give results of different types. Typically this corresponds to all possible branchings that the filter f can do. Recall that we are trying to deduce a type for groupby f (t), that is for the expression groupby f when applied to an argument of type t. Which types shall we use as input for our filter f to compute the type of the intermediate result? Surely we want to have all the