Intersection Types and Counting∗ Paweł Parys UniversityofWarsaw,Poland [email protected] We present a new approachto the following meta-problem: given a quantitative propertyof trees, 7 design a type system such that the desired property for the tree generated by an infinitary ground 1 l -termcorrespondstosomepropertyofaderivationofatypeforthisl -term,inthistypesystem. 0 Ourapproachispresentedintheparticularcaseofthelanguagefinitenessproblemfornondeter- 2 ministichigher-orderrecursionschemes(HORSes):givenanondeterministicHORS,decidewhether n thesetofallfinitetreesgeneratedbythisHORSisfinite. WegiveatypesystemsuchthattheHORS a J can generate a tree of an arbitrarily large finite size if and only if in the type system we can ob- 9 tain derivationsthat are arbitrarilylarge, in an appropriatesense; the latter conditioncan be easily 1 decided. ] O 1 Introduction L s. Inthispaperweconsider l Y-calculus, whichisanextension ofthesimply typedl -calculus byafixed- c point operator Y. A term P of l Y-calculus that is of sort1 o can be used to generate an infinite tree [ BT(P), called the Böhm tree of P. Trees generated by terms of l Y-calculus can be used to faithfully 1 v represent the control flow of programs in languages with higher-order functions. Traditionally, Higher 3 OrderRecursiveSchemes(HORSes)areusedforthispurpose[8,12,17,16];thisformalismisequivalent 0 to l Y-calculus, and the translation between them is rather straightforward [21]. Collapsible Pushdown 3 5 Systems[10]andOrderedTree-PushdownSystems[7]areotherequivalent formalisms. 0 Intersection type systems were intensively used in thecontext ofHORSes,forseveral purposes like . 1 model-checking [13, 16, 5, 20], pumping [14], transformations of HORSes [15, 6], etc. Interestingly, 0 constructions verysimilar tointersection types were used also on theside of collapsible pushdown sys- 7 1 tems;theywerealternating stackautomata[4],andtypesofstacks[19,11]. : In this paper we show how intersection types can be used for deciding quantitative properties of v i trees generated by l Y-terms. We concentrate on the language finiteness problem for nondeterministic X HORSes: given a nondeterministic HORS, decide whether the set of all finite trees generated by this r a HORSisfinite. This problem can be restated in the world of l Y-terms (or standard, deterministic HORSes), gen- erating a single infinite tree. Here, instead of resolving nondeterministic choices during the generation process, we leave them in the resulting tree. Those nondeterministic choices are denoted by a distin- guished br(“branch”) symbol,belowwhichweputoptions thatcouldbechosen. Thentoobtainafinite treegeneratedbytheoriginalHORSwejustneedtorecursivelychooseineverybr-labelednodewhichof thetwosubtreeswewanttoconsider. Thus,inthissetting,thelanguagefinitenessproblemaskswhether thesetofallfinitetreesobtained thiswayisfinite. The difficulty of this problem lies in the fact that sometimes the same finite tree may be found in infinitely many different places of BT(P) (i.e., generated by a nondeterministic HORS in many ways); ∗WorksupportedbytheNationalScienceCenter(decisionDEC-2012/07/D/ST6/02443). 1Weusetheword“sort”insteadoftheusual“type”toavoidconfusionwithintersectiontypesintroducedinthispaper. (cid:13)c P.Parys Submittedto: Thisworkislicensedunderthe ITRS2016 CreativeCommonsAttributionLicense. 2 IntersectionTypesandCounting thustheactualproperty todecideiswhetherthereisacommonboundonthesizeofeachofthesetrees. This makes the problem inaccessible for standard methods used for analyzing HORSes,as they usually concernonlyregularpropertiesoftheBöhmtree,whileboundedness isaproblemofdifferentkind. The same difficulty was observed in [14], where they prove a pumping lemma for deterministic HORSes, whileadmitting(Remark2.2)thattheirmethodistooweaktoreasonaboutnondeterministic HORSes. Inordertosolvethelanguagefinitenessproblem,wepresentanappropriateintersectiontypesystem, where derivations are annotated by flags and markers of multiple kinds. The key property of this type systemisthatthenumberofflagsinatypederivationforal Y-termPapproximatesthesizeofsomefinite treeobtained byresolving nondeterministic choicesintheinfinitetreeBT(P). Inconsequence, thereare typederivationsusingarbitrarilymanyflagsif,andonlyif,theanswertothelanguagefinitenessproblem is“no”. Thelanguagefinitenessproblemwasfirstattackedin[1](forsafeHORSesonly),buttheiralgorithm turned outtobeincorrect [2]. Toourknowledge, theonly knownsolution ofthisproblem follows from arecent decidability resultforthediagonal problem [9,6]. Thisproblem asks, givenanondeterministic HORS and a set of letters S , whether for every n∈N the HORS generates a finite tree in which every letterfromS appears atleastntimes. Clearly, anondeterministic HORSgenerates arbitrarily largetrees exactly when for some letter a itgenerates trees having arbitrarily many aletters, i.e., when the answer tothediagonalproblem forS ={a}is“yes”. Ourtypesystem is,tosomeextent, motivated bythealgorithm of[6]solving thediagonal problem. Thisalgorithm worksbyrepeating twokinds oftransformations ofHORSes. Thefirstofthemturns the HORSintoaHORSgeneratingtreeshavingonlyafixednumberofbranches, onepereachletterfromS (i.e., one branch inour case of|S |=1). Thebranches arechosen nondeterministically out ofsometree generatedbytheoriginalHORS;foreverya∈S thereisachoicewitnessingthataappearedmanytimes inthe original tree. Thensuch aHORSofthe special form isturned intoaHORSthatisoforder lower byone,andgeneratestreeshavingthesamenodesastreesgeneratedbytheoriginalHORS,butarranged differently (in particular, the new trees may have again arbitrarily many branches). After finitely many repetitions of this procedure, a HORSof order 0 is obtained, and the diagonal problem becomes easily decidable. In some sense wewant to do the same, but instead ofapplying all these transformations one by one, we simulate all of them simultaneously in a single type derivation. In this derivation, for each order n, we allow to place arbitrarily one marker “of order n”; this corresponds to the nondeterministic choice of one branch in the n-th step of the previous algorithm. We also place some flags “of order n”, inplacesthatcorrespond tonodesremainingafterthen-thstepofthepreviousalgorithm. The idea of using intersection types for counting is not completely new. Paper [18] presents a type system that, essentially, allows to estimate the size of the b -normal form of al -term just by looking at (the number of some flags in) a derivation of a type for this term. A similar idea, but for higher-order pushdown automata, is present in [19], where we can estimate the number of ♯ symbols appearing on a particular, deterministically chosenbranchofthegeneratedtree. Thispreviousapproach alsousesinter- sectiontypes,wherethederivationsaremarkedwithjustonekindofflags,denoting“productive” places of al -term (oppositely toour approach, where wehave different flagsfor different orders, and wealso havemarkers). Thetroublewiththe“one-flag”approachisthatitworkswellonlyinacompletelydeter- ministicsetting,wherelookingindependently ateachnodeoftheBöhmtreeweknowhowitcontributes to the result; the method stops working (or at least we do not know how to prove that it works) in our situation,wherewefirstnondeterministically performsomeguessesintheBöhmtree,andonlyafterthat wewanttocountsomethingthatdepends onthechosen values. P.Parys 3 Acknowledgements. IwouldliketothankSzymonTorun´czykforstimulatingdiscussions, andanony- mousreviewersforusefulcomments. 2 Preliminaries Trees. Let S be a ranked alphabet, i.e., a set of symbols together with a rank function assigning a nonnegative integer to each of the symbols. We assume that S contains a distinguished symbol br of rank 2, used to denote nondeterministic choices. A S -labeled tree is a tree that is rooted (there is a distinguished rootnode),node-labeled(everynodehasalabelfromS ),ranked(anodewithlabelofrank nhasexactlynchildren), andordered(children ofanodeofranknarenumberedfrom1ton). When t is a S -labeled tree t, by L(t) we denote the set of all finite trees that can be obtaining by choosing in every br-labeled node of t which of the two subtrees we want to consider. More formally, weconsider the following relation →br: wehavet →br uif ucan beobtained fromt by choosing int a br-labelednodexanditschildy,andreplacingthesubtreestartinginxbythesubtreestartinginy(which removes x and the other subtree of x). Let →∗br be the reflexive transitive closure of →br. Then L(t) contains alltreesuthatdonotusethebrlabel,arefinite,andsuchthatt →∗ u. br Infinitary l -calculus. The set of sorts (a.k.a. simple types), constructed from a unique basic sort o using a binary operation →, is defined as usual. The order of a sort is defined by: ord(o) = 0, and ord(a →b )=max(1+ord(a ),ord(b )). We consider infinitary, sorted l -calculus. Infinitary l -terms (or just l -terms) are defined by coin- duction, according tothefollowingrules: • ifa∈S isasymbolofrankr,andPo,...,Po arel -terms,then(aPo...Po)o isal -term, 1 r 1 r • foreverysorta thereareinfinitelymanyvariablesxa ,ya ,za ,...;eachofthemisal -term, • ifPa →b andQa arel -terms,then(Pa →b Qa )b isal -term,and • ifPb isal -termandxa isavariable, then(l xa .Pb )a →b isal -term. Wenaturally identify l -terms differing only in names ofbound variables. Weoften omitthe sort anno- tations of l -terms, but we keep in mind that every l -term (and every variable) has a particular sort. A l -termPisclosedifithasnofreevariables. Noticethat,fortechnicalconvenience, asymbolofpositive rankisnotal -termitself, butalwayscomeswitharguments. Thisisnotarestriction, sincee.g.instead ofaunarysymbolaonemayusetheterml x.ax. Theorderofal -termisjusttheorderofitssort. Thecomplexityofal -termPisthesmallestnumber msuchthattheorderofeverysubtermofPisatmostm. Werestrictourselvestol -termsthathavefinite complexity. A b -reduction is defined as usual. We say that a b -reduction P→b Q is of order n if it concerns a redex (l x.R)S such that ord(l x.R)=n. In this situation the order of x is at most n−1, but may be smaller(whenotherarguments ofRareofordern−1). BöhmTrees. Weconsider Böhm trees only for closed l -terms ofsort o. Forsuch aterm P, its Böhm tree BT(P)isconstructed bycoinduction, asfollows: ifthere isasequence of b -reductions from Ptoa l -termoftheformaP ...P (whereaisasymbol),thentherootofthetreet haslabelaandrchildren, 1 r and the subtree starting in the i-th child is BT(P). If there is no sequence of b -reductions from P to a i 4 IntersectionTypesandCounting l -termoftheaboveform,thenBT(P)isthefullbinarytreewithallnodes labeledbybr.2 ByL(P)we denoteL(BT(P)). l Y-calculus. Thesyntax ofl Y-calculus isthesameasthatoffinitel -calculus, extended bysymbols Y(a →a )→a , for each sort a . A term of l Y-calculus is seen as a term of infinitary l -calculus if we replace each symbolY(a →a )→a bythe unique infinite l -term Z such that Z issyntactically the same as l xa →a .x(Zx). Inthisway,weviewl Y-calculus asafragmentofinfinitaryl -calculus. It is standard to convert a nondeterministic HORS G into a closed l Y-term Po such that L(P) is exactlythesetofallfinitetreesgenerated byG. Thefollowingtheorem, whichisourmainresult, states thatthelanguage finiteness problem isdecidable. Theorem1. Givenaclosedl Y-termPofsorto,onecandecidewhetherL(P)isfinite. 3 Intersection Type System In this section we introduce a type system that allows to determine the desired property: whether in L(P)thereisanarbitrarily largetree. Intuitions. Themainnoveltyofourtypesystem isinusingflagsandmarkers, whichmaylabelnodes ofderivation trees. Toeveryflagandmarkerweassignanumber, calledanorder. Whilederiving atype for a l -term of complexity m, we may place in every derivation tree at most one marker of each order n∈{0,...,m−1},andarbitrarily manyflagsofeachordern∈{0,...,m}. Consider first a l -term M of complexity 0. Such a term actually equals its Böhm tree. Our aim is 0 todescribe somefinitetreet inL(M ),i.e.,obtained fromM byresolving nondeterministic choices in 0 0 some way. Wethus just put flags of order 0 in all those (appearances of) symbols in M that contribute 0 to this tree t; the type system ensures that indeed all symbols of some finite tree in L(M ) are labeled 0 byaflag. Thenclearlywehavethedesired property thatthereisaderivation witharbitrarily manyflags if,andonlyif,therearearbitrarily largetreesinL(M ). 0 Next, consider a l -term M that is of complexity 1, and reduces to M . Of course every finite tree 1 0 fromL(M )iscomposedofsymbolsappearingalreadyinM ;wecanthusalreadyinM label(byorder- 0 1 1 0 flags) all symbols that contribute to some treet ∈L(M ) (and an intersection type system can easily 0 checkcorrectness ofsuchlabeling). Thereis,however,oneproblem: asingleappearance ofasymbolin M may result in many appearances in M (since a function may use its argument many times). Due to 1 0 this, the number of order-0 flags in M does not correspond to the size oft. We rescue ourselves in the 1 following way. Int wechoose one leaf, welabel it by an order-0 marker, and on the path leading from the root to this marker we place order-1 flags. On the one hand, L(M ) contains arbitrarily large trees 0 if, andonly if, itcontains trees witharbitrarily long paths, i.e.,trees witharbitrarily manyorder-1 flags. On the other hand, we can perform the whole labeling (and the type system can check its correctness) already in M , and the number of order-1 flags in M will be precisely the same as it would be in M . 1 1 0 Indeed, inM wehave only order-1 functions, i.e., functions that take trees and use them assubtrees of 1 largertrees;althoughatreecomingasanargumentmaybeduplicated, theorder-0markercanbeplaced inatmostonecopy. Thismeansthat,whilereducingM toM ,everysymbolofM canresultinatmost 1 0 1 2Usuallyoneusesaspeciallabel⊥ofrank0forthispurpose,butfromtheperspectiveofourproblembothdefinitionsare equivalent. P.Parys 5 one symbol of M lying on the selected path to the order-0 marker (beside of arbitrarily many symbols 0 outside ofthispath). ThisprocedurecanberepeatedforM ofcomplexity2thatreducestoM viab -reductionsoforder2 2 1 (andsoonforhigherorders). Wenowplaceamarkeroforder1insomeleafofM ;afterwards,weplace 1 anorder-2flagineverynodethatisonthepathtothemarkedleaf,andthathasachildoutsideofthispath whose some descendant is labeled by an order-1 flag. In effect, for some choice ofa leaf to bemarked, the number of order-2 flags approximates the number of order-1 flags, up to logarithm. Moreover, the wholelabeling canbedoneinM insteadofinM ,withoutchanging thenumberoforder-2 flags. 2 1 Inthisintuitivedescriptionwehavetalkedaboutlabeling“nodesofal -term”,butformallywelabel nodes ofaderivation treethat derives atype fortheterm, inourtype system. Everysuch node contains atypejudgmentforsomesubterm oftheterm. Type Judgments. For every sort a we define the set T a of types of sort a , and the set Fa of full typesofsorta . Thisisdoneasfollows,whereP denotes thepowerset: T a →b =P(Fa )×T b , T o=o, ord(a →b ) Fa ={(k,F,M,t )|F,M⊆{0,...,k−1},F∩M=0/,t ∈T a }, Fa = Fa . k k k[∈N Notice that the sets T a and Fa are finite (unlike Fa ). A type (T,t )∈T a →b is denoted asT→t . A k full type tˆ =(k,F,M,t )∈Fa consists of its order k, a set F of flag orders, a set M of marker orders, k andatypet ;wewriteord(tˆ)=k. Inordertodistinguish typesfromfulltypes,thelatteraredenotedby letterswithahat,liketˆ. A type judgment is of the form G ⊢P:tˆ⊲c, where G , called a type environment, is a function that maps every variable xa to a subset of Fa , P is a l -term, tˆ is a full type of the same sort as P (i.e., tˆ∈Fb whenPisofsortb ),andc∈N. Asusualforintersectiontypes,theintuitivemeaningofatypeT→t isthatal -termhavingthistype canreturnal -termhaving typet ,whiletakinganargument forwhichwecanderiveallfulltypesfrom T. Moreover, in T o there isjust one type o, which can be assigned to every l -term ofsort o. Suppose thatwehavederivedatypejudgmentG ⊢P:tˆ⊲cwithtˆ=(m,F,M,t ). Then • t isthetypederivedforP; • G contains fulltypesthatcouldbeusedforfreevariablesofPinthederivation; • m bounds the order of flags and markers that could be used in the derivation: flags could be of orderatmostm,andmarkersoforderatmostm−1; • M⊆{0,...,m−1}contains theordersofmarkersusedinthederivation, togetherwiththosepro- videdbyfreevariables (i.e.,weimaginethatsomederivations, specifiedbythetypeenvironment, are already substituted in our derivation for free variables); we, however, do not include markers providedbyarguments oftheterm(i.e.,comingfromthesetsT whent =T →...→T →o); i 1 k • F containsthosenumbersn∈{0,...,m−1}(excludingn=m)forwhichaflagofordernisplaced in the derivation itself, or provided by a free variable, or provided by an argument; for technical convenience we,however,removenfromF whenevern∈M (whenn∈M,theinformation about order-nflagsresults inplacinganorder-(n+1)flag,andneednottobefurtherpropagated); • c,calledaflagcounter, countsthenumberoforder-m flagspresent inthederivation. 6 IntersectionTypesandCounting TypeSystem. Beforegivingrulesofthetypesystem,weneedafewdefinitions. Weusethesymbol⊎ todenotedisjoint union. WhenA⊆Nandn∈N,wewriteA↾ for{k∈A|k<n},andsimilarlyA↾ <n ≥n for{k∈A|k≥n}. Bye wedenotethetypeenvironment mappingeveryvariableto0/,andbyG [x7→T] thetypeenvironment mappingxtoT andeveryothervariableytoG (y). Letusnow sayhowatype environment G fromtheconclusion ofarule maybesplit intotype envi- ronments(G ) usedinpremissesoftherule: wesaythatSplit(G |(G ) )holdsifandonlyifforevery i i∈I i i∈I variable x it holds G (x)⊆G (x) for every i∈I, and every full type from G (x) providing some markers i (i.e.,(k,F,M,t )withM6=0/)appears insomeG (x). FulltypeswithemptyM maybediscarded anddu- i plicatedfreely. ThisdefinitionforbidstodiscardfulltypeswithnonemptyM,andfromelsewhereitwill follow that they cannot be duplicated. Asa special case Split(G |G ′) describes how atype environment canbeweakened. All type derivations are assumed to be finite (although we derive types mostly for infinite l -terms, each type derivation analyzes only a finite part of a term). Rules of the type system will guarantee that theordermofderivedfulltypeswillbethesameinthewholederivation(althoughintypeenvironments theremaybefulltypesofdifferentorders). Wearereadytogivethefirstthreerulesofourtypesystem: G ⊢P :tˆ⊲c i∈{1,2} Split(G |e [x7→{(k,F,M′,t )}]) M↾ =M′ i <k (BR) (VAR) G ⊢brP P :tˆ⊲c G ⊢x:(m,F,M,t )⊲0 1 2 G ′[x7→T]⊢P:(m,F,M,t )⊲c Split(G |G ′) G ′(x)=0/ (l ) G ⊢l x.P:(m,F,M\ (k,F′,M′,s )∈TM′,T→t )⊲c [ Weseethattoderiveatypeforthenondeterministic choicebrP P ,weneedtoderiveiteitherforP 1 2 1 orforP . 2 The(VAR) ruleallowstohaveintheresulting setM somenumbersthatdonotcomefromthesetM′ assigned toxbythe typeenvironment; these arethe orders ofmarkers placed inthe leaf using this rule. Notice, however, that weallow here only orders not smaller than k (which isthe order of the superterm l x.P binding this variable x). This is consistent with the intuitive description of the type system (page 4), which says that a marker of order n can be put in a place that will be a leaf after performing all b - reductionsofordersgreaterthann. Indeed,thevariablexremainsaleafafterperformingb -reductionsof ordersgreaterthank,butwhileperformingb -reductionsoforderkthisleafwillbereplacedbyasubterm substituted for x. Recall also that, by definition of a type judgment, we require that (k,F,M′,t )∈Fa k and (m,F,M,t )∈Fa , for appropriate sort a ; this introduces a bound on maximal numbers that may m appearinthesetsF andM. Example1. Denotingrˆ =(1,0/,{0},o) wecanderive: 1 (VAR) (VAR) e [x7→{rˆ }]⊢x:(2,0/,{0},o)⊲0 e [x7→{rˆ }]⊢x:(2,0/,{0,1},o)⊲0 1 1 Inthederivationontheright,themarkeroforder1isplacedintheconclusion oftherule. The (l ) rule allows to use (in a subderivation concerning the l -term P) the variable x with all full types given in the set T. When the sort of l x.P is a →b , by definition of T a →b we have that all full typesinT havethesameorderk=ord(a →b )(since(T→t )∈T a →b ). Recallthatweintendtostorein thesetMthemarkerscontainedinthederivationitselfandthoseprovidedbyfreevariables,butnotthose provided by arguments. Because of this, in the conclusion of the rule we remove from M the markers provided by x. This operation makes sense only because there is at most one marker of each order, so P.Parys 7 markers provided by x cannot be provided by any other free variable nor placed in the derivation itself. ThesetF,unlikeM,storesalsoflagsprovidedbyarguments,sowedonotneedtoremoveanythingfrom F. Example2. The(l )rulecanbeused,e.g.,inthefollowingway(whereaisasymbolofrank1): e [x7→{rˆ }]⊢ax:(2,{1},{0},o)⊲0 e [x7→{rˆ }]⊢ax:(2,0/,{0,1},o)⊲1 1 (l ) 1 (l ) e ⊢l x.ax:(2,{1},0/,{rˆ }→o)⊲0 e ⊢l x.ax:(2,0/,{1},{rˆ }→o)⊲1 1 1 Notice that in the conclusion of the rule, in both examples, weremove 0 from the set of marker orders, because theorder-0markerisprovidedbyx. Thenexttworules useapredicate Comp ,saying howflagsandmarkersfrom premisses contribute m to the conclusion. It takes “as input” pairs (F,c) for i ∈ I; each of them consists of the set of flag i i orders F and of the flag counter c from some premiss. Moreover, the predicate takes a set of marker i i orders M fromthecurrent typejudgment (itcontains ordersofmarkersusedinthederivation, including those provided by free variables). The goal is to compute the set of flag orders F and the flag counter c that should be placed in the current type judgment. First, for each n∈{1,...,m} consecutively, we decidewhetheraflagofordernshouldbeplacedonthecurrenttypejudgment. Wefollowheretherules mentioned in the intuitive description. Namely, weplace a flag of order n if weare on the path leading to the marker of order n−1 (i.e., if n−1∈M), and simultaneously we receive an information about a flagofordern−1. Byreceivingthisinformationwemeanthateitheraflagofordern−1wasplacedon the current type judgment, orn−1belongs tosomesetF. Actually, weplace multiple flagsoforder n: i oneper eachflagoforder n−1placed onthecurrent type judgment, andonepereach setF containing i n−1. Then,wecomputeF andc. Incwestorethenumberofflagsofthemaximalorderm: wesumall the numbers c, and we add the number of order-m flags placed on the current type judgment. In F we i keep elements ofall F, and weadd the orders nof flagsthat were placed onthe current type judgment. i We, however, remove from F all elements of M. This is because every flag of some order n−1should result in creating at most one flag of order n, in the closest ancestor that lies on the path leading to the markerofordern−1. Ifwehavecreatedanorder-nflagonthecurrenttypejudgment,i.e.,ifn−1∈M, wedonotwanttodothisagainintheparent. Below we give a formal definition, in which f′ contains the number of order-n flags placed on the n current type judgment, while f additionally counts the number of premisses for which n∈F. We say n i thatComp (M;((F,c)) )=(F,c)when m i i i∈I F ={n∈{0,...,m−1}| f >0∧n6∈M}, c= f′ +(cid:229) c , where,forn∈{0,...,m}, n m i i∈I f = f′+(cid:229) |F ∩{n}|, f′ = fn−1 ifn−1∈M, n n i n (cid:26) 0 otherwise. i∈I Wenowpresentaruleforconstants otherthanbr: G ⊢P :(m,F,M,o)⊲c foreachi∈{1,...,r} M=M′⊎M ⊎···⊎M i i i i i 1 r (m=0)⇒(F′=0/∧c′=1) (m>0)⇒(F′={0}∧c′ =0) (r>0)⇒(M′=0/) a6=br Split(G |G ,...,G ) Comp (M;(F′,c′),(F ,c ),...,(F,c ))=(F,c) 1 r m 1 1 r r (CON) G ⊢aP ...P :(m,F,M,o)⊲c 1 r Here, the conditions in the second line say that in a node using the (CON) rule we always place a flag of order 0 (via F′ or via c′, depending on m), and that if the node is a leaf (i.e., r = 0), then we 8 IntersectionTypesandCounting are allowed to place markers of arbitrary order (via M′). Then to the Comp predicate, beside of pairs m (F,c)comingfrompremisses, wealsopasstheinformation (F′,c′)abouttheorder-0 flagplaced inthe i i current node; this predicate decides whether we should place also some flags of positive orders. Let us emphasize that in this rule (and similarly in the next rule) we have a disjoint union M′⊎M ⊎···⊎M , 1 r whichensures thatamarkerofanyordermaybeplacedonlyinonenodeofaderivation. Example3. The(CON) rulemaybeinstantiated inthefollowingway: e [x7→{rˆ }]⊢x:(2,0/,{0},o)⊲0 e [x7→{rˆ }]⊢x:(2,0/,{0,1},o)⊲0 1 1 (CON) (CON) e [x7→{rˆ }]⊢ax:(2,{1},{0},o)⊲0 e [x7→{rˆ }]⊢ax:(2,0/,{0,1},o)⊲1 1 1 In the left example, flags of order 0 and 1 are placed in the conclusion of the rule (a flag of order 0 is createdbecauseweareinaconstant;sincethemarkeroforder0isvisible,wedonotput0intothesetof flagorders, but instead wecreate aflagof order 1). In the right example, amarker oforder 1is visible, whichcausesthatthistimeflagsoforder0,1,and2areplacedintheconclusionofthe(CON)rule(again, wedonotput0nor1intothesetofflagorders, becauseof0and1inthesetofmarkerorders). Thenextruledescribes application: G ′⊢P:(m,F′,M′,{(ord(P),F↾ ,M↾ ,t )|i∈I}→t )⊲c′ i <ord(P) i <ord(P) i G ⊢Q:(m,F,M,t )⊲c foreachi∈I M=M′⊎ M i i i i i i∈I i ord(P)≤m Split(G |G ′,(G ) ) Comp (M;(F′,c′),((F↾ ] ,c)) )=(F,c) i i∈I m i ≥ord(P) i i∈I (@) G ⊢PQ:(m,F,M,t )⊲c In this rule, it is allowed (but in fact useless) that for two different i∈I the full types (m,F,M,t ) i i i are equal. It is also allowed that I = 0/, in which case no type needs to be derived for Q. Observe how flags and markers coming from premisses concerning Q are propagated: only flags and markers of order n < ord(P) are visible to P, while only flags of order n ≥ ord(P) are passed to the Comp m predicate. This can be justified if we recall the intuitions staying behind the type system (see page 4). Indeed,whileconsidering flagsandmarkersofordern,weshouldimaginethel -termobtainedfromthe current l -term by performing all b -reductions of all orders greater than n; the distribution of flags and markers of order n in the current l -term actually simulates their distribution in this imaginary l -term. Thus,ifn<ord(P),thenourapplication willdisappear inthisimaginary l -term,andQwillbealready substituted somewhere in P; for this reason weneed to pass the information about flagsand markers of ordernfromQtoP. Conversely, ifn≥ord(P),thenintheimaginaryl -termtheconsidered application will be still present, and in consequence the subterm corresponding to P will not see flags and markers ofordernplacedinthesubtermcorresponding toQ. Example4. Denotebytˆf andtˆm thetypesderivedinExample2: tˆf =(2,{1},0/,{rˆ1}→o), and tˆm=(2,0/,{1},{rˆ1}→o). Then,usingthe (@) rule,wecanderive(whereeisasymbolofrank0,and f avariable): (VAR) (CON) e [f 7→{tˆm}]⊢ f :tˆm⊲0 e ⊢e:(2,{1},{0},o)⊲0 (@) e [f 7→{tˆf,tˆm}]⊢ fe:(2,0/,{0,1},o)⊲1 Recall that rˆ =(1,0/,{0},o). In the conclusion of the (@) rule the information about a flag of order 1 1 (fromthesecondpremiss)meetstheinformationaboutthemarkeroforder1(fromthefirstpremiss),and P.Parys 9 thus aflag oforder 2 isplaced, which increases the flag counter. Notice that wehave discarded the full type tˆf assigned to f in the type environment; this is allowed because tˆf provides no markers (equally well tˆf could be assigned to f also in one or two of the premisses, and discarded there). On the other hand,thefulltypetˆm providesmarkers,soitcannotbediscardednorduplicated (inparticular, wecould notpassittotheconclusion ofthe (CON) rule). Thekeyproperty ofthetypesystem isdescribed bythefollowingtheorem. Theorem 2. Let P be a closed l -term of sort o and complexity m. Then L(P) is infinite if and only if forarbitrarily largecwecanderivee ⊢P:rˆ ⊲c,whererˆ =(m,0/,{0,...,m−1},o). m m The left-to-right implication of Theorem 2 (completeness of the type system) is shown in Section 4, while the opposite implication (soundness of the type system) in Section 5. In Section 6 we discuss how Theorem 1 follows from Theorem 2. Before all that, we give a few more examples of derivations, illustrating thetypesystemandTheorem2. Example 5. In this example weanalyze the l -term P =R(l x.ax), where Ris defined by coinduction 1 as R=(l f.br(fe)(R(l x.f (fx)))). As previously, a and e are symbols of rank 1 and 0, respectively. In L(P ) there are trees that consist of a branch of a symbols ended with an e symbol, but only those 1 wherethenumberofasymbolsis2k forsomek∈N. NoticethatthecomplexityofP is2. 1 Continuing Example4,wederivethefulltypesˆR=(2,0/,{0},{tˆf,tˆm}→o)forR: e [f 7→{tˆf,tˆm}]⊢ fe:(2,0/,{0,1},o)⊲1 (BR) e [f 7→{tˆf,tˆm}]⊢br(fe)(R(l x.f(fx))):(2,0/,{0,1},o)⊲1 (l ) e ⊢R:sˆ ⊲1 R Next,wederivethesamefulltypeforR,butusingthesecondargumentofthebrsymbol;thisresults ingreatervaluesoftheflagcounter. Westartbyderivingthefulltypetˆf forthesubterm l x.f(fx): e [f 7→{tˆf}]⊢ f :tˆf⊲0 e [x7→{rˆ1}]⊢x:(2,0/,{0},o)⊲0 (@) e [f 7→{tˆf}]⊢ f :tˆf⊲0 e [f 7→{tˆf},x7→{rˆ1}]⊢ fx:(2,{1},{0},o)⊲0 (@) e [f 7→{tˆf},x7→{rˆ1}]⊢ f(fx):(2,{1},{0},o)⊲0 (l ) e [f 7→{tˆf}]⊢l x.f(fx):tˆf⊲0 Intheabovederivationtherearenoflagsnormarkers. Next,wederivetˆm forthesamesubterm: e [f 7→{tˆm}]⊢ f :tˆm⊲0 e [x7→{rˆ1}]⊢x:(2,0/,{0},o)⊲0 (@) e [f 7→{tˆf}]⊢ f :tˆf⊲0 e [f 7→{tˆm},x7→{rˆ1}]⊢ fx:(2,0/,{0,1},o)⊲0 (@) e [f 7→{tˆf,tˆm},x7→{rˆ1}]⊢ f(fx):(2,0/,{0,1},o)⊲1 (l ) e [f 7→{tˆf,tˆm}]⊢l x.f(fx):tˆm⊲1 Belowthelower (@) ruletheinformation about aflagoforder1meetstheinformation aboutthemarker of order 1, and thus a flag of order 2 is placed, which increases the flag counter. We continue with the l -termR: e ⊢R:sˆR⊲c e [f 7→{tˆf}]⊢l x.f(fx):tˆf⊲0 e [f 7→{tˆf,tˆm}]⊢l x.f(fx):tˆm⊲1 (@) e [f 7→{tˆf,tˆm}]⊢R(l x.f(fx)):(2,0/,{0,1},o)⊲c+1 (BR) e [f 7→{tˆf,tˆm}]⊢br(fe)(R(l x.f(fx))):(2,0/,{0,1},o)⊲c+1 (l ) e ⊢R:sˆ ⊲c+1 R 10 IntersectionTypesandCounting In this fragment of a derivation no flag nor marker is placed. In particular, there is no order-2 flag in conclusion ofthe (@) rule,although itssecondpremissprovidesaflagoforder1whilethethirdpremiss provides the marker of order 1. We recall from the definition of the (@) rule that the information about flagsandmarkerscomingfromthearguments isdividedintotwoparts. Numberssmallerthantheorder of the operator (ord(R)=2 in our case) are passed to the operator, while only greater numbers (≥2 in ourcase)contribute increatingnewflagsviatheComppredicate. By composing the above fragments of a derivation, we can derive e ⊢ R : sˆ ⊲c for every c ≥ 1. R RecallthatinExamples1-3wehavederivede ⊢l x.ax:tˆf⊲0ande ⊢l x.ax:tˆm⊲1. Togetherwiththe above,thisallowstoderiveforP thefulltyperˆ =(2,0/,{0,1},o) (appearing inTheorem2): 1 2 e ⊢R:sˆR⊲c e ⊢l x.ax:tˆf⊲0 e ⊢l x.ax:tˆm⊲1 (@) e ⊢P :rˆ ⊲c+1 1 2 Wecannotice acorrespondence betweenaderivation withflagcounter c+1andatreeinL(P)ofsize 2c−1+1. Weremark thatineveryofthese derivations onlythree flagsoforder 0andonlythree flagsof order1arepresent, inthethreenodesusingthe (CON) rule. Example6. Consider asimilar l -term P =R(l x.bxx), whereRisaspreviously, and bisasymbol of 2 rank2. InL(P )wehave,foreveryk∈N,afullbinarytreeinwhicheverybranchconsistof2k symbols 2 bandendswithanesymbol. Thistimeforthesubterml x.bxx weneedtoderivethreefulltypes: tˆ′ =(2,{0},0/,{(1,{0},0/,o)}→o), 0 tˆ′=(2,{1},0/,{(1,{0},0/,o),rˆ }→o), and f 1 tˆm′ =(2,0/,{1},{(1,{0},0/,o),rˆ1}→o). Thelastoneisderivedwithflagcounter1. Noticethattˆ′andtˆ′ neednowtwofulltypesfortheargument f m x; the new one (1,{0},0/,o) describes the subtree that is not on the path to the order-0 marker. Wealso haveanewfulltypetˆ′ thatdescribes theuseofl x.bxx outsideofthepathtotheorder-0marker. 0 Then, similarly as in the previous example, for every c ≥ 1 we can derive e ⊢ R : sˆ′ ⊲c, where R sˆR′ =(2,0/,{0},{tˆ0′,tˆf′,tˆm′ }→o). Again, this allows to derive e ⊢P2 :rˆ2⊲c+1. This time a derivation withflagcounterc+1corresponds toatreeinL(P)ofsize2h−1withh=2c−1+1. Example7. Next,considerthel -termP =R(l x.x). TheonlytreeinL(P )consistsofasingleenode. 3 3 Let us see how the derivation from Example 5 has to be modified. The full type tˆm can still be derived forl x.x(although withflagcounter0now),butinsteadoftˆf wehavetousetˆf′′=(2,0/,0/,{rˆ1}→o)that provides noflagoforder1: (VAR) (VAR) e [x7→{rˆ }]⊢x:(2,0/,{0},o)⊲0 e [x7→{rˆ }]⊢x:(2,0/,{0,1},o)⊲0 1 (l ) 1 (l ) e ⊢l x.x:tˆf′′⊲0 e ⊢l x.x:tˆm⊲0 Next,forRwewanttoderivethefulltypesˆR′′=(2,0/,{0},{tˆf′′,tˆm}→o). Wecaneasilyadoptevery of the previous derivations for e ⊢ R : sˆR⊲c: we basically replace every tˆf by tˆf′′. The key point is that while deriving the full type tˆm for the subterm l x.f(fx), previously in the lower (@) rule wehave received information about an order-1 flag, and thus we have created an order-2 flag and increased the flagcounter;thistimethereisnoinformationaboutanorder-1flag,andthuswedonotcreateanorder-2 flag and do not increase the flag counter. In consequence, even if this part of the derivation is repeated arbitrarily manytimes,thevalueoftheflagcounterofthewholederivation remains1.