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