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