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