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