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