src/Pure/pattern.ML
author obua
Sun May 29 12:39:12 2005 +0200 (2005-05-29)
changeset 16108 cf468b93a02e
parent 15797 a63605582573
child 16651 40b96a501773
permissions -rw-r--r--
Implement cycle-free overloading, so that definitions cannot harm consistency any more (except of course via interaction with axioms).
wenzelm@12784
     1
(*  Title:      Pure/pattern.ML
clasohm@0
     2
    ID:         $Id$
wenzelm@12784
     3
    Author:     Tobias Nipkow, Christine Heinzelmann, and Stefan Berghofer
clasohm@0
     4
clasohm@0
     5
Unification of Higher-Order Patterns.
clasohm@0
     6
clasohm@0
     7
See also:
clasohm@0
     8
Tobias Nipkow. Functional Unification of Higher-Order Patterns.
clasohm@0
     9
In Proceedings of the 8th IEEE Symposium Logic in Computer Science, 1993.
nipkow@678
    10
nipkow@678
    11
TODO: optimize red by special-casing it
clasohm@0
    12
*)
clasohm@0
    13
paulson@2751
    14
infix aeconv;
paulson@2751
    15
clasohm@0
    16
signature PATTERN =
wenzelm@14787
    17
sig
nipkow@13642
    18
  val trace_unify_fail  : bool ref
paulson@2751
    19
  val aeconv            : term * term -> bool
paulson@2725
    20
  val eta_contract      : term -> term
berghofe@13998
    21
  val eta_long          : typ list -> term -> term
wenzelm@12781
    22
  val beta_eta_contract : term -> term
paulson@2725
    23
  val eta_contract_atom : term -> term
wenzelm@14787
    24
  val match             : Type.tsig -> term * term
berghofe@15797
    25
                          -> Type.tyenv * Envir.tenv
wenzelm@14787
    26
  val first_order_match : Type.tsig -> term * term
berghofe@15797
    27
                          -> Type.tyenv * Envir.tenv
wenzelm@14787
    28
  val matches           : Type.tsig -> term * term -> bool
wenzelm@14787
    29
  val matches_subterm   : Type.tsig -> term * term -> bool
wenzelm@14787
    30
  val unify             : Sign.sg * Envir.env * (term * term)list -> Envir.env
nipkow@4820
    31
  val first_order       : term -> bool
nipkow@4820
    32
  val pattern           : term -> bool
wenzelm@14787
    33
  val rewrite_term      : Type.tsig -> (term * term) list -> (term -> term option) list
berghofe@13195
    34
                          -> term -> term
clasohm@0
    35
  exception Unif
clasohm@0
    36
  exception MATCH
clasohm@0
    37
  exception Pattern
wenzelm@14787
    38
end;
clasohm@0
    39
paulson@1501
    40
structure Pattern : PATTERN =
clasohm@0
    41
struct
clasohm@0
    42
clasohm@0
    43
exception Unif;
clasohm@0
    44
exception Pattern;
clasohm@0
    45
nipkow@13642
    46
val trace_unify_fail = ref false;
nipkow@13642
    47
wenzelm@14875
    48
fun string_of_term sg env binders t = Sign.string_of_term sg
nipkow@13642
    49
  (Envir.norm_term env (subst_bounds(map Free binders,t)));
nipkow@13642
    50
skalberg@15570
    51
fun bname binders i = fst(List.nth(binders,i));
nipkow@13642
    52
fun bnames binders is = space_implode " " (map (bname binders) is);
nipkow@13642
    53
wenzelm@14875
    54
fun typ_clash sg (tye,T,U) =
nipkow@13642
    55
  if !trace_unify_fail
wenzelm@14875
    56
  then let val t = Sign.string_of_typ sg (Envir.norm_type tye T)
wenzelm@14875
    57
           and u = Sign.string_of_typ sg (Envir.norm_type tye U)
nipkow@13642
    58
       in tracing("The following types do not unify:\n" ^ t ^ "\n" ^ u) end
nipkow@13642
    59
  else ()
nipkow@13642
    60
nipkow@13642
    61
fun clash a b =
nipkow@13642
    62
  if !trace_unify_fail then tracing("Clash: " ^ a ^ " =/= " ^ b) else ()
nipkow@13642
    63
nipkow@13642
    64
fun boundVar binders i =
nipkow@13642
    65
  "bound variable " ^ bname binders i ^ " (depth " ^ string_of_int i ^ ")";
nipkow@13642
    66
nipkow@13642
    67
fun clashBB binders i j =
nipkow@13642
    68
  if !trace_unify_fail then clash (boundVar binders i) (boundVar binders j)
nipkow@13642
    69
  else ()
nipkow@13642
    70
nipkow@13642
    71
fun clashB binders i s =
nipkow@13642
    72
  if !trace_unify_fail then clash (boundVar binders i) s
nipkow@13642
    73
  else ()
nipkow@13642
    74
berghofe@15797
    75
fun proj_fail sg (env,binders,F,_,is,t) =
nipkow@13642
    76
  if !trace_unify_fail
nipkow@13642
    77
  then let val f = Syntax.string_of_vname F
nipkow@13642
    78
           val xs = bnames binders is
wenzelm@14875
    79
           val u = string_of_term sg env binders t
nipkow@13642
    80
           val ys = bnames binders (loose_bnos t \\ is)
nipkow@13642
    81
       in tracing("Cannot unify variable " ^ f ^
nipkow@13642
    82
               " (depending on bound variables " ^ xs ^ ")\nwith term " ^ u ^
nipkow@13642
    83
               "\nTerm contains additional bound variable(s) " ^ ys)
nipkow@13642
    84
       end
nipkow@13642
    85
  else ()
nipkow@13642
    86
wenzelm@14875
    87
fun ocheck_fail sg (F,t,binders,env) =
nipkow@13642
    88
  if !trace_unify_fail
nipkow@13642
    89
  then let val f = Syntax.string_of_vname F
wenzelm@14875
    90
           val u = string_of_term sg env binders t
nipkow@13642
    91
       in tracing("Variable " ^ f ^ " occurs in term\n" ^ u ^
nipkow@13642
    92
                  "\nCannot unify!\n")
nipkow@13642
    93
       end
nipkow@13642
    94
  else ()
nipkow@13642
    95
wenzelm@12784
    96
fun occurs(F,t,env) =
berghofe@15797
    97
    let fun occ(Var (G, T))   = (case Envir.lookup (env, (G, T)) of
skalberg@15531
    98
                                 SOME(t) => occ t
skalberg@15531
    99
                               | NONE    => F=G)
clasohm@0
   100
          | occ(t1$t2)      = occ t1 orelse occ t2
clasohm@0
   101
          | occ(Abs(_,_,t)) = occ t
clasohm@0
   102
          | occ _           = false
clasohm@0
   103
    in occ t end;
clasohm@0
   104
clasohm@0
   105
clasohm@0
   106
fun mapbnd f =
clasohm@0
   107
    let fun mpb d (Bound(i))     = if i < d then Bound(i) else Bound(f(i-d)+d)
clasohm@0
   108
          | mpb d (Abs(s,T,t))   = Abs(s,T,mpb(d+1) t)
nipkow@678
   109
          | mpb d ((u1 $ u2))    = (mpb d u1)$(mpb d u2)
nipkow@678
   110
          | mpb _ atom           = atom
clasohm@0
   111
    in mpb 0 end;
clasohm@0
   112
berghofe@14861
   113
fun idx [] j     = raise Unif
clasohm@0
   114
  | idx(i::is) j = if i=j then length is else idx is j;
clasohm@0
   115
skalberg@15570
   116
fun at xs i = List.nth (xs,i);
clasohm@0
   117
clasohm@0
   118
fun mkabs (binders,is,t)  =
skalberg@15570
   119
    let fun mk(i::is) = let val (x,T) = List.nth(binders,i)
wenzelm@12784
   120
                        in Abs(x,T,mk is) end
clasohm@0
   121
          | mk []     = t
clasohm@0
   122
    in mk is end;
clasohm@0
   123
clasohm@0
   124
val incr = mapbnd (fn i => i+1);
clasohm@0
   125
clasohm@0
   126
fun ints_of []             = []
wenzelm@12784
   127
  | ints_of (Bound i ::bs) =
clasohm@0
   128
      let val is = ints_of bs
berghofe@1576
   129
      in if i mem_int is then raise Pattern else i::is end
clasohm@0
   130
  | ints_of _              = raise Pattern;
clasohm@0
   131
berghofe@12232
   132
fun ints_of' env ts = ints_of (map (Envir.head_norm env) ts);
berghofe@12232
   133
clasohm@0
   134
clasohm@0
   135
fun app (s,(i::is)) = app (s$Bound(i),is)
clasohm@0
   136
  | app (s,[])      = s;
clasohm@0
   137
clasohm@0
   138
fun red (Abs(_,_,s)) (i::is) js = red s is (i::js)
nipkow@678
   139
  | red t            []      [] = t
nipkow@678
   140
  | red t            is      jn = app (mapbnd (at jn) t,is);
nipkow@678
   141
clasohm@0
   142
clasohm@0
   143
(* split_type ([T1,....,Tn]---> T,n,[]) = ([Tn,...,T1],T) *)
clasohm@0
   144
fun split_type (T,0,Ts)                    = (Ts,T)
clasohm@0
   145
  | split_type (Type ("fun",[T1,T2]),n,Ts) = split_type (T2,n-1,T1::Ts)
nipkow@678
   146
  | split_type _                           = error("split_type");
clasohm@0
   147
berghofe@13891
   148
fun type_of_G (env as Envir.Envir {iTs, ...}) (T,n,is) =
berghofe@13891
   149
  let val (Ts, U) = split_type (Envir.norm_type iTs T, n, [])
berghofe@13891
   150
  in map (at Ts) is ---> U end;
clasohm@0
   151
clasohm@0
   152
fun mkhnf (binders,is,G,js) = mkabs (binders, is, app(G,js));
clasohm@0
   153
clasohm@0
   154
fun mknewhnf(env,binders,is,F as (a,_),T,js) =
berghofe@13891
   155
  let val (env',G) = Envir.genvar a (env,type_of_G env (T,length is,js))
berghofe@15797
   156
  in Envir.update (((F, T), mkhnf (binders, is, G, js)), env') end;
clasohm@0
   157
clasohm@0
   158
clasohm@0
   159
(* mk_proj_list(is) = [ |is| - k | 1 <= k <= |is| and is[k] >= 0 ] *)
clasohm@0
   160
fun mk_proj_list is =
skalberg@15570
   161
    let fun mk(i::is,j) = if isSome i then j :: mk(is,j-1) else mk(is,j-1)
clasohm@0
   162
          | mk([],_)    = []
clasohm@0
   163
    in mk(is,length is - 1) end;
clasohm@0
   164
clasohm@0
   165
fun proj(s,env,binders,is) =
clasohm@0
   166
    let fun trans d i = if i<d then i else (idx is (i-d))+d;
berghofe@12232
   167
        fun pr(s,env,d,binders) = (case Envir.head_norm env s of
clasohm@0
   168
              Abs(a,T,t) => let val (t',env') = pr(t,env,d+1,((a,T)::binders))
clasohm@0
   169
                            in (Abs(a,T,t'),env') end
clasohm@0
   170
            | t => (case strip_comb t of
clasohm@0
   171
                (c as Const _,ts) =>
clasohm@0
   172
                         let val (ts',env') = prs(ts,env,d,binders)
clasohm@0
   173
                         in (list_comb(c,ts'),env') end
clasohm@0
   174
                 | (f as Free _,ts) =>
clasohm@0
   175
                         let val (ts',env') = prs(ts,env,d,binders)
clasohm@0
   176
                         in (list_comb(f,ts'),env') end
clasohm@0
   177
                 | (Bound(i),ts) =>
clasohm@0
   178
                         let val j = trans d i
berghofe@14861
   179
                             val (ts',env') = prs(ts,env,d,binders)
berghofe@14861
   180
                         in (list_comb(Bound j,ts'),env') end
clasohm@0
   181
                 | (Var(F as (a,_),Fty),ts) =>
berghofe@12232
   182
                      let val js = ints_of' env ts;
berghofe@14861
   183
                          val js' = map (try (trans d)) js;
clasohm@0
   184
                          val ks = mk_proj_list js';
skalberg@15570
   185
                          val ls = List.mapPartial I js'
berghofe@13891
   186
                          val Hty = type_of_G env (Fty,length js,ks)
clasohm@0
   187
                          val (env',H) = Envir.genvar a (env,Hty)
clasohm@0
   188
                          val env'' =
berghofe@15797
   189
                            Envir.update (((F, Fty), mkhnf (binders, js, H, ks)), env')
clasohm@0
   190
                      in (app(H,ls),env'') end
clasohm@0
   191
                 | _  => raise Pattern))
clasohm@0
   192
        and prs(s::ss,env,d,binders) =
clasohm@0
   193
              let val (s',env1) = pr(s,env,d,binders)
clasohm@0
   194
                  val (ss',env2) = prs(ss,env1,d,binders)
clasohm@0
   195
              in (s'::ss',env2) end
clasohm@0
   196
          | prs([],env,_,_) = ([],env)
clasohm@0
   197
   in if downto0(is,length binders - 1) then (s,env)
clasohm@0
   198
      else pr(s,env,0,binders)
clasohm@0
   199
   end;
clasohm@0
   200
clasohm@0
   201
clasohm@0
   202
(* mk_ff_list(is,js) = [ length(is) - k | 1 <= k <= |is| and is[k] = js[k] ] *)
wenzelm@12784
   203
fun mk_ff_list(is,js) =
wenzelm@12784
   204
    let fun mk([],[],_)        = []
clasohm@0
   205
          | mk(i::is,j::js, k) = if i=j then k :: mk(is,js,k-1)
clasohm@0
   206
                                        else mk(is,js,k-1)
nipkow@678
   207
          | mk _               = error"mk_ff_list"
clasohm@0
   208
    in mk(is,js,length is-1) end;
clasohm@0
   209
clasohm@0
   210
fun flexflex1(env,binders,F,Fty,is,js) =
clasohm@0
   211
  if is=js then env
clasohm@0
   212
  else let val ks = mk_ff_list(is,js)
clasohm@0
   213
       in mknewhnf(env,binders,is,F,Fty,ks) end;
clasohm@0
   214
clasohm@0
   215
fun flexflex2(env,binders,F,Fty,is,G,Gty,js) =
clasohm@0
   216
  let fun ff(F,Fty,is,G as (a,_),Gty,js) =
berghofe@1576
   217
            if js subset_int is
clasohm@0
   218
            then let val t= mkabs(binders,is,app(Var(G,Gty),map (idx is) js))
berghofe@15797
   219
                 in Envir.update (((F, Fty), t), env) end
berghofe@1576
   220
            else let val ks = is inter_int js
berghofe@13891
   221
                     val Hty = type_of_G env (Fty,length is,map (idx is) ks)
clasohm@0
   222
                     val (env',H) = Envir.genvar a (env,Hty)
clasohm@0
   223
                     fun lam(is) = mkabs(binders,is,app(H,map (idx is) ks));
berghofe@15797
   224
                 in Envir.update (((G, Gty), lam js), Envir.update (((F, Fty), lam is), env'))
clasohm@0
   225
                 end;
clasohm@0
   226
  in if xless(G,F) then ff(F,Fty,is,G,Gty,js) else ff(G,Gty,js,F,Fty,is) end
clasohm@0
   227
wenzelm@14875
   228
fun unify_types sg (T,U, env as Envir.Envir{asol,iTs,maxidx}) =
clasohm@0
   229
  if T=U then env
wenzelm@14875
   230
  else let val (iTs',maxidx') = Type.unify (Sign.tsig_of sg) (iTs, maxidx) (U, T)
nipkow@1435
   231
       in Envir.Envir{asol=asol,maxidx=maxidx',iTs=iTs'} end
wenzelm@14875
   232
       handle Type.TUNIFY => (typ_clash sg (iTs,T,U); raise Unif);
clasohm@0
   233
wenzelm@14875
   234
fun unif sg binders (env,(s,t)) = case (Envir.head_norm env s, Envir.head_norm env t) of
clasohm@0
   235
      (Abs(ns,Ts,ts),Abs(nt,Tt,tt)) =>
clasohm@0
   236
         let val name = if ns = "" then nt else ns
wenzelm@14875
   237
         in unif sg ((name,Ts)::binders) (env,(ts,tt)) end
wenzelm@14875
   238
    | (Abs(ns,Ts,ts),t) => unif sg ((ns,Ts)::binders) (env,(ts,(incr t)$Bound(0)))
wenzelm@14875
   239
    | (t,Abs(nt,Tt,tt)) => unif sg ((nt,Tt)::binders) (env,((incr t)$Bound(0),tt))
wenzelm@14875
   240
    | p => cases sg (binders,env,p)
clasohm@0
   241
wenzelm@14875
   242
and cases sg (binders,env,(s,t)) = case (strip_comb s,strip_comb t) of
wenzelm@12784
   243
       ((Var(F,Fty),ss),(Var(G,Gty),ts)) =>
berghofe@12232
   244
         if F = G then flexflex1(env,binders,F,Fty,ints_of' env ss,ints_of' env ts)
berghofe@12232
   245
                  else flexflex2(env,binders,F,Fty,ints_of' env ss,G,Gty,ints_of' env ts)
berghofe@15797
   246
      | ((Var(F,Fty),ss),_)           => flexrigid sg (env,binders,F,Fty,ints_of' env ss,t)
berghofe@15797
   247
      | (_,(Var(F,Fty),ts))           => flexrigid sg (env,binders,F,Fty,ints_of' env ts,s)
wenzelm@14875
   248
      | ((Const c,ss),(Const d,ts))   => rigidrigid sg (env,binders,c,d,ss,ts)
wenzelm@14875
   249
      | ((Free(f),ss),(Free(g),ts))   => rigidrigid sg (env,binders,f,g,ss,ts)
wenzelm@14875
   250
      | ((Bound(i),ss),(Bound(j),ts)) => rigidrigidB sg (env,binders,i,j,ss,ts)
clasohm@0
   251
      | ((Abs(_),_),_)                => raise Pattern
clasohm@0
   252
      | (_,(Abs(_),_))                => raise Pattern
nipkow@13642
   253
      | ((Const(c,_),_),(Free(f,_),_)) => (clash c f; raise Unif)
nipkow@13642
   254
      | ((Const(c,_),_),(Bound i,_))   => (clashB binders i c; raise Unif)
nipkow@13642
   255
      | ((Free(f,_),_),(Const(c,_),_)) => (clash f c; raise Unif)
nipkow@13642
   256
      | ((Free(f,_),_),(Bound i,_))    => (clashB binders i f; raise Unif)
nipkow@13642
   257
      | ((Bound i,_),(Const(c,_),_))   => (clashB binders i c; raise Unif)
nipkow@13642
   258
      | ((Bound i,_),(Free(f,_),_))    => (clashB binders i f; raise Unif)
nipkow@13642
   259
clasohm@0
   260
wenzelm@14875
   261
and rigidrigid sg (env,binders,(a,Ta),(b,Tb),ss,ts) =
nipkow@13642
   262
      if a<>b then (clash a b; raise Unif)
skalberg@15570
   263
      else Library.foldl (unif sg binders) (unify_types sg (Ta,Tb,env), ss~~ts)
clasohm@0
   264
wenzelm@14875
   265
and rigidrigidB sg (env,binders,i,j,ss,ts) =
nipkow@13642
   266
     if i <> j then (clashBB binders i j; raise Unif)
skalberg@15570
   267
     else Library.foldl (unif sg binders) (env ,ss~~ts)
clasohm@0
   268
berghofe@15797
   269
and flexrigid sg (params as (env,binders,F,Fty,is,t)) =
wenzelm@14875
   270
      if occurs(F,t,env) then (ocheck_fail sg (F,t,binders,env); raise Unif)
nipkow@13642
   271
      else (let val (u,env') = proj(t,env,binders,is)
berghofe@15797
   272
            in Envir.update (((F, Fty), mkabs (binders, is, u)), env') end
wenzelm@14875
   273
            handle Unif => (proj_fail sg params; raise Unif));
clasohm@0
   274
skalberg@15570
   275
fun unify(sg,env,tus) = Library.foldl (unif sg []) (env,tus);
clasohm@0
   276
clasohm@0
   277
paulson@2725
   278
(*Eta-contract a term (fully)*)
nipkow@2792
   279
wenzelm@12797
   280
fun eta_contract t =
wenzelm@12797
   281
  let
wenzelm@12797
   282
    exception SAME;
wenzelm@14787
   283
    fun eta (Abs (a, T, body)) =
wenzelm@12797
   284
      ((case eta body of
wenzelm@14787
   285
          body' as (f $ Bound 0) =>
wenzelm@14787
   286
            if loose_bvar1 (f, 0) then Abs(a, T, body')
wenzelm@14787
   287
            else incr_boundvars ~1 f
wenzelm@12797
   288
        | body' => Abs (a, T, body')) handle SAME =>
wenzelm@12797
   289
       (case body of
wenzelm@14787
   290
          (f $ Bound 0) =>
wenzelm@14787
   291
            if loose_bvar1 (f, 0) then raise SAME
wenzelm@14787
   292
            else incr_boundvars ~1 f
wenzelm@12797
   293
        | _ => raise SAME))
wenzelm@12797
   294
      | eta (f $ t) =
wenzelm@12797
   295
          (let val f' = eta f
wenzelm@12797
   296
           in f' $ etah t end handle SAME => f $ eta t)
wenzelm@12797
   297
      | eta _ = raise SAME
wenzelm@12797
   298
    and etah t = (eta t handle SAME => t)
wenzelm@12797
   299
  in etah t end;
clasohm@0
   300
wenzelm@12781
   301
val beta_eta_contract = eta_contract o Envir.beta_norm;
wenzelm@12781
   302
nipkow@6539
   303
(*Eta-contract a term from outside: just enough to reduce it to an atom
nipkow@6539
   304
DOESN'T QUITE WORK!
nipkow@6539
   305
*)
wenzelm@12784
   306
fun eta_contract_atom (t0 as Abs(a, T, body)) =
paulson@2725
   307
      (case  eta_contract2 body  of
wenzelm@12784
   308
        body' as (f $ Bound 0) =>
wenzelm@12784
   309
            if loose_bvar1(f,0) then Abs(a,T,body')
wenzelm@12784
   310
            else eta_contract_atom (incr_boundvars ~1 f)
paulson@2725
   311
      | _ => t0)
paulson@2725
   312
  | eta_contract_atom t = t
paulson@2725
   313
and eta_contract2 (f$t) = f $ eta_contract_atom t
paulson@2725
   314
  | eta_contract2 t     = eta_contract_atom t;
paulson@2725
   315
berghofe@13998
   316
(* put a term into eta long beta normal form *)
berghofe@13998
   317
fun eta_long Ts (Abs (s, T, t)) = Abs (s, T, eta_long (T :: Ts) t)
berghofe@13998
   318
  | eta_long Ts t = (case strip_comb t of
berghofe@13998
   319
      (Abs _, _) => eta_long Ts (Envir.beta_norm t)
wenzelm@14787
   320
    | (u, ts) =>
berghofe@13998
   321
      let
berghofe@13998
   322
        val Us = binder_types (fastype_of1 (Ts, t));
berghofe@13998
   323
        val i = length Us
berghofe@13998
   324
      in list_abs (map (pair "x") Us,
berghofe@13998
   325
        list_comb (incr_boundvars i u, map (eta_long (rev Us @ Ts))
berghofe@13998
   326
          (map (incr_boundvars i) ts @ map Bound (i - 1 downto 0))))
berghofe@13998
   327
      end);
berghofe@13998
   328
paulson@2725
   329
nipkow@678
   330
(*Tests whether 2 terms are alpha/eta-convertible and have same type.
nipkow@678
   331
  Note that Consts and Vars may have more than one type.*)
paulson@2751
   332
fun t aeconv u = aconv_aux (eta_contract_atom t, eta_contract_atom u)
paulson@2751
   333
and aconv_aux (Const(a,T), Const(b,U)) = a=b  andalso  T=U
paulson@2751
   334
  | aconv_aux (Free(a,T),  Free(b,U))  = a=b  andalso  T=U
paulson@2751
   335
  | aconv_aux (Var(v,T),   Var(w,U))   = eq_ix(v,w) andalso  T=U
wenzelm@12784
   336
  | aconv_aux (Bound i,    Bound j)    = i=j
paulson@2751
   337
  | aconv_aux (Abs(_,T,t), Abs(_,U,u)) = (t aeconv u)  andalso  T=U
wenzelm@12784
   338
  | aconv_aux (f$t,        g$u)        = (f aeconv g)  andalso (t aeconv u)
paulson@2751
   339
  | aconv_aux _ =  false;
nipkow@678
   340
nipkow@678
   341
nipkow@4820
   342
(*** Matching ***)
nipkow@4820
   343
nipkow@4820
   344
exception MATCH;
nipkow@4820
   345
nipkow@4820
   346
fun typ_match tsig args = (Type.typ_match tsig args)
nipkow@4820
   347
                          handle Type.TYPE_MATCH => raise MATCH;
nipkow@4820
   348
nipkow@4820
   349
(*First-order matching;
nipkow@4820
   350
  fomatch tsig (pattern, object) returns a (tyvar,typ)list and (var,term)list.
nipkow@4820
   351
  The pattern and object may have variables in common.
nipkow@4820
   352
  Instantiation does not affect the object, so matching ?a with ?a+1 works.
nipkow@4820
   353
  Object is eta-contracted on the fly (by eta-expanding the pattern).
nipkow@4820
   354
  Precondition: the pattern is already eta-contracted!
nipkow@4820
   355
  Note: types are matched on the fly *)
nipkow@4820
   356
fun fomatch tsig =
nipkow@4820
   357
  let
nipkow@4820
   358
    fun mtch (instsp as (tyinsts,insts)) = fn
nipkow@4820
   359
        (Var(ixn,T), t)  =>
wenzelm@12784
   360
          if loose_bvar(t,0) then raise MATCH
berghofe@15797
   361
          else (case Envir.lookup' (instsp, (ixn, T)) of
skalberg@15531
   362
                  NONE => (typ_match tsig (tyinsts, (T, fastype_of t)),
berghofe@15797
   363
                           Vartab.update_new ((ixn, (T, t)), insts))
skalberg@15531
   364
                | SOME u => if t aeconv u then instsp else raise MATCH)
nipkow@4820
   365
      | (Free (a,T), Free (b,U)) =>
wenzelm@12784
   366
          if a=b then (typ_match tsig (tyinsts,(T,U)), insts) else raise MATCH
nipkow@4820
   367
      | (Const (a,T), Const (b,U))  =>
wenzelm@12784
   368
          if a=b then (typ_match tsig (tyinsts,(T,U)), insts) else raise MATCH
nipkow@4820
   369
      | (Bound i, Bound j)  =>  if  i=j  then  instsp  else raise MATCH
nipkow@4820
   370
      | (Abs(_,T,t), Abs(_,U,u))  =>
wenzelm@12784
   371
          mtch (typ_match tsig (tyinsts,(T,U)),insts) (t,u)
nipkow@4820
   372
      | (f$t, g$u) => mtch (mtch instsp (f,g)) (t, u)
nipkow@4820
   373
      | (t, Abs(_,U,u))  =>  mtch instsp ((incr t)$(Bound 0), u)
nipkow@4820
   374
      | _ => raise MATCH
nipkow@4820
   375
  in mtch end;
nipkow@4820
   376
berghofe@15797
   377
fun first_order_match tsig = fomatch tsig (Vartab.empty, Vartab.empty);
berghofe@8406
   378
nipkow@4820
   379
(* Matching of higher-order patterns *)
nipkow@4820
   380
berghofe@15797
   381
fun match_bind(itms,binders,ixn,T,is,t) =
nipkow@4820
   382
  let val js = loose_bnos t
nipkow@4820
   383
  in if null is
berghofe@15797
   384
     then if null js then Vartab.update_new ((ixn, (T, t)), itms) else raise MATCH
nipkow@4820
   385
     else if js subset_int is
nipkow@4820
   386
          then let val t' = if downto0(is,length binders - 1) then t
nipkow@4820
   387
                            else mapbnd (idx is) t
berghofe@15797
   388
               in Vartab.update_new ((ixn, (T, mkabs (binders, is, t'))), itms) end
nipkow@4820
   389
          else raise MATCH
nipkow@4820
   390
  end;
nipkow@4820
   391
nipkow@678
   392
fun match tsg (po as (pat,obj)) =
nipkow@678
   393
let
nipkow@4820
   394
  (* Pre: pat and obj have same type *)
nipkow@4820
   395
  fun mtch binders (env as (iTs,itms),(pat,obj)) =
nipkow@4820
   396
    case pat of
nipkow@4820
   397
      Abs(ns,Ts,ts) =>
nipkow@4820
   398
        (case obj of
nipkow@4820
   399
           Abs(nt,Tt,tt) => mtch ((nt,Tt)::binders) (env,(ts,tt))
berghofe@15797
   400
         | _ => let val Tt = Envir.typ_subst_TVars iTs Ts
nipkow@4820
   401
                in mtch((ns,Tt)::binders)(env,(ts,(incr obj)$Bound(0))) end)
nipkow@4820
   402
    | _ => (case obj of
nipkow@4820
   403
              Abs(nt,Tt,tt) =>
nipkow@4820
   404
                mtch((nt,Tt)::binders)(env,((incr pat)$Bound(0),tt))
nipkow@4820
   405
            | _ => cases(binders,env,pat,obj))
nipkow@678
   406
nipkow@4820
   407
  and cases(binders,env as (iTs,itms),pat,obj) =
nipkow@4820
   408
    let val (ph,pargs) = strip_comb pat
nipkow@4820
   409
        fun rigrig1(iTs,oargs) =
skalberg@15570
   410
              Library.foldl (mtch binders) ((iTs,itms), pargs~~oargs)
nipkow@4820
   411
        fun rigrig2((a,Ta),(b,Tb),oargs) =
nipkow@4820
   412
              if a<> b then raise MATCH
nipkow@4820
   413
              else rigrig1(typ_match tsg (iTs,(Ta,Tb)), oargs)
nipkow@4820
   414
    in case ph of
berghofe@15797
   415
         Var(ixn,T) =>
nipkow@4820
   416
           let val is = ints_of pargs
berghofe@15797
   417
           in case Envir.lookup' (env, (ixn, T)) of
berghofe@15797
   418
                NONE => (iTs,match_bind(itms,binders,ixn,T,is,obj))
skalberg@15531
   419
              | SOME u => if obj aeconv (red u is []) then env
nipkow@4820
   420
                          else raise MATCH
nipkow@4820
   421
           end
nipkow@4820
   422
       | _ =>
nipkow@4820
   423
           let val (oh,oargs) = strip_comb obj
nipkow@4820
   424
           in case (ph,oh) of
nipkow@4820
   425
                (Const c,Const d) => rigrig2(c,d,oargs)
nipkow@4820
   426
              | (Free f,Free g)   => rigrig2(f,g,oargs)
nipkow@4820
   427
              | (Bound i,Bound j) => if i<>j then raise MATCH
nipkow@4820
   428
                                     else rigrig1(iTs,oargs)
nipkow@4820
   429
              | (Abs _, _)        => raise Pattern
nipkow@4820
   430
              | (_, Abs _)        => raise Pattern
nipkow@4820
   431
              | _                 => raise MATCH
nipkow@4820
   432
           end
nipkow@4820
   433
    end;
nipkow@678
   434
nipkow@4820
   435
  val pT = fastype_of pat
nipkow@4820
   436
  and oT = fastype_of obj
berghofe@8406
   437
  val iTs = typ_match tsg (Vartab.empty, (pT,oT))
berghofe@15797
   438
  val insts2 = (iTs, Vartab.empty)
nipkow@678
   439
berghofe@15797
   440
in mtch [] (insts2, po)
berghofe@15797
   441
   handle Pattern => fomatch tsg insts2 po
nipkow@678
   442
end;
clasohm@0
   443
clasohm@0
   444
(*Predicate: does the pattern match the object?*)
nipkow@678
   445
fun matches tsig po = (match tsig po; true) handle MATCH => false;
clasohm@0
   446
nipkow@4667
   447
(* Does pat match a subterm of obj? *)
nipkow@4667
   448
fun matches_subterm tsig (pat,obj) =
nipkow@4667
   449
  let fun msub(bounds,obj) = matches tsig (pat,obj) orelse
nipkow@4667
   450
            case obj of
nipkow@4667
   451
              Abs(x,T,t) => let val y = variant bounds x
nipkow@4667
   452
                                val f = Free(":" ^ y,T)
nipkow@4667
   453
                            in msub(x::bounds,subst_bound(f,t)) end
nipkow@4667
   454
            | s$t => msub(bounds,s) orelse msub(bounds,t)
nipkow@4667
   455
            | _ => false
nipkow@4667
   456
  in msub([],obj) end;
nipkow@4667
   457
nipkow@4820
   458
fun first_order(Abs(_,_,t)) = first_order t
nipkow@4820
   459
  | first_order(t $ u) = first_order t andalso first_order u andalso
nipkow@4820
   460
                         not(is_Var t)
nipkow@4820
   461
  | first_order _ = true;
nipkow@4820
   462
nipkow@4820
   463
fun pattern(Abs(_,_,t)) = pattern t
nipkow@4820
   464
  | pattern(t) = let val (head,args) = strip_comb t
nipkow@4820
   465
                 in if is_Var head
nipkow@4820
   466
                    then let val _ = ints_of args in true end
nipkow@4820
   467
                         handle Pattern => false
nipkow@4820
   468
                    else forall pattern args
nipkow@4820
   469
                 end;
nipkow@4820
   470
wenzelm@12784
   471
wenzelm@12784
   472
(* rewriting -- simple but fast *)
wenzelm@12784
   473
berghofe@13195
   474
fun rewrite_term tsig rules procs tm =
wenzelm@12784
   475
  let
berghofe@13195
   476
    val skel0 = Bound 0;
berghofe@13195
   477
wenzelm@12797
   478
    val rhs_names =
skalberg@15574
   479
      foldr (fn ((_, rhs), names) => add_term_free_names (rhs, names)) [] rules;
berghofe@13195
   480
wenzelm@12797
   481
    fun variant_absfree (x, T, t) =
wenzelm@12797
   482
      let
wenzelm@12797
   483
        val x' = variant (add_term_free_names (t, rhs_names)) x;
wenzelm@12797
   484
        val t' = subst_bound (Free (x', T), t);
wenzelm@12797
   485
      in (fn u => Abs (x, T, abstract_over (Free (x', T), u)), t') end;
wenzelm@12797
   486
wenzelm@12784
   487
    fun match_rew tm (tm1, tm2) =
skalberg@15570
   488
      let val rtm = getOpt (Term.rename_abs tm1 tm tm2, tm2)
berghofe@15797
   489
      in SOME (Envir.subst_vars (match tsig (tm1, tm)) rtm, rtm)
skalberg@15531
   490
        handle MATCH => NONE
berghofe@13195
   491
      end;
wenzelm@12784
   492
skalberg@15531
   493
    fun rew (Abs (_, _, body) $ t) = SOME (subst_bound (t, body), skel0)
berghofe@13195
   494
      | rew tm = (case get_first (match_rew tm) rules of
skalberg@15570
   495
          NONE => Option.map (rpair skel0) (get_first (fn p => p tm) procs)
berghofe@13195
   496
        | x => x);
berghofe@13195
   497
skalberg@15531
   498
    fun rew1 (Var _) _ = NONE
berghofe@13195
   499
      | rew1 skel tm = (case rew2 skel tm of
skalberg@15531
   500
          SOME tm1 => (case rew tm1 of
skalberg@15570
   501
              SOME (tm2, skel') => SOME (getOpt (rew1 skel' tm2, tm2))
skalberg@15531
   502
            | NONE => SOME tm1)
skalberg@15531
   503
        | NONE => (case rew tm of
skalberg@15570
   504
              SOME (tm1, skel') => SOME (getOpt (rew1 skel' tm1, tm1))
skalberg@15531
   505
            | NONE => NONE))
wenzelm@12784
   506
berghofe@13195
   507
    and rew2 skel (tm1 $ tm2) = (case tm1 of
wenzelm@12784
   508
            Abs (_, _, body) =>
wenzelm@12784
   509
              let val tm' = subst_bound (tm2, body)
skalberg@15570
   510
              in SOME (getOpt (rew2 skel0 tm', tm')) end
wenzelm@14787
   511
          | _ =>
berghofe@13195
   512
            let val (skel1, skel2) = (case skel of
berghofe@13195
   513
                skel1 $ skel2 => (skel1, skel2)
berghofe@13195
   514
              | _ => (skel0, skel0))
berghofe@13195
   515
            in case rew1 skel1 tm1 of
skalberg@15531
   516
                SOME tm1' => (case rew1 skel2 tm2 of
skalberg@15531
   517
                    SOME tm2' => SOME (tm1' $ tm2')
skalberg@15531
   518
                  | NONE => SOME (tm1' $ tm2))
skalberg@15531
   519
              | NONE => (case rew1 skel2 tm2 of
skalberg@15531
   520
                    SOME tm2' => SOME (tm1 $ tm2')
skalberg@15531
   521
                  | NONE => NONE)
berghofe@13195
   522
            end)
berghofe@13195
   523
      | rew2 skel (Abs (x, T, tm)) =
berghofe@13195
   524
          let
berghofe@13195
   525
            val (abs, tm') = variant_absfree (x, T, tm);
berghofe@13195
   526
            val skel' = (case skel of Abs (_, _, skel') => skel' | _ => skel0)
berghofe@13195
   527
          in case rew1 skel' tm' of
skalberg@15531
   528
              SOME tm'' => SOME (abs tm'')
skalberg@15531
   529
            | NONE => NONE
wenzelm@12797
   530
          end
skalberg@15531
   531
      | rew2 _ _ = NONE
wenzelm@12784
   532
skalberg@15570
   533
  in getOpt (rew1 skel0 tm, tm) end;
wenzelm@12784
   534
clasohm@0
   535
end;
nipkow@13642
   536
nipkow@13642
   537
val trace_unify_fail = Pattern.trace_unify_fail;