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