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