src/Pure/pattern.ML
author paulson
Wed Mar 05 10:04:45 1997 +0100 (1997-03-05)
changeset 2725 9453616d4b80
parent 2616 704b6c7432cf
child 2751 673c4eefd2e1
permissions -rw-r--r--
Declares eta_contract_atom; fixed comment; some tidying
     1 (*  Title: 	pattern
     2     ID:         $Id$
     3     Author: 	Tobias Nipkow and Christine Heinzelmann, TU Muenchen
     4     Copyright   1993  TU Muenchen
     5 
     6 Unification of Higher-Order Patterns.
     7 
     8 See also:
     9 Tobias Nipkow. Functional Unification of Higher-Order Patterns.
    10 In Proceedings of the 8th IEEE Symposium Logic in Computer Science, 1993.
    11 
    12 TODO: optimize red by special-casing it
    13 *)
    14 
    15 signature PATTERN =
    16   sig
    17   type type_sig
    18   type sg
    19   type env
    20   val eta_contract      : term -> term
    21   val eta_contract_atom : term -> term
    22   val match             : type_sig -> term * term
    23                           -> (indexname*typ)list * (indexname*term)list
    24   val matches           : type_sig -> term * term -> bool
    25   val unify             : sg * env * (term * term)list -> env
    26   exception Unif
    27   exception MATCH
    28   exception Pattern
    29   end;
    30 
    31 structure Pattern : PATTERN =
    32 struct
    33 
    34 type type_sig = Type.type_sig
    35 type sg = Sign.sg
    36 type env = Envir.env
    37 
    38 exception Unif;
    39 exception Pattern;
    40 
    41 fun occurs(F,t,env) = 
    42     let fun occ(Var(G,_))   = (case Envir.lookup(env,G) of
    43                                  Some(t) => occ t
    44                                | None    => F=G)
    45           | occ(t1$t2)      = occ t1 orelse occ t2
    46           | occ(Abs(_,_,t)) = occ t
    47           | occ _           = false
    48     in occ t end;
    49 
    50 
    51 fun mapbnd f =
    52     let fun mpb d (Bound(i))     = if i < d then Bound(i) else Bound(f(i-d)+d)
    53           | mpb d (Abs(s,T,t))   = Abs(s,T,mpb(d+1) t)
    54           | mpb d ((u1 $ u2))    = (mpb d u1)$(mpb d u2)
    55           | mpb _ atom           = atom
    56     in mpb 0 end;
    57 
    58 fun idx [] j     = ~10000
    59   | idx(i::is) j = if i=j then length is else idx is j;
    60 
    61 fun at xs i = nth_elem (i,xs);
    62 
    63 fun mkabs (binders,is,t)  =
    64     let fun mk(i::is) = let val (x,T) = nth_elem(i,binders)
    65                         in Abs(x,T,mk is) end 
    66           | mk []     = t
    67     in mk is end;
    68 
    69 val incr = mapbnd (fn i => i+1);
    70 
    71 fun ints_of []             = []
    72   | ints_of (Bound i ::bs) = 
    73       let val is = ints_of bs
    74       in if i mem_int is then raise Pattern else i::is end
    75   | ints_of _              = raise Pattern;
    76 
    77 
    78 fun app (s,(i::is)) = app (s$Bound(i),is)
    79   | app (s,[])      = s;
    80 
    81 fun red (Abs(_,_,s)) (i::is) js = red s is (i::js)
    82   | red t            []      [] = t
    83   | red t            is      jn = app (mapbnd (at jn) t,is);
    84 
    85 
    86 (* split_type ([T1,....,Tn]---> T,n,[]) = ([Tn,...,T1],T) *)
    87 fun split_type (T,0,Ts)                    = (Ts,T)
    88   | split_type (Type ("fun",[T1,T2]),n,Ts) = split_type (T2,n-1,T1::Ts)
    89   | split_type _                           = error("split_type");
    90 
    91 fun type_of_G (T,n,is) =
    92   let val (Ts,U) = split_type(T,n,[]) in map(at Ts)is ---> U end;
    93 
    94 fun mkhnf (binders,is,G,js) = mkabs (binders, is, app(G,js));
    95 
    96 fun mknewhnf(env,binders,is,F as (a,_),T,js) =
    97   let val (env',G) = Envir.genvar a (env,type_of_G(T,length is,js))
    98   in Envir.update((F,mkhnf(binders,is,G,js)),env') end;
    99 
   100 
   101 fun devar env t = case strip_comb t of
   102         (Var(F,_),ys) =>
   103             (case Envir.lookup(env,F) of
   104                Some(t) => devar env (red t (ints_of  ys) []) 
   105              | None    => t)
   106       |  _            => t;
   107 
   108 
   109 (* mk_proj_list(is) = [ |is| - k | 1 <= k <= |is| and is[k] >= 0 ] *)
   110 fun mk_proj_list is =
   111     let fun mk(i::is,j) = if i >= 0 then j :: mk(is,j-1) else mk(is,j-1)
   112           | mk([],_)    = []
   113     in mk(is,length is - 1) end;
   114 
   115 fun proj(s,env,binders,is) =
   116     let fun trans d i = if i<d then i else (idx is (i-d))+d;
   117         fun pr(s,env,d,binders) = (case devar env s of
   118               Abs(a,T,t) => let val (t',env') = pr(t,env,d+1,((a,T)::binders))
   119                             in (Abs(a,T,t'),env') end
   120             | t => (case strip_comb t of
   121                 (c as Const _,ts) =>
   122                          let val (ts',env') = prs(ts,env,d,binders)
   123                          in (list_comb(c,ts'),env') end
   124                  | (f as Free _,ts) =>
   125                          let val (ts',env') = prs(ts,env,d,binders)
   126                          in (list_comb(f,ts'),env') end
   127                  | (Bound(i),ts) =>
   128                          let val j = trans d i
   129                          in if j < 0 then raise Unif
   130                             else let val (ts',env') = prs(ts,env,d,binders)
   131                                  in (list_comb(Bound j,ts'),env') end
   132                          end
   133                  | (Var(F as (a,_),Fty),ts) =>
   134                       let val js = ints_of ts;
   135                           val js' = map (trans d) js;
   136                           val ks = mk_proj_list js';
   137                           val ls = filter (fn i => i >= 0) js'
   138                           val Hty = type_of_G(Fty,length js,ks)
   139                           val (env',H) = Envir.genvar a (env,Hty)
   140                           val env'' =
   141                                 Envir.update((F,mkhnf(binders,js,H,ks)),env')
   142                       in (app(H,ls),env'') end
   143                  | _  => raise Pattern))
   144         and prs(s::ss,env,d,binders) =
   145               let val (s',env1) = pr(s,env,d,binders)
   146                   val (ss',env2) = prs(ss,env1,d,binders)
   147               in (s'::ss',env2) end
   148           | prs([],env,_,_) = ([],env)
   149    in if downto0(is,length binders - 1) then (s,env)
   150       else pr(s,env,0,binders)
   151    end;
   152 
   153 
   154 (* mk_ff_list(is,js) = [ length(is) - k | 1 <= k <= |is| and is[k] = js[k] ] *)
   155 fun mk_ff_list(is,js) = 
   156     let fun mk([],[],_)        = [] 
   157           | mk(i::is,j::js, k) = if i=j then k :: mk(is,js,k-1)
   158                                         else mk(is,js,k-1)
   159           | mk _               = error"mk_ff_list"
   160     in mk(is,js,length is-1) end;
   161 
   162 fun flexflex1(env,binders,F,Fty,is,js) =
   163   if is=js then env
   164   else let val ks = mk_ff_list(is,js)
   165        in mknewhnf(env,binders,is,F,Fty,ks) end;
   166 
   167 fun flexflex2(env,binders,F,Fty,is,G,Gty,js) =
   168   let fun ff(F,Fty,is,G as (a,_),Gty,js) =
   169             if js subset_int is
   170             then let val t= mkabs(binders,is,app(Var(G,Gty),map (idx is) js))
   171                  in Envir.update((F,t),env) end
   172             else let val ks = is inter_int js
   173                      val Hty = type_of_G(Fty,length is,map (idx is) ks)
   174                      val (env',H) = Envir.genvar a (env,Hty)
   175                      fun lam(is) = mkabs(binders,is,app(H,map (idx is) ks));
   176                  in Envir.update((G,lam js), Envir.update((F,lam is),env'))
   177                  end;
   178   in if xless(G,F) then ff(F,Fty,is,G,Gty,js) else ff(G,Gty,js,F,Fty,is) end
   179 
   180 val tsgr = ref(Type.tsig0);
   181 
   182 fun unify_types(T,U, env as Envir.Envir{asol,iTs,maxidx}) =
   183   if T=U then env
   184   else let val (iTs',maxidx') = Type.unify (!tsgr) maxidx iTs (U,T)
   185        in Envir.Envir{asol=asol,maxidx=maxidx',iTs=iTs'} end
   186        handle Type.TUNIFY => raise Unif;
   187 
   188 fun unif binders (env,(s,t)) = case (devar env s,devar env t) of
   189       (Abs(ns,Ts,ts),Abs(nt,Tt,tt)) =>
   190          let val name = if ns = "" then nt else ns
   191          in unif ((name,Ts)::binders) (env,(ts,tt)) end
   192     | (Abs(ns,Ts,ts),t) => unif ((ns,Ts)::binders) (env,(ts,(incr t)$Bound(0)))
   193     | (t,Abs(nt,Tt,tt)) => unif ((nt,Tt)::binders) (env,((incr t)$Bound(0),tt))
   194     | p => cases(binders,env,p)
   195 
   196 and cases(binders,env,(s,t)) = case (strip_comb s,strip_comb t) of
   197        ((Var(F,Fty),ss),(Var(G,Gty),ts)) => 
   198          if F = G then flexflex1(env,binders,F,Fty,ints_of ss,ints_of ts)
   199                   else flexflex2(env,binders,F,Fty,ints_of ss,G,Gty,ints_of ts)
   200       | ((Var(F,_),ss),_)             => flexrigid(env,binders,F,ints_of ss,t)
   201       | (_,(Var(F,_),ts))             => flexrigid(env,binders,F,ints_of ts,s)
   202       | ((Const c,ss),(Const d,ts))   => rigidrigid(env,binders,c,d,ss,ts)
   203       | ((Free(f),ss),(Free(g),ts))   => rigidrigid(env,binders,f,g,ss,ts)
   204       | ((Bound(i),ss),(Bound(j),ts)) => rigidrigidB (env,binders,i,j,ss,ts) 
   205       | ((Abs(_),_),_)                => raise Pattern
   206       | (_,(Abs(_),_))                => raise Pattern
   207       | _                             => raise Unif
   208 
   209 and rigidrigid (env,binders,(a,Ta),(b,Tb),ss,ts) =
   210       if a<>b then raise Unif
   211       else foldl (unif binders) (unify_types(Ta,Tb,env), ss~~ts)
   212 
   213 and rigidrigidB (env,binders,i,j,ss,ts) =
   214      if i <> j then raise Unif else foldl (unif binders) (env ,ss~~ts)
   215 
   216 and flexrigid (env,binders,F,is,t) =
   217       if occurs(F,t,env) then raise Unif
   218       else let val (u,env') = proj(t,env,binders,is)
   219            in Envir.update((F,mkabs(binders,is,u)),env') end;
   220 
   221 fun unify(sg,env,tus) = (tsgr := #tsig(Sign.rep_sg sg);
   222                          foldl (unif []) (env,tus));
   223 
   224 
   225 (*Eta-contract a term (fully)*)
   226 fun eta_contract (Abs(a,T,body)) = 
   227       (case  eta_contract body  of
   228         body' as (f $ Bound 0) => 
   229 	  if (0 mem_int loose_bnos f) then Abs(a,T,body')
   230 	  else incr_boundvars ~1 f 
   231       | body' => Abs(a,T,body'))
   232   | eta_contract(f$t) = eta_contract f $ eta_contract t
   233   | eta_contract t = t;
   234 
   235 
   236 (*Eta-contract a term from outside: just enough to reduce it to an atom*)
   237 fun eta_contract_atom (t0 as Abs(a, T, body)) = 
   238       (case  eta_contract2 body  of
   239         body' as (f $ Bound 0) => 
   240 	    if (0 mem_int loose_bnos f) then Abs(a,T,body')
   241 	    else eta_contract_atom (incr_boundvars ~1 f)
   242       | _ => t0)
   243   | eta_contract_atom t = t
   244 and eta_contract2 (f$t) = f $ eta_contract_atom t
   245   | eta_contract2 t     = eta_contract_atom t;
   246 
   247 
   248 (* Pattern matching *)
   249 exception MATCH;
   250 
   251 (*First-order matching;  term_match tsig (pattern, object)
   252     returns a (tyvar,typ)list and (var,term)list.
   253   The pattern and object may have variables in common.
   254   Instantiation does not affect the object, so matching ?a with ?a+1 works.
   255   A Const does not match a Free of the same name! *)
   256 fun fomatch tsig (pat,obj) =
   257   let fun typ_match args = (Type.typ_match tsig args)
   258 			   handle Type.TYPE_MATCH => raise MATCH;
   259       fun mtch (tyinsts,insts) = fn
   260 	(Var(ixn,T), t)  =>
   261 	  if loose_bvar(t,0) then raise MATCH
   262 	  else (case assoc_string_int(insts,ixn) of
   263 		  None => (typ_match (tyinsts, (T, fastype_of t)), 
   264 			   (ixn,t)::insts)
   265 		| Some u => if t aconv u then (tyinsts,insts) else raise MATCH)
   266       | (Free (a,T), Free (b,U)) =>
   267 	  if  a=b  then (typ_match (tyinsts,(T,U)), insts)  else raise MATCH
   268       | (Const (a,T), Const (b,U))  =>
   269 	  if  a=b  then (typ_match (tyinsts,(T,U)), insts)  else raise MATCH
   270       | (Bound i, Bound j)  =>
   271           if  i=j  then  (tyinsts,insts)  else raise MATCH
   272       | (Abs(_,T,t), Abs(_,U,u))  =>
   273 	  mtch (typ_match (tyinsts,(T,U)),insts) (t,u)
   274       | (f$t, g$u) => mtch (mtch (tyinsts,insts) (f,g)) (t, u)
   275       | _ => raise MATCH
   276   in mtch([],[]) (eta_contract pat, eta_contract obj) end;
   277 
   278 
   279 fun match_bind(itms,binders,ixn,is,t) =
   280   let val js = loose_bnos t
   281   in if null is
   282      then if null js then (ixn,t)::itms else raise MATCH
   283      else if js subset_int is
   284           then let val t' = if downto0(is,length binders - 1) then t
   285                             else mapbnd (idx is) t
   286                in (ixn, mkabs(binders,is,t')) :: itms end
   287           else raise MATCH
   288   end;
   289 
   290 (*Tests whether 2 terms are alpha/eta-convertible and have same type.
   291   Note that Consts and Vars may have more than one type.*)
   292 infix aeconv;
   293 fun (Const(a,T)) aeconv (Const(b,U)) = a=b  andalso  T=U
   294   | (Free(a,T))  aeconv (Free(b,U))  = a=b  andalso  T=U
   295   | (Var(v,T))   aeconv (Var(w,U))   = v=w  andalso  T=U
   296   | (Bound i)    aeconv (Bound j)    = i=j
   297   | (Abs(_,T,t)) aeconv (Abs(_,U,u)) = (t aeconv u)  andalso  T=U
   298   | (Abs(_,T,t)) aeconv u            = t aeconv ((incr u)$Bound(0))
   299   | t            aeconv (Abs(_,U,u)) = ((incr t)$Bound(0)) aeconv u
   300   | (f$t)        aeconv (g$u)        = (f aeconv g)  andalso (t aeconv u)
   301   | _ aeconv _                       =  false;
   302 
   303 
   304 fun match tsg (po as (pat,obj)) =
   305 let
   306 
   307 fun typ_match args = Type.typ_match tsg args
   308                      handle Type.TYPE_MATCH => raise MATCH;
   309 
   310 (* Pre: pat and obj have same type *)
   311 fun mtch binders (env as (iTs,itms),(pat,obj)) =
   312       case pat of
   313         Abs(ns,Ts,ts) =>
   314           (case obj of
   315              Abs(nt,Tt,tt) => mtch ((nt,Tt)::binders) (env,(ts,tt))
   316            | _ => let val Tt = typ_subst_TVars iTs Ts
   317                   in mtch((ns,Tt)::binders)(env,(ts,(incr obj)$Bound(0))) end)
   318       | _ => (case obj of
   319                 Abs(nt,Tt,tt) =>
   320                   mtch((nt,Tt)::binders)(env,((incr pat)$Bound(0),tt))
   321               | _ => cases(binders,env,pat,obj))
   322 
   323 and cases(binders,env as (iTs,itms),pat,obj) =
   324       let val (ph,pargs) = strip_comb pat
   325           fun rigrig1(iTs,oargs) =
   326                 foldl (mtch binders) ((iTs,itms), pargs~~oargs)
   327           fun rigrig2((a,Ta),(b,Tb),oargs) =
   328                 if a<> b then raise MATCH
   329                 else rigrig1(typ_match(iTs,(Ta,Tb)), oargs)
   330       in case ph of
   331            Var(ixn,_) =>
   332              let val is = ints_of pargs
   333              in case assoc_string_int(itms,ixn) of
   334                   None => (iTs,match_bind(itms,binders,ixn,is,obj))
   335                 | Some u => if obj aeconv (red u is []) then env
   336                             else raise MATCH
   337              end
   338          | _ =>
   339              let val (oh,oargs) = strip_comb obj
   340              in case (ph,oh) of
   341                   (Const c,Const d) => rigrig2(c,d,oargs)
   342                 | (Free f,Free g)   => rigrig2(f,g,oargs)
   343                 | (Bound i,Bound j) => if i<>j then raise MATCH
   344                                        else rigrig1(iTs,oargs)
   345                 | (Abs _, _)        => raise Pattern
   346                 | (_, Abs _)        => raise Pattern
   347                 | _                 => raise MATCH
   348              end
   349       end;
   350 
   351 val pT = fastype_of pat
   352 and oT = fastype_of obj
   353 val iTs = typ_match ([],(pT,oT))
   354 
   355 in mtch [] ((iTs,[]), po)
   356    handle Pattern => fomatch tsg po
   357 end;
   358 
   359 (*Predicate: does the pattern match the object?*)
   360 fun matches tsig po = (match tsig po; true) handle MATCH => false;
   361 
   362 end;