src/Pure/unify.ML
author bulwahn
Tue Aug 31 08:00:53 2010 +0200 (2010-08-31)
changeset 38950 62578950e748
parent 37720 50a9e2fa4f6b
child 39116 f14735a88886
permissions -rw-r--r--
storing options for prolog code generation in the theory
berghofe@15797
     1
(*  Title:      Pure/unify.ML
wenzelm@16425
     2
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
clasohm@0
     3
    Copyright   Cambridge University 1992
clasohm@0
     4
wenzelm@16425
     5
Higher-Order Unification.
clasohm@0
     6
wenzelm@16425
     7
Types as well as terms are unified.  The outermost functions assume
wenzelm@16425
     8
the terms to be unified already have the same type.  In resolution,
wenzelm@16425
     9
this is assured because both have type "prop".
clasohm@0
    10
*)
clasohm@0
    11
wenzelm@16425
    12
signature UNIFY =
wenzelm@16425
    13
sig
wenzelm@24178
    14
  val trace_bound_value: Config.value Config.T
wenzelm@24178
    15
  val trace_bound: int Config.T
wenzelm@24178
    16
  val search_bound_value: Config.value Config.T
wenzelm@24178
    17
  val search_bound: int Config.T
wenzelm@24178
    18
  val trace_simp_value: Config.value Config.T
wenzelm@24178
    19
  val trace_simp: bool Config.T
wenzelm@24178
    20
  val trace_types_value: Config.value Config.T
wenzelm@24178
    21
  val trace_types: bool Config.T
wenzelm@16425
    22
  val unifiers: theory * Envir.env * ((term * term) list) ->
wenzelm@16425
    23
    (Envir.env * (term * term) list) Seq.seq
wenzelm@19864
    24
  val smash_unifiers: theory -> (term * term) list -> Envir.env -> Envir.env Seq.seq
wenzelm@19864
    25
  val matchers: theory -> (term * term) list -> Envir.env Seq.seq
wenzelm@19864
    26
  val matches_list: theory -> term list -> term list -> bool
wenzelm@16425
    27
end
clasohm@0
    28
wenzelm@19864
    29
structure Unify : UNIFY =
clasohm@0
    30
struct
clasohm@0
    31
clasohm@0
    32
(*Unification options*)
clasohm@0
    33
wenzelm@24178
    34
(*tracing starts above this depth, 0 for full*)
wenzelm@36001
    35
val trace_bound_value = Config.declare true "unify_trace_bound" (K (Config.Int 50));
wenzelm@24178
    36
val trace_bound = Config.int trace_bound_value;
wenzelm@24178
    37
wenzelm@24178
    38
(*unification quits above this depth*)
wenzelm@36001
    39
val search_bound_value = Config.declare true "unify_search_bound" (K (Config.Int 60));
wenzelm@24178
    40
val search_bound = Config.int search_bound_value;
wenzelm@24178
    41
wenzelm@24178
    42
(*print dpairs before calling SIMPL*)
wenzelm@36001
    43
val trace_simp_value = Config.declare true "unify_trace_simp" (K (Config.Bool false));
wenzelm@24178
    44
val trace_simp = Config.bool trace_simp_value;
wenzelm@24178
    45
wenzelm@24178
    46
(*announce potential incompleteness of type unification*)
wenzelm@36001
    47
val trace_types_value = Config.declare true "unify_trace_types" (K (Config.Bool false));
wenzelm@24178
    48
val trace_types = Config.bool trace_types_value;
wenzelm@24178
    49
clasohm@0
    50
clasohm@0
    51
type binderlist = (string*typ) list;
clasohm@0
    52
clasohm@0
    53
type dpair = binderlist * term * term;
clasohm@0
    54
wenzelm@32032
    55
fun body_type env =
wenzelm@32032
    56
  let
wenzelm@32032
    57
    val tyenv = Envir.type_env env;
wenzelm@32032
    58
    fun bT (Type ("fun", [_, T])) = bT T
wenzelm@32032
    59
      | bT (T as TVar v) =
wenzelm@32032
    60
          (case Type.lookup tyenv v of
wenzelm@32032
    61
            NONE => T
wenzelm@32032
    62
          | SOME T' => bT T')
wenzelm@32032
    63
      | bT T = T;
wenzelm@32032
    64
  in bT end;
clasohm@0
    65
wenzelm@32032
    66
fun binder_types env =
wenzelm@32032
    67
  let
wenzelm@32032
    68
    val tyenv = Envir.type_env env;
wenzelm@32032
    69
    fun bTs (Type ("fun", [T, U])) = T :: bTs U
wenzelm@37636
    70
      | bTs (TVar v) =
wenzelm@32032
    71
          (case Type.lookup tyenv v of
wenzelm@32032
    72
            NONE => []
wenzelm@32032
    73
          | SOME T' => bTs T')
wenzelm@32032
    74
      | bTs _ = [];
wenzelm@32032
    75
  in bTs end;
clasohm@0
    76
clasohm@0
    77
fun strip_type env T = (binder_types env T, body_type env T);
clasohm@0
    78
berghofe@12231
    79
fun fastype env (Ts, t) = Envir.fastype env (map snd Ts) t;
clasohm@0
    80
clasohm@0
    81
wenzelm@32032
    82
(* eta normal form *)
wenzelm@32032
    83
wenzelm@32032
    84
fun eta_norm env =
wenzelm@32032
    85
  let
wenzelm@32032
    86
    val tyenv = Envir.type_env env;
wenzelm@32032
    87
    fun etif (Type ("fun", [T, U]), t) =
wenzelm@32032
    88
          Abs ("", T, etif (U, incr_boundvars 1 t $ Bound 0))
wenzelm@32032
    89
      | etif (TVar v, t) =
wenzelm@32032
    90
          (case Type.lookup tyenv v of
wenzelm@32032
    91
            NONE => t
wenzelm@32032
    92
          | SOME T => etif (T, t))
wenzelm@32032
    93
      | etif (_, t) = t;
wenzelm@32032
    94
    fun eta_nm (rbinder, Abs (a, T, body)) =
wenzelm@32032
    95
          Abs (a, T, eta_nm ((a, T) :: rbinder, body))
wenzelm@32032
    96
      | eta_nm (rbinder, t) = etif (fastype env (rbinder, t), t);
clasohm@0
    97
  in eta_nm end;
clasohm@0
    98
clasohm@0
    99
clasohm@0
   100
(*OCCURS CHECK
wenzelm@19864
   101
  Does the uvar occur in the term t?
clasohm@0
   102
  two forms of search, for whether there is a rigid path to the current term.
clasohm@0
   103
  "seen" is list of variables passed thru, is a memo variable for sharing.
berghofe@15797
   104
  This version searches for nonrigid occurrence, returns true if found.
berghofe@15797
   105
  Since terms may contain variables with same name and different types,
berghofe@15797
   106
  the occurs check must ignore the types of variables. This avoids
berghofe@15797
   107
  that ?x::?'a is unified with f(?x::T), which may lead to a cyclic
berghofe@15797
   108
  substitution when ?'a is instantiated with T later. *)
wenzelm@37635
   109
fun occurs_terms (seen: indexname list Unsynchronized.ref,
wenzelm@19864
   110
      env: Envir.env, v: indexname, ts: term list): bool =
wenzelm@37635
   111
  let
wenzelm@37635
   112
    fun occurs [] = false
wenzelm@37636
   113
      | occurs (t :: ts) = occur t orelse occurs ts
wenzelm@37635
   114
    and occur (Const _) = false
wenzelm@37635
   115
      | occur (Bound _) = false
wenzelm@37635
   116
      | occur (Free _) = false
wenzelm@37635
   117
      | occur (Var (w, T)) =
wenzelm@37635
   118
          if member (op =) (!seen) w then false
wenzelm@37635
   119
          else if Term.eq_ix (v, w) then true
wenzelm@37635
   120
            (*no need to lookup: v has no assignment*)
wenzelm@37635
   121
          else
wenzelm@37635
   122
            (seen := w :: !seen;
wenzelm@37635
   123
             case Envir.lookup (env, (w, T)) of
wenzelm@37635
   124
               NONE => false
wenzelm@37635
   125
             | SOME t => occur t)
wenzelm@37635
   126
      | occur (Abs (_, _, body)) = occur body
wenzelm@37635
   127
      | occur (f $ t) = occur t orelse occur f;
wenzelm@37635
   128
  in occurs ts end;
clasohm@0
   129
clasohm@0
   130
clasohm@0
   131
(* f(a1,...,an)  ---->   (f,  [a1,...,an])  using the assignments*)
wenzelm@37635
   132
fun head_of_in (env, t) : term =
wenzelm@37635
   133
  (case t of
wenzelm@37635
   134
    f $ _ => head_of_in (env, f)
wenzelm@37635
   135
  | Var vT =>
wenzelm@37635
   136
      (case Envir.lookup (env, vT) of
wenzelm@37635
   137
        SOME u => head_of_in (env, u)
wenzelm@37635
   138
      | NONE => t)
wenzelm@37635
   139
  | _ => t);
clasohm@0
   140
clasohm@0
   141
clasohm@0
   142
datatype occ = NoOcc | Nonrigid | Rigid;
clasohm@0
   143
clasohm@0
   144
(* Rigid occur check
clasohm@0
   145
Returns Rigid    if it finds a rigid occurrence of the variable,
clasohm@0
   146
        Nonrigid if it finds a nonrigid path to the variable.
clasohm@0
   147
        NoOcc    otherwise.
clasohm@0
   148
  Continues searching for a rigid occurrence even if it finds a nonrigid one.
clasohm@0
   149
clasohm@0
   150
Condition for detecting non-unifable terms: [ section 5.3 of Huet (1975) ]
clasohm@0
   151
   a rigid path to the variable, appearing with no arguments.
clasohm@0
   152
Here completeness is sacrificed in order to reduce danger of divergence:
clasohm@0
   153
   reject ALL rigid paths to the variable.
wenzelm@19864
   154
Could check for rigid paths to bound variables that are out of scope.
clasohm@0
   155
Not necessary because the assignment test looks at variable's ENTIRE rbinder.
clasohm@0
   156
clasohm@0
   157
Treatment of head(arg1,...,argn):
clasohm@0
   158
If head is a variable then no rigid path, switch to nonrigid search
wenzelm@19864
   159
for arg1,...,argn.
wenzelm@19864
   160
If head is an abstraction then possibly no rigid path (head could be a
clasohm@0
   161
   constant function) so again use nonrigid search.  Happens only if
wenzelm@19864
   162
   term is not in normal form.
clasohm@0
   163
clasohm@0
   164
Warning: finds a rigid occurrence of ?f in ?f(t).
clasohm@0
   165
  Should NOT be called in this case: there is a flex-flex unifier
clasohm@0
   166
*)
wenzelm@37635
   167
fun rigid_occurs_term (seen: indexname list Unsynchronized.ref, env, v: indexname, t) =
wenzelm@37635
   168
  let
wenzelm@37635
   169
    fun nonrigid t =
wenzelm@37635
   170
      if occurs_terms (seen, env, v, [t]) then Nonrigid
wenzelm@37635
   171
      else NoOcc
wenzelm@37635
   172
    fun occurs [] = NoOcc
wenzelm@37635
   173
      | occurs (t :: ts) =
wenzelm@37635
   174
          (case occur t of
wenzelm@37635
   175
            Rigid => Rigid
wenzelm@37635
   176
          | oc => (case occurs ts of NoOcc => oc | oc2 => oc2))
wenzelm@37635
   177
    and occomb (f $ t) =
wenzelm@37635
   178
        (case occur t of
wenzelm@37635
   179
          Rigid => Rigid
wenzelm@37635
   180
        | oc => (case occomb f of NoOcc => oc | oc2 => oc2))
wenzelm@37635
   181
      | occomb t = occur t
wenzelm@37635
   182
    and occur (Const _) = NoOcc
wenzelm@37635
   183
      | occur (Bound _) = NoOcc
wenzelm@37635
   184
      | occur (Free _) = NoOcc
wenzelm@37635
   185
      | occur (Var (w, T)) =
wenzelm@37635
   186
          if member (op =) (!seen) w then NoOcc
wenzelm@37635
   187
          else if Term.eq_ix (v, w) then Rigid
wenzelm@37635
   188
          else
wenzelm@37635
   189
            (seen := w :: !seen;
wenzelm@37635
   190
             case Envir.lookup (env, (w, T)) of
wenzelm@37635
   191
               NONE => NoOcc
wenzelm@37635
   192
             | SOME t => occur t)
wenzelm@37635
   193
      | occur (Abs (_, _, body)) = occur body
wenzelm@37635
   194
      | occur (t as f $ _) =  (*switch to nonrigid search?*)
wenzelm@37635
   195
          (case head_of_in (env, f) of
wenzelm@37635
   196
            Var (w,_) => (*w is not assigned*)
wenzelm@37635
   197
              if Term.eq_ix (v, w) then Rigid
wenzelm@37635
   198
              else nonrigid t
wenzelm@37636
   199
          | Abs _ => nonrigid t (*not in normal form*)
wenzelm@37635
   200
          | _ => occomb t)
wenzelm@37635
   201
  in occur t end;
clasohm@0
   202
clasohm@0
   203
wenzelm@19864
   204
exception CANTUNIFY;  (*Signals non-unifiability.  Does not signal errors!*)
wenzelm@37635
   205
exception ASSIGN;  (*Raised if not an assignment*)
clasohm@0
   206
clasohm@0
   207
wenzelm@32032
   208
fun unify_types thy (T, U, env) =
wenzelm@32032
   209
  if T = U then env
wenzelm@32032
   210
  else
wenzelm@32032
   211
    let
wenzelm@32032
   212
      val Envir.Envir {maxidx, tenv, tyenv} = env;
wenzelm@32032
   213
      val (tyenv', maxidx') = Sign.typ_unify thy (U, T) (tyenv, maxidx);
wenzelm@32032
   214
    in Envir.Envir {maxidx = maxidx', tenv = tenv, tyenv = tyenv'} end
wenzelm@32032
   215
    handle Type.TUNIFY => raise CANTUNIFY;
clasohm@0
   216
wenzelm@37635
   217
fun test_unify_types thy (args as (T, U, _)) =
wenzelm@37635
   218
  let
wenzelm@37635
   219
    val str_of = Syntax.string_of_typ_global thy;
wenzelm@37635
   220
    fun warn () = tracing ("Potential loss of completeness: " ^ str_of U ^ " = " ^ str_of T);
wenzelm@37635
   221
    val env' = unify_types thy args;
wenzelm@37635
   222
  in if is_TVar T orelse is_TVar U then warn () else (); env' end;
clasohm@0
   223
clasohm@0
   224
(*Is the term eta-convertible to a single variable with the given rbinder?
clasohm@0
   225
  Examples: ?a   ?f(B.0)   ?g(B.1,B.0)
clasohm@0
   226
  Result is var a for use in SIMPL. *)
wenzelm@37635
   227
fun get_eta_var ([], _, Var vT) = vT
clasohm@0
   228
  | get_eta_var (_::rbinder, n, f $ Bound i) =
wenzelm@37635
   229
      if n = i then get_eta_var (rbinder, n + 1, f)
wenzelm@37635
   230
      else raise ASSIGN
clasohm@0
   231
  | get_eta_var _ = raise ASSIGN;
clasohm@0
   232
clasohm@0
   233
clasohm@0
   234
(*Solve v=u by assignment -- "fixedpoint" to Huet -- if v not in u.
clasohm@0
   235
  If v occurs rigidly then nonunifiable.
clasohm@0
   236
  If v occurs nonrigidly then must use full algorithm. *)
wenzelm@16664
   237
fun assignment thy (env, rbinder, t, u) =
wenzelm@37635
   238
  let val vT as (v,T) = get_eta_var (rbinder, 0, t) in
wenzelm@37635
   239
    (case rigid_occurs_term (Unsynchronized.ref [], env, v, u) of
wenzelm@37635
   240
      NoOcc =>
wenzelm@37635
   241
        let val env = unify_types thy (body_type env T, fastype env (rbinder, u), env)
wenzelm@37635
   242
        in Envir.update ((vT, Logic.rlist_abs (rbinder, u)), env) end
wenzelm@37635
   243
    | Nonrigid => raise ASSIGN
wenzelm@37635
   244
    | Rigid => raise CANTUNIFY)
wenzelm@37635
   245
  end;
clasohm@0
   246
clasohm@0
   247
clasohm@0
   248
(*Extends an rbinder with a new disagreement pair, if both are abstractions.
clasohm@0
   249
  Tries to unify types of the bound variables!
clasohm@0
   250
  Checks that binders have same length, since terms should be eta-normal;
clasohm@0
   251
    if not, raises TERM, probably indicating type mismatch.
wenzelm@19864
   252
  Uses variable a (unless the null string) to preserve user's naming.*)
wenzelm@37635
   253
fun new_dpair thy (rbinder, Abs (a, T, body1), Abs (b, U, body2), env) =
wenzelm@37635
   254
      let
wenzelm@37635
   255
        val env' = unify_types thy (T, U, env);
wenzelm@37635
   256
        val c = if a = "" then b else a;
wenzelm@37635
   257
      in new_dpair thy ((c,T) :: rbinder, body1, body2, env') end
wenzelm@37635
   258
  | new_dpair _ (_, Abs _, _, _) = raise TERM ("new_dpair", [])
wenzelm@37635
   259
  | new_dpair _ (_, _, Abs _, _) = raise TERM ("new_dpair", [])
wenzelm@37635
   260
  | new_dpair _ (rbinder, t1, t2, env) = ((rbinder, t1, t2), env);
clasohm@0
   261
clasohm@0
   262
wenzelm@37635
   263
fun head_norm_dpair thy (env, (rbinder, t, u)) : dpair * Envir.env =
wenzelm@37635
   264
  new_dpair thy (rbinder,
wenzelm@19864
   265
    eta_norm env (rbinder, Envir.head_norm env t),
wenzelm@37635
   266
    eta_norm env (rbinder, Envir.head_norm env u), env);
clasohm@0
   267
clasohm@0
   268
clasohm@0
   269
clasohm@0
   270
(*flexflex: the flex-flex pairs,  flexrigid: the flex-rigid pairs
clasohm@0
   271
  Does not perform assignments for flex-flex pairs:
lcp@646
   272
    may create nonrigid paths, which prevent other assignments.
lcp@646
   273
  Does not even identify Vars in dpairs such as ?a =?= ?b; an attempt to
lcp@646
   274
    do so caused numerous problems with no compensating advantage.
lcp@646
   275
*)
wenzelm@37635
   276
fun SIMPL0 thy (dp0, (env,flexflex,flexrigid)) : Envir.env * dpair list * dpair list =
wenzelm@37635
   277
  let
wenzelm@37635
   278
    val (dp as (rbinder, t, u), env) = head_norm_dpair thy (env, dp0);
wenzelm@37635
   279
    fun SIMRANDS (f $ t, g $ u, env) =
wenzelm@37635
   280
          SIMPL0 thy ((rbinder, t, u), SIMRANDS (f, g, env))
wenzelm@37635
   281
      | SIMRANDS (t as _$_, _, _) =
wenzelm@37635
   282
          raise TERM ("SIMPL: operands mismatch", [t, u])
wenzelm@37635
   283
      | SIMRANDS (t, u as _ $ _, _) =
wenzelm@37635
   284
          raise TERM ("SIMPL: operands mismatch", [t, u])
wenzelm@37635
   285
      | SIMRANDS (_, _, env) = (env, flexflex, flexrigid);
wenzelm@37635
   286
  in
wenzelm@37635
   287
    (case (head_of t, head_of u) of
wenzelm@37635
   288
      (Var (_, T), Var (_, U)) =>
wenzelm@37635
   289
        let
wenzelm@37635
   290
          val T' = body_type env T and U' = body_type env U;
wenzelm@37635
   291
          val env = unify_types thy (T', U', env);
wenzelm@37635
   292
        in (env, dp :: flexflex, flexrigid) end
wenzelm@37635
   293
    | (Var _, _) =>
wenzelm@37635
   294
        ((assignment thy (env, rbinder,t,u), flexflex, flexrigid)
wenzelm@37635
   295
          handle ASSIGN => (env, flexflex, dp :: flexrigid))
wenzelm@37635
   296
    | (_, Var _) =>
wenzelm@37635
   297
        ((assignment thy (env, rbinder, u, t), flexflex, flexrigid)
wenzelm@37635
   298
          handle ASSIGN => (env, flexflex, (rbinder, u, t) :: flexrigid))
wenzelm@37635
   299
    | (Const (a, T), Const (b, U)) =>
wenzelm@37635
   300
        if a = b then SIMRANDS (t, u, unify_types thy (T, U, env))
wenzelm@37635
   301
        else raise CANTUNIFY
wenzelm@37635
   302
    | (Bound i, Bound j) =>
wenzelm@37635
   303
        if i = j then SIMRANDS (t, u, env) else raise CANTUNIFY
wenzelm@37635
   304
    | (Free (a, T), Free (b, U)) =>
wenzelm@37635
   305
        if a = b then SIMRANDS (t, u, unify_types thy (T, U, env))
wenzelm@37635
   306
        else raise CANTUNIFY
wenzelm@37635
   307
    | _ => raise CANTUNIFY)
wenzelm@37635
   308
  end;
clasohm@0
   309
clasohm@0
   310
clasohm@0
   311
(* changed(env,t) checks whether the head of t is a variable assigned in env*)
wenzelm@37635
   312
fun changed (env, f $ _) = changed (env, f)
wenzelm@37635
   313
  | changed (env, Var v) = (case Envir.lookup (env, v) of NONE => false | _ => true)
clasohm@0
   314
  | changed _ = false;
clasohm@0
   315
clasohm@0
   316
clasohm@0
   317
(*Recursion needed if any of the 'head variables' have been updated
clasohm@0
   318
  Clever would be to re-do just the affected dpairs*)
wenzelm@16664
   319
fun SIMPL thy (env,dpairs) : Envir.env * dpair list * dpair list =
wenzelm@37635
   320
  let
wenzelm@37635
   321
    val all as (env', flexflex, flexrigid) = List.foldr (SIMPL0 thy) (env, [], []) dpairs;
wenzelm@37635
   322
    val dps = flexrigid @ flexflex;
wenzelm@37635
   323
  in
wenzelm@37635
   324
    if exists (fn (_, t, u) => changed (env', t) orelse changed (env', u)) dps
wenzelm@37635
   325
    then SIMPL thy (env', dps) else all
wenzelm@37635
   326
  end;
clasohm@0
   327
clasohm@0
   328
wenzelm@19864
   329
(*Makes the terms E1,...,Em,    where Ts = [T...Tm].
clasohm@0
   330
  Each Ei is   ?Gi(B.(n-1),...,B.0), and has type Ti
clasohm@0
   331
  The B.j are bound vars of binder.
wenzelm@19864
   332
  The terms are not made in eta-normal-form, SIMPL does that later.
clasohm@0
   333
  If done here, eta-expansion must be recursive in the arguments! *)
wenzelm@37636
   334
fun make_args _ (_, env, []) = (env, [])   (*frequent case*)
clasohm@0
   335
  | make_args name (binder: typ list, env, Ts) : Envir.env * term list =
wenzelm@37635
   336
      let
wenzelm@37635
   337
        fun funtype T = binder ---> T;
wenzelm@37635
   338
        val (env', vars) = Envir.genvars name (env, map funtype Ts);
wenzelm@37635
   339
      in (env', map (fn var => Logic.combound (var, 0, length binder)) vars) end;
clasohm@0
   340
clasohm@0
   341
clasohm@0
   342
(*Abstraction over a list of types, like list_abs*)
wenzelm@37635
   343
fun types_abs ([], u) = u
wenzelm@37635
   344
  | types_abs (T :: Ts, u) = Abs ("", T, types_abs (Ts, u));
clasohm@0
   345
clasohm@0
   346
(*Abstraction over the binder of a type*)
wenzelm@37635
   347
fun type_abs (env, T, t) = types_abs (binder_types env T, t);
clasohm@0
   348
clasohm@0
   349
clasohm@0
   350
(*MATCH taking "big steps".
clasohm@0
   351
  Copies u into the Var v, using projection on targs or imitation.
clasohm@0
   352
  A projection is allowed unless SIMPL raises an exception.
clasohm@0
   353
  Allocates new variables in projection on a higher-order argument,
clasohm@0
   354
    or if u is a variable (flex-flex dpair).
clasohm@0
   355
  Returns long sequence of every way of copying u, for backtracking
clasohm@0
   356
  For example, projection in ?b'(?a) may be wrong if other dpairs constrain ?a.
wenzelm@19864
   357
  The order for trying projections is crucial in ?b'(?a)
clasohm@0
   358
  NB "vname" is only used in the call to make_args!!   *)
wenzelm@37635
   359
fun matchcopy thy vname =
wenzelm@37635
   360
  let
wenzelm@37635
   361
    fun mc (rbinder, targs, u, ed as (env, dpairs)) : (term * (Envir.env * dpair list)) Seq.seq =
wenzelm@37635
   362
      let
wenzelm@37635
   363
        val trace_tps = Config.get_global thy trace_types;
wenzelm@37635
   364
        (*Produce copies of uarg and cons them in front of uargs*)
wenzelm@37635
   365
        fun copycons uarg (uargs, (env, dpairs)) =
wenzelm@37635
   366
          Seq.map (fn (uarg', ed') => (uarg' :: uargs, ed'))
wenzelm@37635
   367
            (mc (rbinder, targs,eta_norm env (rbinder, Envir.head_norm env uarg),
wenzelm@37635
   368
              (env, dpairs)));
wenzelm@37635
   369
        (*Produce sequence of all possible ways of copying the arg list*)
wenzelm@37635
   370
        fun copyargs [] = Seq.cons ([], ed) Seq.empty
wenzelm@37635
   371
          | copyargs (uarg :: uargs) = Seq.maps (copycons uarg) (copyargs uargs);
wenzelm@37635
   372
        val (uhead, uargs) = strip_comb u;
wenzelm@37635
   373
        val base = body_type env (fastype env (rbinder, uhead));
wenzelm@37635
   374
        fun joinargs (uargs', ed') = (list_comb (uhead, uargs'), ed');
wenzelm@37635
   375
        (*attempt projection on argument with given typ*)
wenzelm@37635
   376
        val Ts = map (curry (fastype env) rbinder) targs;
wenzelm@37635
   377
        fun projenv (head, (Us, bary), targ, tail) =
wenzelm@37635
   378
          let
wenzelm@37635
   379
            val env =
wenzelm@37635
   380
              if trace_tps then test_unify_types thy (base, bary, env)
wenzelm@37635
   381
              else unify_types thy (base, bary, env)
wenzelm@37635
   382
          in
wenzelm@37635
   383
            Seq.make (fn () =>
wenzelm@37635
   384
              let
wenzelm@37635
   385
                val (env', args) = make_args vname (Ts, env, Us);
wenzelm@37635
   386
                (*higher-order projection: plug in targs for bound vars*)
wenzelm@37635
   387
                fun plugin arg = list_comb (head_of arg, targs);
wenzelm@37635
   388
                val dp = (rbinder, list_comb (targ, map plugin args), u);
wenzelm@37635
   389
                val (env2, frigid, fflex) = SIMPL thy (env', dp :: dpairs);
wenzelm@37635
   390
                (*may raise exception CANTUNIFY*)
wenzelm@37635
   391
              in
wenzelm@37635
   392
                SOME ((list_comb (head, args), (env2, frigid @ fflex)), tail)
wenzelm@37635
   393
              end handle CANTUNIFY => Seq.pull tail)
wenzelm@37635
   394
          end handle CANTUNIFY => tail;
wenzelm@37635
   395
        (*make a list of projections*)
wenzelm@37635
   396
        fun make_projs (T::Ts, targ::targs) =
wenzelm@37635
   397
            (Bound(length Ts), T, targ) :: make_projs (Ts,targs)
wenzelm@37635
   398
          | make_projs ([],[]) = []
wenzelm@37635
   399
          | make_projs _ = raise TERM ("make_projs", u::targs);
wenzelm@37635
   400
        (*try projections and imitation*)
wenzelm@37635
   401
        fun matchfun ((bvar,T,targ)::projs) =
wenzelm@37635
   402
             (projenv(bvar, strip_type env T, targ, matchfun projs))
wenzelm@37635
   403
          | matchfun [] = (*imitation last of all*)
wenzelm@37635
   404
            (case uhead of
wenzelm@37635
   405
         Const _ => Seq.map joinargs (copyargs uargs)
wenzelm@37635
   406
             | Free _  => Seq.map joinargs (copyargs uargs)
wenzelm@37635
   407
             | _ => Seq.empty)  (*if Var, would be a loop!*)
wenzelm@37635
   408
    in
wenzelm@37635
   409
      (case uhead of
wenzelm@37635
   410
        Abs (a, T, body) =>
wenzelm@37635
   411
          Seq.map (fn (body', ed') => (Abs (a, T, body'), ed'))
wenzelm@37635
   412
            (mc ((a, T) :: rbinder, (map (incr_boundvars 1) targs) @ [Bound 0], body, ed))
wenzelm@37636
   413
      | Var (w, _) =>
wenzelm@37635
   414
          (*a flex-flex dpair: make variable for t*)
wenzelm@37635
   415
          let
wenzelm@37635
   416
            val (env', newhd) = Envir.genvar (#1 w) (env, Ts ---> base);
wenzelm@37635
   417
            val tabs = Logic.combound (newhd, 0, length Ts);
wenzelm@37635
   418
            val tsub = list_comb (newhd, targs);
wenzelm@37635
   419
          in Seq.single (tabs, (env', (rbinder, tsub, u) :: dpairs)) end
wenzelm@37635
   420
      | _ => matchfun (rev (make_projs (Ts, targs))))
wenzelm@37635
   421
    end;
wenzelm@37635
   422
  in mc end;
clasohm@0
   423
clasohm@0
   424
clasohm@0
   425
(*Call matchcopy to produce assignments to the variable in the dpair*)
wenzelm@37635
   426
fun MATCH thy (env, (rbinder, t, u), dpairs) : (Envir.env * dpair list) Seq.seq =
wenzelm@37635
   427
  let
wenzelm@37635
   428
    val (Var (vT as (v, T)), targs) = strip_comb t;
wenzelm@37635
   429
    val Ts = binder_types env T;
wenzelm@37635
   430
    fun new_dset (u', (env', dpairs')) =
wenzelm@37635
   431
      (*if v was updated to s, must unify s with u' *)
wenzelm@37635
   432
      (case Envir.lookup (env', vT) of
wenzelm@37635
   433
        NONE => (Envir.update ((vT, types_abs (Ts, u')), env'), dpairs')
wenzelm@37635
   434
      | SOME s => (env', ([], s, types_abs (Ts, u')) :: dpairs'));
wenzelm@37635
   435
  in
wenzelm@37635
   436
    Seq.map new_dset (matchcopy thy (#1 v) (rbinder, targs, u, (env, dpairs)))
clasohm@0
   437
  end;
clasohm@0
   438
clasohm@0
   439
clasohm@0
   440
clasohm@0
   441
(**** Flex-flex processing ****)
clasohm@0
   442
wenzelm@19864
   443
(*At end of unification, do flex-flex assignments like ?a -> ?f(?b)
clasohm@0
   444
  Attempts to update t with u, raising ASSIGN if impossible*)
wenzelm@19864
   445
fun ff_assign thy (env, rbinder, t, u) : Envir.env =
wenzelm@37635
   446
  let val vT as (v, T) = get_eta_var (rbinder, 0, t) in
wenzelm@37635
   447
    if occurs_terms (Unsynchronized.ref [], env, v, [u]) then raise ASSIGN
wenzelm@37635
   448
    else
wenzelm@37635
   449
      let val env = unify_types thy (body_type env T, fastype env (rbinder, u), env)
wenzelm@37635
   450
      in Envir.vupdate ((vT, Logic.rlist_abs (rbinder, u)), env) end
wenzelm@37635
   451
  end;
clasohm@0
   452
clasohm@0
   453
paulson@37720
   454
(*If an argument contains a banned Bound, then it should be deleted.
paulson@37720
   455
  But if the only path is flexible, this is difficult; the code gives up!
paulson@37720
   456
  In  %x y.?a(x) =?= %x y.?b(?c(y)) should we instantiate ?b or ?c *)
paulson@37720
   457
exception CHANGE_FAIL;   (*flexible occurrence of banned variable, or other reason to quit*)
paulson@37720
   458
paulson@37720
   459
clasohm@0
   460
(*Flex argument: a term, its type, and the index that refers to it.*)
wenzelm@37635
   461
type flarg = {t: term, T: typ, j: int};
clasohm@0
   462
clasohm@0
   463
(*Form the arguments into records for deletion/sorting.*)
wenzelm@37635
   464
fun flexargs ([], [], []) = [] : flarg list
wenzelm@37635
   465
  | flexargs (j :: js, t :: ts, T :: Ts) = {j = j, t = t, T = T} :: flexargs (js, ts, Ts)
paulson@37720
   466
  | flexargs _ = raise CHANGE_FAIL;
paulson@37720
   467
(*We give up if we see a variable of function type not applied to a full list of 
paulson@37720
   468
  arguments (remember, this code assumes that terms are fully eta-expanded).  This situation 
paulson@37720
   469
  can occur if a type variable is instantiated with a function type.
paulson@37720
   470
*)
clasohm@0
   471
lcp@651
   472
(*Check whether the 'banned' bound var indices occur rigidly in t*)
wenzelm@19864
   473
fun rigid_bound (lev, banned) t =
wenzelm@37635
   474
  let val (head,args) = strip_comb t in
wenzelm@37635
   475
    (case head of
wenzelm@37635
   476
      Bound i =>
wenzelm@37635
   477
        member (op =) banned (i - lev) orelse exists (rigid_bound (lev, banned)) args
wenzelm@37635
   478
    | Var _ => false  (*no rigid occurrences here!*)
wenzelm@37635
   479
    | Abs (_, _, u) =>
wenzelm@37635
   480
        rigid_bound (lev + 1, banned) u orelse
wenzelm@37635
   481
        exists (rigid_bound (lev, banned)) args
wenzelm@37635
   482
    | _ => exists (rigid_bound (lev, banned)) args)
clasohm@0
   483
  end;
clasohm@0
   484
lcp@651
   485
(*Squash down indices at level >=lev to delete the banned from a term.*)
lcp@651
   486
fun change_bnos banned =
wenzelm@37635
   487
  let
wenzelm@37635
   488
    fun change lev (Bound i) =
wenzelm@37635
   489
          if i < lev then Bound i
wenzelm@37635
   490
          else if member (op =) banned (i - lev) then
wenzelm@37635
   491
            raise CHANGE_FAIL (**flexible occurrence: give up**)
wenzelm@37635
   492
          else Bound (i - length (filter (fn j => j < i - lev) banned))
wenzelm@37635
   493
      | change lev (Abs (a, T, t)) = Abs (a, T, change(lev + 1) t)
wenzelm@37635
   494
      | change lev (t $ u) = change lev t $ change lev u
wenzelm@37635
   495
      | change lev t = t;
wenzelm@37635
   496
  in change 0 end;
clasohm@0
   497
clasohm@0
   498
(*Change indices, delete the argument if it contains a banned Bound*)
wenzelm@37635
   499
fun change_arg banned ({j, t, T}, args) : flarg list =
wenzelm@37635
   500
  if rigid_bound (0, banned) t then args  (*delete argument!*)
wenzelm@37635
   501
  else {j = j, t = change_bnos banned t, T = T} :: args;
clasohm@0
   502
clasohm@0
   503
clasohm@0
   504
(*Sort the arguments to create assignments if possible:
clasohm@0
   505
  create eta-terms like ?g(B.1,B.0) *)
wenzelm@37635
   506
fun arg_less ({t = Bound i1, ...}, {t = Bound i2, ...}) = (i2 < i1)
wenzelm@37635
   507
  | arg_less (_: flarg, _: flarg) = false;
clasohm@0
   508
clasohm@0
   509
(*Test whether the new term would be eta-equivalent to a variable --
clasohm@0
   510
  if so then there is no point in creating a new variable*)
wenzelm@37635
   511
fun decreasing n ([]: flarg list) = (n = 0)
wenzelm@37635
   512
  | decreasing n ({j, ...} :: args) = j = n - 1 andalso decreasing (n - 1) args;
clasohm@0
   513
clasohm@0
   514
(*Delete banned indices in the term, simplifying it.
clasohm@0
   515
  Force an assignment, if possible, by sorting the arguments.
clasohm@0
   516
  Update its head; squash indices in arguments. *)
clasohm@0
   517
fun clean_term banned (env,t) =
wenzelm@37635
   518
  let
wenzelm@37635
   519
    val (Var (v, T), ts) = strip_comb t;
wenzelm@37635
   520
    val (Ts, U) = strip_type env T
wenzelm@37635
   521
    and js = length ts - 1  downto 0;
paulson@37720
   522
    val args = sort (make_ord arg_less) (List.foldr (change_arg banned) [] (flexargs (js, ts, Ts))) 
wenzelm@37635
   523
    val ts' = map #t args;
wenzelm@37635
   524
  in
wenzelm@37635
   525
    if decreasing (length Ts) args then (env, (list_comb (Var (v, T), ts')))
wenzelm@37635
   526
    else
wenzelm@37635
   527
      let
wenzelm@37635
   528
        val (env', v') = Envir.genvar (#1 v) (env, map #T args ---> U);
wenzelm@37635
   529
        val body = list_comb (v', map (Bound o #j) args);
wenzelm@37635
   530
        val env2 = Envir.vupdate ((((v, T), types_abs (Ts, body)), env'));
wenzelm@37635
   531
        (*the vupdate affects ts' if they contain v*)
wenzelm@37635
   532
      in (env2, Envir.norm_term env2 (list_comb (v', ts'))) end
wenzelm@37635
   533
  end;
clasohm@0
   534
clasohm@0
   535
clasohm@0
   536
(*Add tpair if not trivial or already there.
clasohm@0
   537
  Should check for swapped pairs??*)
wenzelm@37635
   538
fun add_tpair (rbinder, (t0, u0), tpairs) : (term * term) list =
wenzelm@19864
   539
  if t0 aconv u0 then tpairs
clasohm@0
   540
  else
wenzelm@37635
   541
    let
wenzelm@37635
   542
      val t = Logic.rlist_abs (rbinder, t0)
wenzelm@37635
   543
      and u = Logic.rlist_abs (rbinder, u0);
wenzelm@37635
   544
      fun same (t', u') = (t aconv t') andalso (u aconv u')
wenzelm@37635
   545
    in if exists same tpairs then tpairs else (t, u) :: tpairs end;
clasohm@0
   546
clasohm@0
   547
clasohm@0
   548
(*Simplify both terms and check for assignments.
clasohm@0
   549
  Bound vars in the binder are "banned" unless used in both t AND u *)
wenzelm@37635
   550
fun clean_ffpair thy ((rbinder, t, u), (env, tpairs)) =
wenzelm@37635
   551
  let
wenzelm@37635
   552
    val loot = loose_bnos t and loou = loose_bnos u
wenzelm@37635
   553
    fun add_index (j, (a, T)) (bnos, newbinder) =
wenzelm@37635
   554
      if member (op =) loot j andalso member (op =) loou j
wenzelm@37635
   555
      then (bnos, (a, T) :: newbinder)  (*needed by both: keep*)
wenzelm@37635
   556
      else (j :: bnos, newbinder);   (*remove*)
wenzelm@37635
   557
    val (banned, rbin') = fold_rev add_index ((0 upto (length rbinder - 1)) ~~ rbinder) ([], []);
wenzelm@37635
   558
    val (env', t') = clean_term banned (env, t);
wenzelm@37635
   559
    val (env'',u') = clean_term banned (env',u);
wenzelm@37635
   560
  in
wenzelm@37635
   561
    (ff_assign thy (env'', rbin', t', u'), tpairs)
wenzelm@37635
   562
      handle ASSIGN =>
wenzelm@37635
   563
        (ff_assign thy (env'', rbin', u', t'), tpairs)
wenzelm@37635
   564
          handle ASSIGN => (env'', add_tpair (rbin', (t', u'), tpairs))
clasohm@0
   565
  end
wenzelm@37635
   566
  handle CHANGE_FAIL => (env, add_tpair (rbinder, (t, u), tpairs));
clasohm@0
   567
clasohm@0
   568
clasohm@0
   569
(*IF the flex-flex dpair is an assignment THEN do it  ELSE  put in tpairs
clasohm@0
   570
  eliminates trivial tpairs like t=t, as well as repeated ones
wenzelm@19864
   571
  trivial tpairs can easily escape SIMPL:  ?A=t, ?A=?B, ?B=t gives t=t
clasohm@0
   572
  Resulting tpairs MAY NOT be in normal form:  assignments may occur here.*)
wenzelm@37635
   573
fun add_ffpair thy ((rbinder,t0,u0), (env,tpairs)) : Envir.env * (term * term) list =
wenzelm@37635
   574
  let
wenzelm@37635
   575
    val t = Envir.norm_term env t0
wenzelm@37635
   576
    and u = Envir.norm_term env u0;
wenzelm@37635
   577
  in
wenzelm@37635
   578
    (case (head_of t, head_of u) of
wenzelm@37635
   579
      (Var (v, T), Var (w, U)) =>  (*Check for identical variables...*)
wenzelm@37635
   580
        if Term.eq_ix (v, w) then     (*...occur check would falsely return true!*)
wenzelm@37635
   581
          if T = U then (env, add_tpair (rbinder, (t, u), tpairs))
wenzelm@37635
   582
          else raise TERM ("add_ffpair: Var name confusion", [t, u])
wenzelm@37635
   583
        else if Term_Ord.indexname_ord (v, w) = LESS then (*prefer to update the LARGER variable*)
wenzelm@37635
   584
          clean_ffpair thy ((rbinder, u, t), (env, tpairs))
wenzelm@37635
   585
        else clean_ffpair thy ((rbinder, t, u), (env, tpairs))
wenzelm@37635
   586
    | _ => raise TERM ("add_ffpair: Vars expected", [t, u]))
clasohm@0
   587
  end;
clasohm@0
   588
clasohm@0
   589
clasohm@0
   590
(*Print a tracing message + list of dpairs.
clasohm@0
   591
  In t==u print u first because it may be rigid or flexible --
clasohm@0
   592
    t is always flexible.*)
wenzelm@37635
   593
fun print_dpairs thy msg (env, dpairs) =
wenzelm@37635
   594
  let
wenzelm@37635
   595
    fun pdp (rbinder, t, u) =
wenzelm@37635
   596
      let
wenzelm@37635
   597
        fun termT t =
wenzelm@37635
   598
          Syntax.pretty_term_global thy (Envir.norm_term env (Logic.rlist_abs (rbinder, t)));
wenzelm@37635
   599
        val bsymbs = [termT u, Pretty.str" =?=", Pretty.brk 1, termT t];
wenzelm@37635
   600
      in tracing (Pretty.string_of (Pretty.blk (0, bsymbs))) end;
wenzelm@37635
   601
  in tracing msg; List.app pdp dpairs end;
clasohm@0
   602
clasohm@0
   603
clasohm@0
   604
(*Unify the dpairs in the environment.
wenzelm@19864
   605
  Returns flex-flex disagreement pairs NOT IN normal form.
clasohm@0
   606
  SIMPL may raise exception CANTUNIFY. *)
wenzelm@37635
   607
fun hounifiers (thy, env, tus : (term * term) list) : (Envir.env * (term * term) list) Seq.seq =
wenzelm@24178
   608
  let
wenzelm@36787
   609
    val trace_bnd = Config.get_global thy trace_bound;
wenzelm@36787
   610
    val search_bnd = Config.get_global thy search_bound;
wenzelm@36787
   611
    val trace_smp = Config.get_global thy trace_simp;
wenzelm@37635
   612
    fun add_unify tdepth ((env, dpairs), reseq) =
wenzelm@37635
   613
      Seq.make (fn () =>
wenzelm@37635
   614
        let
wenzelm@37635
   615
          val (env', flexflex, flexrigid) =
wenzelm@37635
   616
           (if tdepth > trace_bnd andalso trace_smp
wenzelm@37635
   617
            then print_dpairs thy "Enter SIMPL" (env, dpairs) else ();
wenzelm@37635
   618
            SIMPL thy (env, dpairs));
wenzelm@37635
   619
        in
wenzelm@37635
   620
          (case flexrigid of
wenzelm@37635
   621
            [] => SOME (List.foldr (add_ffpair thy) (env', []) flexflex, reseq)
wenzelm@37635
   622
          | dp :: frigid' =>
wenzelm@37635
   623
              if tdepth > search_bnd then
wenzelm@37635
   624
                (warning "Unification bound exceeded"; Seq.pull reseq)
wenzelm@37635
   625
              else
wenzelm@37635
   626
               (if tdepth > trace_bnd then
wenzelm@37635
   627
                  print_dpairs thy "Enter MATCH" (env',flexrigid@flexflex)
wenzelm@37635
   628
                else ();
wenzelm@37635
   629
                Seq.pull (Seq.it_right
wenzelm@37635
   630
                    (add_unify (tdepth + 1)) (MATCH thy (env',dp, frigid'@flexflex), reseq))))
wenzelm@37635
   631
        end
wenzelm@37635
   632
        handle CANTUNIFY =>
wenzelm@37635
   633
         (if tdepth > trace_bnd then tracing"Failure node" else ();
wenzelm@37635
   634
          Seq.pull reseq));
wenzelm@37635
   635
    val dps = map (fn (t, u) => ([], t, u)) tus;
wenzelm@16425
   636
  in add_unify 1 ((env, dps), Seq.empty) end;
clasohm@0
   637
wenzelm@18184
   638
fun unifiers (params as (thy, env, tus)) =
wenzelm@19473
   639
  Seq.cons (fold (Pattern.unify thy) tus env, []) Seq.empty
wenzelm@16425
   640
    handle Pattern.Unif => Seq.empty
wenzelm@37635
   641
      | Pattern.Pattern => hounifiers params;
clasohm@0
   642
clasohm@0
   643
clasohm@0
   644
(*For smash_flexflex1*)
clasohm@0
   645
fun var_head_of (env,t) : indexname * typ =
wenzelm@37635
   646
  (case head_of (strip_abs_body (Envir.norm_term env t)) of
wenzelm@37635
   647
    Var (v, T) => (v, T)
wenzelm@37635
   648
  | _ => raise CANTUNIFY);  (*not flexible, cannot use trivial substitution*)
clasohm@0
   649
clasohm@0
   650
clasohm@0
   651
(*Eliminate a flex-flex pair by the trivial substitution, see Huet (1975)
clasohm@0
   652
  Unifies ?f(t1...rm) with ?g(u1...un) by ?f -> %x1...xm.?a, ?g -> %x1...xn.?a
wenzelm@19864
   653
  Unfortunately, unifies ?f(t,u) with ?g(t,u) by ?f, ?g -> %(x,y)?a,
wenzelm@19864
   654
  though just ?g->?f is a more general unifier.
clasohm@0
   655
  Unlike Huet (1975), does not smash together all variables of same type --
clasohm@0
   656
    requires more work yet gives a less general unifier (fewer variables).
clasohm@0
   657
  Handles ?f(t1...rm) with ?f(u1...um) to avoid multiple updates. *)
wenzelm@37636
   658
fun smash_flexflex1 ((t, u), env) : Envir.env =
wenzelm@37635
   659
  let
wenzelm@37635
   660
    val vT as (v, T) = var_head_of (env, t)
wenzelm@37635
   661
    and wU as (w, U) = var_head_of (env, u);
wenzelm@37635
   662
    val (env', var) = Envir.genvar (#1 v) (env, body_type env T);
wenzelm@37635
   663
    val env'' = Envir.vupdate ((wU, type_abs (env', U, var)), env');
wenzelm@37635
   664
  in
wenzelm@37635
   665
    if vT = wU then env''  (*the other update would be identical*)
wenzelm@37635
   666
    else Envir.vupdate ((vT, type_abs (env', T, var)), env'')
clasohm@0
   667
  end;
clasohm@0
   668
clasohm@0
   669
clasohm@0
   670
(*Smash all flex-flexpairs.  Should allow selection of pairs by a predicate?*)
wenzelm@37636
   671
fun smash_flexflex (env, tpairs) : Envir.env =
wenzelm@23178
   672
  List.foldr smash_flexflex1 env tpairs;
clasohm@0
   673
clasohm@0
   674
(*Returns unifiers with no remaining disagreement pairs*)
wenzelm@19864
   675
fun smash_unifiers thy tus env =
wenzelm@37635
   676
  Seq.map smash_flexflex (unifiers (thy, env, tus));
clasohm@0
   677
wenzelm@19864
   678
wenzelm@19864
   679
(*Pattern matching*)
wenzelm@32032
   680
fun first_order_matchers thy pairs (Envir.Envir {maxidx, tenv, tyenv}) =
wenzelm@20020
   681
  let val (tyenv', tenv') = fold (Pattern.first_order_match thy) pairs (tyenv, tenv)
wenzelm@32032
   682
  in Seq.single (Envir.Envir {maxidx = maxidx, tenv = tenv', tyenv = tyenv'}) end
wenzelm@19864
   683
  handle Pattern.MATCH => Seq.empty;
wenzelm@19864
   684
wenzelm@19864
   685
(*General matching -- keeps variables disjoint*)
wenzelm@19864
   686
fun matchers _ [] = Seq.single (Envir.empty ~1)
wenzelm@19864
   687
  | matchers thy pairs =
wenzelm@19864
   688
      let
wenzelm@19864
   689
        val maxidx = fold (Term.maxidx_term o #2) pairs ~1;
wenzelm@19864
   690
        val offset = maxidx + 1;
wenzelm@19864
   691
        val pairs' = map (apfst (Logic.incr_indexes ([], offset))) pairs;
wenzelm@19864
   692
        val maxidx' = fold (fn (t, u) => Term.maxidx_term t #> Term.maxidx_term u) pairs' ~1;
wenzelm@19864
   693
wenzelm@19864
   694
        val pat_tvars = fold (Term.add_tvars o #1) pairs' [];
wenzelm@19864
   695
        val pat_vars = fold (Term.add_vars o #1) pairs' [];
wenzelm@19864
   696
wenzelm@19864
   697
        val decr_indexesT =
wenzelm@19864
   698
          Term.map_atyps (fn T as TVar ((x, i), S) =>
wenzelm@19864
   699
            if i > maxidx then TVar ((x, i - offset), S) else T | T => T);
wenzelm@19864
   700
        val decr_indexes =
wenzelm@20548
   701
          Term.map_types decr_indexesT #>
wenzelm@19864
   702
          Term.map_aterms (fn t as Var ((x, i), T) =>
wenzelm@19864
   703
            if i > maxidx then Var ((x, i - offset), T) else t | t => t);
wenzelm@19864
   704
wenzelm@32032
   705
        fun norm_tvar env ((x, i), S) =
wenzelm@32032
   706
          ((x, i - offset),
wenzelm@32032
   707
            (S, decr_indexesT (Envir.norm_type (Envir.type_env env) (TVar ((x, i), S)))));
wenzelm@32032
   708
        fun norm_var env ((x, i), T) =
wenzelm@19864
   709
          let
wenzelm@32032
   710
            val tyenv = Envir.type_env env;
wenzelm@19864
   711
            val T' = Envir.norm_type tyenv T;
wenzelm@19864
   712
            val t' = Envir.norm_term env (Var ((x, i), T'));
wenzelm@19864
   713
          in ((x, i - offset), (decr_indexesT T', decr_indexes t')) end;
wenzelm@19864
   714
wenzelm@19864
   715
        fun result env =
wenzelm@19876
   716
          if Envir.above env maxidx then   (* FIXME proper handling of generated vars!? *)
wenzelm@19864
   717
            SOME (Envir.Envir {maxidx = maxidx,
wenzelm@32032
   718
              tyenv = Vartab.make (map (norm_tvar env) pat_tvars),
wenzelm@32032
   719
              tenv = Vartab.make (map (norm_var env) pat_vars)})
wenzelm@19866
   720
          else NONE;
wenzelm@19864
   721
wenzelm@19864
   722
        val empty = Envir.empty maxidx';
wenzelm@19864
   723
      in
wenzelm@19876
   724
        Seq.append
wenzelm@19920
   725
          (Seq.map_filter result (smash_unifiers thy pairs' empty))
wenzelm@20020
   726
          (first_order_matchers thy pairs empty)
wenzelm@19864
   727
      end;
wenzelm@19864
   728
wenzelm@19864
   729
fun matches_list thy ps os =
wenzelm@19864
   730
  length ps = length os andalso is_some (Seq.pull (matchers thy (ps ~~ os)));
wenzelm@19864
   731
clasohm@0
   732
end;