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