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