src/Pure/defs.ML
author obua
Tue Jun 07 06:39:39 2005 +0200 (2005-06-07)
changeset 16308 636a1a84977a
parent 16198 cfd070a2cc4d
child 16361 cb31cb768a6c
permissions -rw-r--r--
1) Fixed bug in Defs.merge_edges_1.
2) Major optimization of Defs.define: do not store dependencies between constants that
cannot introduce cycles anyway. In that way, the cycle test adds almost no overhead to
theories that define their constants in HOL-light / HOL4 style.
3) Cleaned up Defs.graph, no superfluous name tags are stored anymore.
obua@16108
     1
(*  Title:      Pure/General/defs.ML
obua@16108
     2
    ID:         $Id$
obua@16108
     3
    Author:     Steven Obua, TU Muenchen
obua@16108
     4
obua@16308
     5
    Checks if definitions preserve consistency of logic by enforcing 
obua@16308
     6
    that there are no cyclic definitions. The algorithm is described in 
obua@16308
     7
    "An Algorithm for Determining Definitional Cycles in Higher-Order Logic with Overloading", 
obua@16308
     8
    Steven Obua, technical report, to be written :-)
obua@16108
     9
*)
obua@16108
    10
obua@16108
    11
signature DEFS = sig
obua@16108
    12
    
obua@16198
    13
  type graph
obua@16198
    14
       
obua@16198
    15
  exception DEFS of string
obua@16198
    16
  exception CIRCULAR of (typ * string * string) list
obua@16198
    17
  exception INFINITE_CHAIN of (typ * string * string) list 
obua@16198
    18
  exception FINAL of string * typ
obua@16198
    19
  exception CLASH of string * string * string
obua@16198
    20
                     
obua@16198
    21
  val empty : graph
obua@16198
    22
  val declare : graph -> string * typ -> graph  (* exception DEFS *)
obua@16198
    23
  val define : graph -> string * typ -> string -> (string * typ) list -> graph 
obua@16308
    24
    (* exception DEFS, CIRCULAR, INFINITE_CHAIN, CLASH, FINAL *)   
obua@16308
    25
                                                                     
obua@16198
    26
  val finalize : graph -> string * typ -> graph (* exception DEFS *)
obua@16108
    27
obua@16198
    28
  val finals : graph -> (typ list) Symtab.table
obua@16158
    29
obua@16198
    30
  val merge : graph -> graph -> graph (* exception CIRCULAR, INFINITE_CHAIN, CLASH *)
obua@16108
    31
obua@16308
    32
  (* If set to true then the exceptions CIRCULAR and INFINITE_CHAIN return the full
obua@16308
    33
     chain of definitions that lead to the exception. In the beginning, chain_history 
obua@16308
    34
     is initialized with the Isabelle environment variable DEFS_CHAIN_HISTORY. *)
obua@16308
    35
  val set_chain_history : bool -> unit
obua@16308
    36
  val chain_history : unit -> bool
obua@16308
    37
obua@16108
    38
end
obua@16108
    39
obua@16108
    40
structure Defs :> DEFS = struct
obua@16108
    41
obua@16108
    42
type tyenv = Type.tyenv
obua@16108
    43
type edgelabel = (int * typ * typ * (typ * string * string) list)
obua@16108
    44
obua@16108
    45
datatype node = Node of
obua@16308
    46
         typ  (* most general type of constant *)
obua@16308
    47
         * defnode Symtab.table  
obua@16308
    48
             (* a table of defnodes, each corresponding to 1 definition of the 
obua@16308
    49
                constant for a particular type, indexed by axiom name *)
obua@16308
    50
         * (unit Symtab.table) Symtab.table 
obua@16308
    51
             (* a table of all back referencing defnodes to this node, 
obua@16308
    52
                indexed by node name of the defnodes *)
obua@16198
    53
         * typ list (* a list of all finalized types *)
obua@16108
    54
     
obua@16198
    55
     and defnode = Defnode of
obua@16198
    56
         typ  (* type of the constant in this particular definition *)
obua@16308
    57
         * (edgelabel list) Symtab.table (* The edges, grouped by nodes. *)
obua@16108
    58
obua@16108
    59
fun getnode graph noderef = the (Symtab.lookup (graph, noderef))
obua@16308
    60
fun get_nodedefs (Node (_, defs, _, _)) = defs
obua@16308
    61
fun get_defnode (Node (_, defs, _, _)) defname = Symtab.lookup (defs, defname)
obua@16308
    62
fun get_defnode' graph noderef defname = 
obua@16308
    63
    Symtab.lookup (get_nodedefs (the (Symtab.lookup (graph, noderef))), defname)
obua@16108
    64
obua@16308
    65
datatype graphaction = Declare of string * typ
obua@16158
    66
		     | Define of string * typ * string * (string * typ) list
obua@16158
    67
		     | Finalize of string * typ
obua@16108
    68
obua@16308
    69
type graph = int * (graphaction list) * (node Symtab.table)
obua@16198
    70
             
obua@16308
    71
val CHAIN_HISTORY = 
obua@16308
    72
    let
obua@16308
    73
      fun f c = if Char.isSpace c then "" else String.str (Char.toUpper c) 
obua@16308
    74
      val env = String.translate f (getenv "DEFS_CHAIN_HISTORY")
obua@16308
    75
    in
obua@16308
    76
      ref (env = "ON" orelse env = "TRUE")
obua@16308
    77
    end
obua@16308
    78
obua@16308
    79
fun set_chain_history b = CHAIN_HISTORY := b
obua@16308
    80
fun chain_history () = !CHAIN_HISTORY
obua@16308
    81
obua@16308
    82
val empty = (0, [], Symtab.empty)
obua@16108
    83
obua@16108
    84
exception DEFS of string;
obua@16108
    85
exception CIRCULAR of (typ * string * string) list;
obua@16113
    86
exception INFINITE_CHAIN of (typ * string * string) list;
obua@16108
    87
exception CLASH of string * string * string;
obua@16158
    88
exception FINAL of string * typ;
obua@16108
    89
obua@16108
    90
fun def_err s = raise (DEFS s)
obua@16108
    91
obua@16308
    92
fun checkT (Type (a, Ts)) = Type (a, map checkT Ts)
obua@16308
    93
  | checkT (TVar ((a, 0), _)) = TVar ((a, 0), [])
obua@16308
    94
  | checkT (TVar ((a, i), _)) = def_err "type is not clean"
obua@16308
    95
  | checkT (TFree (a, _)) = TVar ((a, 0), [])
obua@16308
    96
obua@16308
    97
fun declare' (cost, actions, g) (cty as (name, ty)) =
obua@16308
    98
    (cost, (Declare cty)::actions, 
obua@16308
    99
     Symtab.update_new ((name, Node (ty, Symtab.empty, Symtab.empty, [])), g))
obua@16158
   100
    handle Symtab.DUP _ => def_err "constant is already declared"
obua@16108
   101
obua@16308
   102
fun declare g (name, ty) = declare' g (name, checkT ty)
obua@16308
   103
obua@16108
   104
fun rename ty1 ty2 = incr_tvar ((maxidx_of_typ ty1)+1) ty2;  
obua@16108
   105
obua@16108
   106
fun subst_incr_tvar inc t =
obua@16108
   107
    if (inc > 0) then 
obua@16198
   108
      let
obua@16198
   109
	val tv = typ_tvars t
obua@16198
   110
	val t' = incr_tvar inc t
obua@16198
   111
	fun update_subst (((n,i), _), s) =
obua@16198
   112
	    Vartab.update (((n, i), ([], TVar ((n, i+inc), []))), s)
obua@16198
   113
      in
obua@16198
   114
	(t',List.foldl update_subst Vartab.empty tv)
obua@16198
   115
      end	
obua@16108
   116
    else
obua@16198
   117
      (t, Vartab.empty)
obua@16198
   118
    
obua@16108
   119
fun subst s ty = Envir.norm_type s ty
obua@16198
   120
                 
obua@16108
   121
fun subst_history s history = map (fn (ty, cn, dn) => (subst s ty, cn, dn)) history
obua@16198
   122
                              
obua@16108
   123
fun is_instance instance_ty general_ty =
obua@16108
   124
    Type.typ_instance Type.empty_tsig (instance_ty, general_ty)
obua@16198
   125
    
obua@16108
   126
fun is_instance_r instance_ty general_ty =
obua@16108
   127
    is_instance instance_ty (rename instance_ty general_ty)
obua@16198
   128
    
obua@16108
   129
fun unify ty1 ty2 = 
obua@16108
   130
    SOME (fst (Type.unify Type.empty_tsig (Vartab.empty, 0) (ty1, ty2)))
obua@16108
   131
    handle Type.TUNIFY => NONE
obua@16198
   132
                            
obua@16108
   133
(* 
obua@16308
   134
   Unifies ty1 and ty2, renaming ty1 and ty2 so that they have greater indices than max and 
obua@16308
   135
   so that they are different. All indices in ty1 and ty2 are supposed to be less than or 
obua@16308
   136
   equal to max.
obua@16308
   137
   Returns SOME (max', s1, s2), so that s1(ty1) = s2(ty2) and max' is greater or equal than 
obua@16308
   138
   all indices in s1, s2, ty1, ty2.
obua@16108
   139
*)
obua@16108
   140
fun unify_r max ty1 ty2 = 
obua@16108
   141
    let
obua@16308
   142
      val max = Int.max(max, 0)
obua@16198
   143
      val max1 = max (* >= maxidx_of_typ ty1 *)
obua@16198
   144
      val max2 = max (* >= maxidx_of_typ ty2 *)
obua@16198
   145
      val max = Int.max(max, Int.max (max1, max2))
obua@16308
   146
      val (ty1, s1) = subst_incr_tvar (max + 1) ty1
obua@16308
   147
      val (ty2, s2) = subst_incr_tvar (max + max1 + 2) ty2
obua@16308
   148
      val max = max + max1 + max2 + 2	
obua@16198
   149
      fun merge a b = Vartab.merge (fn _ => false) (a, b)
obua@16108
   150
    in
obua@16198
   151
      case unify ty1 ty2 of
obua@16198
   152
	NONE => NONE
obua@16198
   153
      | SOME s => SOME (max, merge s1 s, merge s2 s)
obua@16108
   154
    end
obua@16198
   155
    
obua@16108
   156
fun can_be_unified_r ty1 ty2 =
obua@16108
   157
    let
obua@16198
   158
      val ty2 = rename ty1 ty2
obua@16108
   159
    in
obua@16198
   160
      case unify ty1 ty2 of
obua@16198
   161
	NONE => false
obua@16198
   162
      | _ => true
obua@16108
   163
    end
obua@16198
   164
    
obua@16108
   165
fun can_be_unified ty1 ty2 =
obua@16108
   166
    case unify ty1 ty2 of
obua@16198
   167
      NONE => false
obua@16198
   168
    | _ => true
obua@16198
   169
           
obua@16308
   170
structure Inttab = TableFun(type key = int val ord = int_ord);
obua@16108
   171
obua@16308
   172
fun normalize_edge_idx (edge as (maxidx, u1, v1, history)) =
obua@16308
   173
    if maxidx <= 1000000 then edge else
obua@16308
   174
    let
obua@16308
   175
      
obua@16308
   176
      fun idxlist idx extract_ty inject_ty (tab, max) ts = 
obua@16308
   177
          foldr 
obua@16308
   178
            (fn (e, ((tab, max), ts)) => 
obua@16308
   179
                let
obua@16308
   180
                  val ((tab, max), ty) = idx (tab, max) (extract_ty e)
obua@16308
   181
                  val e = inject_ty (ty, e)
obua@16308
   182
                in
obua@16308
   183
                  ((tab, max), e::ts)
obua@16308
   184
                end)
obua@16308
   185
            ((tab,max), []) ts
obua@16308
   186
          
obua@16308
   187
      fun idx (tab,max) (TVar ((a,i),_)) = 
obua@16308
   188
          (case Inttab.lookup (tab, i) of 
obua@16308
   189
             SOME j => ((tab, max), TVar ((a,j),[]))
obua@16308
   190
           | NONE => ((Inttab.update ((i, max), tab), max+1), TVar ((a,max),[])))
obua@16308
   191
        | idx (tab,max) (Type (t, ts)) = 
obua@16308
   192
          let 
obua@16308
   193
            val ((tab, max), ts) = idxlist idx I fst (tab, max) ts
obua@16308
   194
          in
obua@16308
   195
            ((tab,max), Type (t, ts))
obua@16308
   196
          end
obua@16308
   197
        | idx (tab, max) ty = ((tab, max), ty)
obua@16308
   198
      
obua@16308
   199
      val ((tab,max), u1) = idx (Inttab.empty, 0) u1
obua@16308
   200
      val ((tab,max), v1) = idx (tab, max) v1
obua@16308
   201
      val ((tab,max), history) = 
obua@16308
   202
          idxlist idx
obua@16308
   203
            (fn (ty,_,_) => ty) 
obua@16308
   204
            (fn (ty, (_, s1, s2)) => (ty, s1, s2)) 
obua@16308
   205
            (tab, max) history
obua@16308
   206
    in
obua@16308
   207
      (max, u1, v1, history)
obua@16308
   208
    end
obua@16308
   209
                        
obua@16108
   210
fun compare_edges (e1 as (maxidx1, u1, v1, history1)) (e2 as (maxidx2, u2, v2, history2)) =
obua@16108
   211
    let
obua@16198
   212
      val t1 = u1 --> v1
obua@16308
   213
      val t2 = incr_tvar (maxidx1+1) (u2 --> v2)
obua@16108
   214
    in
obua@16308
   215
      if (is_instance t1 t2) then
obua@16308
   216
	(if is_instance t2 t1 then
obua@16198
   217
	   SOME (int_ord (length history2, length history1))
obua@16198
   218
	 else
obua@16198
   219
	   SOME LESS)
obua@16308
   220
      else if (is_instance t2 t1) then
obua@16198
   221
	SOME GREATER
obua@16198
   222
      else
obua@16198
   223
	NONE
obua@16108
   224
    end
obua@16308
   225
obua@16308
   226
fun merge_edges_1 (x, []) = [x]
obua@16108
   227
  | merge_edges_1 (x, (y::ys)) = 
obua@16108
   228
    (case compare_edges x y of
obua@16198
   229
       SOME LESS => (y::ys)
obua@16198
   230
     | SOME EQUAL => (y::ys)
obua@16198
   231
     | SOME GREATER => merge_edges_1 (x, ys)
obua@16198
   232
     | NONE => y::(merge_edges_1 (x, ys)))
obua@16198
   233
    
obua@16108
   234
fun merge_edges xs ys = foldl merge_edges_1 xs ys
obua@16108
   235
obua@16308
   236
fun define' (cost, actions, graph) (mainref, ty) axname body =
obua@16108
   237
    let
obua@16198
   238
      val mainnode  = (case Symtab.lookup (graph, mainref) of 
obua@16198
   239
			 NONE => def_err ("constant "^mainref^" is not declared")
obua@16198
   240
		       | SOME n => n)
obua@16308
   241
      val (Node (gty, defs, backs, finals)) = mainnode
obua@16308
   242
      val _ = (if is_instance_r ty gty then () 
obua@16308
   243
               else def_err "type of constant does not match declared type")
obua@16198
   244
      fun check_def (s, Defnode (ty', _)) = 
obua@16308
   245
          (if can_be_unified_r ty ty' then 
obua@16198
   246
	     raise (CLASH (mainref, axname, s))
obua@16198
   247
	   else if s = axname then
obua@16198
   248
	     def_err "name of axiom is already used for another definition of this constant"
obua@16198
   249
	   else false)	
obua@16198
   250
      val _ = Symtab.exists check_def defs
obua@16198
   251
      fun check_final finalty = 
obua@16198
   252
	  (if can_be_unified_r finalty ty then
obua@16198
   253
	     raise (FINAL (mainref, finalty))
obua@16198
   254
	   else
obua@16198
   255
	     true)
obua@16198
   256
      val _ = forall check_final finals
obua@16198
   257
	             
obua@16308
   258
      (* now we know that the only thing that can prevent acceptance of the definition 
obua@16308
   259
         is a cyclic dependency *)
obua@16108
   260
obua@16308
   261
      fun insert_edges edges (nodename, links) =
obua@16308
   262
          (if links = [] then 
obua@16308
   263
             edges
obua@16308
   264
           else
obua@16308
   265
             let
obua@16308
   266
               val links = map normalize_edge_idx links
obua@16308
   267
             in
obua@16308
   268
               Symtab.update ((nodename, 
obua@16308
   269
	                       case Symtab.lookup (edges, nodename) of
obua@16308
   270
	                         NONE => links
obua@16308
   271
	                       | SOME links' => merge_edges links' links),
obua@16308
   272
                              edges)
obua@16308
   273
             end)
obua@16308
   274
	 
obua@16308
   275
      fun make_edges ((bodyn, bodyty), edges) =
obua@16198
   276
	  let
obua@16198
   277
	    val bnode = 
obua@16198
   278
		(case Symtab.lookup (graph, bodyn) of 
obua@16198
   279
		   NONE => def_err "body of constant definition references undeclared constant"
obua@16198
   280
		 | SOME x => x)
obua@16308
   281
	    val (Node (general_btyp, bdefs, bbacks, bfinals)) = bnode
obua@16198
   282
	  in
obua@16198
   283
	    case unify_r 0 bodyty general_btyp of
obua@16308
   284
	      NONE => edges
obua@16198
   285
	    | SOME (maxidx, sigma1, sigma2) => 
obua@16308
   286
              if exists (is_instance_r bodyty) bfinals then 
obua@16308
   287
                edges
obua@16308
   288
              else
obua@16308
   289
	        let
obua@16308
   290
		  fun insert_trans_edges ((step1, edges), (nodename, links)) =
obua@16308
   291
                      let
obua@16308
   292
                        val (maxidx1, alpha1, beta1, defname) = step1
obua@16308
   293
                        fun connect (maxidx2, alpha2, beta2, history) = 
obua@16308
   294
		            case unify_r (Int.max (maxidx1, maxidx2)) beta1 alpha2 of
obua@16308
   295
		              NONE => NONE
obua@16308
   296
		            | SOME (max, sleft, sright) =>				  
obua@16308
   297
			      SOME (max, subst sleft alpha1, subst sright beta2, 
obua@16308
   298
                                    if !CHAIN_HISTORY then   
obua@16308
   299
			              ((subst sleft beta1, bodyn, defname)::
obua@16308
   300
				       (subst_history sright history))
obua@16308
   301
                                    else [])            
obua@16308
   302
                        val links' = List.mapPartial connect links
obua@16308
   303
                      in
obua@16308
   304
                        (step1, insert_edges edges (nodename, links'))
obua@16308
   305
                      end
obua@16308
   306
                                                                
obua@16308
   307
                  fun make_edges' ((swallowed, edges),
obua@16308
   308
                                   (def_name, Defnode (def_ty, def_edges))) =
obua@16308
   309
		      if swallowed then
obua@16308
   310
		        (swallowed, edges)
obua@16308
   311
		      else 
obua@16308
   312
		        (case unify_r 0 bodyty def_ty of
obua@16308
   313
			   NONE => (swallowed, edges)
obua@16308
   314
		         | SOME (maxidx, sigma1, sigma2) => 
obua@16308
   315
			   (is_instance_r bodyty def_ty,
obua@16308
   316
                            snd (Symtab.foldl insert_trans_edges 
obua@16308
   317
                              (((maxidx, subst sigma1 ty, subst sigma2 def_ty, def_name),
obua@16308
   318
                                edges), def_edges))))
obua@16308
   319
          	  val (swallowed, edges) = Symtab.foldl make_edges' ((false, edges), bdefs)
obua@16308
   320
	        in
obua@16308
   321
		  if swallowed then 
obua@16308
   322
		    edges
obua@16308
   323
		  else 
obua@16308
   324
                    insert_edges edges 
obua@16308
   325
                    (bodyn, [(maxidx, subst sigma1 ty, subst sigma2 general_btyp,[])])
obua@16308
   326
	        end
obua@16198
   327
	  end 
obua@16308
   328
                    
obua@16308
   329
      val edges = foldl make_edges Symtab.empty body
obua@16308
   330
                  				               
obua@16308
   331
      (* We also have to add the backreferences that this new defnode induces. *)  
obua@16308
   332
      fun install_backrefs (graph, (noderef, links)) =
obua@16308
   333
          if links <> [] then
obua@16308
   334
            let
obua@16308
   335
              val (Node (ty, defs, backs, finals)) = getnode graph noderef
obua@16308
   336
              val defnames =
obua@16308
   337
                  (case Symtab.lookup (backs, mainref) of
obua@16308
   338
                     NONE => Symtab.empty
obua@16308
   339
                   | SOME s => s)
obua@16308
   340
              val defnames' = Symtab.update_new ((axname, ()), defnames)
obua@16308
   341
              val backs' = Symtab.update ((mainref,defnames'), backs)
obua@16308
   342
            in
obua@16308
   343
              Symtab.update ((noderef, Node (ty, defs, backs', finals)), graph)
obua@16308
   344
            end
obua@16308
   345
          else
obua@16308
   346
            graph
obua@16198
   347
            
obua@16198
   348
      val graph = Symtab.foldl install_backrefs (graph, edges)
obua@16198
   349
                  
obua@16308
   350
      val (Node (_, _, backs, _)) = getnode graph mainref
obua@16308
   351
      val thisDefnode = Defnode (ty, edges)
obua@16308
   352
      val graph = Symtab.update ((mainref, Node (gty, Symtab.update_new 
obua@16198
   353
        ((axname, thisDefnode), defs), backs, finals)), graph)
obua@16198
   354
		                
obua@16308
   355
      (* Now we have to check all backreferences to this node and inform them about 
obua@16308
   356
         the new defnode. In this section we also check for circularity. *)
obua@16308
   357
      fun update_backrefs ((backs, graph), (noderef, defnames)) =
obua@16198
   358
	  let
obua@16308
   359
	    fun update_defs ((defnames, graph),(defname, _)) =
obua@16198
   360
		let
obua@16308
   361
                  val (Node (nodety, nodedefs, nodebacks, nodefinals)) = getnode graph noderef
obua@16308
   362
		  val (Defnode (def_ty, defnode_edges)) = 
obua@16308
   363
                      the (Symtab.lookup (nodedefs, defname))
obua@16308
   364
		  val edges = the (Symtab.lookup (defnode_edges, mainref))
obua@16308
   365
 					
obua@16198
   366
	          (* the type of thisDefnode is ty *)
obua@16308
   367
		  fun update (e as (max, alpha, beta, history), (changed, edges)) = 
obua@16198
   368
		      case unify_r max beta ty of
obua@16308
   369
			NONE => (changed, e::edges)
obua@16198
   370
		      | SOME (max', s_beta, s_ty) =>
obua@16198
   371
			let
obua@16198
   372
			  val alpha' = subst s_beta alpha
obua@16198
   373
			  val ty' = subst s_ty ty				      
obua@16198
   374
			  val _ = 
obua@16198
   375
			      if noderef = mainref andalso defname = axname then
obua@16198
   376
				(case unify alpha' ty' of
obua@16198
   377
				   NONE => 
obua@16198
   378
				   if (is_instance_r ty' alpha') then
obua@16198
   379
				     raise (INFINITE_CHAIN (
obua@16198
   380
					    (alpha', mainref, axname)::
obua@16198
   381
					    (subst_history s_beta history)@
obua@16198
   382
					    [(ty', mainref, axname)]))
obua@16198
   383
				   else ()
obua@16308
   384
				 | SOME s => 
obua@16308
   385
                                   raise (CIRCULAR (
obua@16308
   386
					  (subst s alpha', mainref, axname)::
obua@16308
   387
					  (subst_history s (subst_history s_beta history))@
obua@16308
   388
					  [(subst s ty', mainref, axname)])))
obua@16308
   389
			      else ()                             
obua@16198
   390
			in
obua@16308
   391
			  if is_instance_r beta ty then
obua@16308
   392
			    (true, edges)
obua@16198
   393
			  else
obua@16308
   394
			    (changed, e::edges)
obua@16308
   395
			end		    			   			       
obua@16308
   396
                  
obua@16308
   397
                  val (changed, edges') = foldl update (false, []) edges
obua@16308
   398
                  val defnames' = if edges' = [] then 
obua@16308
   399
                                    defnames 
obua@16308
   400
                                  else 
obua@16308
   401
                                    Symtab.update ((defname, ()), defnames)
obua@16308
   402
                in
obua@16308
   403
                  if changed then
obua@16308
   404
                    let
obua@16308
   405
                      val defnode_edges' = 
obua@16308
   406
                          if edges' = [] then
obua@16308
   407
                            Symtab.delete mainref defnode_edges
obua@16308
   408
                          else
obua@16308
   409
                            Symtab.update ((mainref, edges'), defnode_edges)
obua@16308
   410
                      val defnode' = Defnode (def_ty, defnode_edges')
obua@16308
   411
                      val nodedefs' = Symtab.update ((defname, defnode'), nodedefs)
obua@16308
   412
                      val graph' = 
obua@16308
   413
                          Symtab.update 
obua@16308
   414
                            ((noderef, Node (nodety, nodedefs', nodebacks, nodefinals)),graph) 
obua@16308
   415
                    in
obua@16308
   416
                      (defnames', graph')
obua@16308
   417
                    end
obua@16308
   418
                  else
obua@16308
   419
                    (defnames', graph)
obua@16308
   420
                end
obua@16108
   421
		    
obua@16308
   422
	    val (defnames', graph') = Symtab.foldl update_defs 
obua@16308
   423
                                                   ((Symtab.empty, graph), defnames)
obua@16198
   424
	  in
obua@16308
   425
	    if Symtab.is_empty defnames' then 
obua@16308
   426
	      (backs, graph')
obua@16198
   427
	    else
obua@16198
   428
	      let
obua@16308
   429
		val backs' = Symtab.update_new ((noderef, defnames'), backs)
obua@16198
   430
	      in
obua@16308
   431
		(backs', graph')
obua@16198
   432
	      end
obua@16198
   433
	  end
obua@16308
   434
        
obua@16308
   435
      val (backs, graph) = Symtab.foldl update_backrefs ((Symtab.empty, graph), backs)
obua@16308
   436
                                        						 
obua@16198
   437
      (* If a Circular exception is thrown then we never reach this point. *)
obua@16308
   438
      val (Node (gty, defs, _, finals)) = getnode graph mainref
obua@16308
   439
      val graph = Symtab.update ((mainref, Node (gty, defs, backs, finals)), graph) 
obua@16108
   440
    in	    
obua@16308
   441
      (cost+3,(Define (mainref, ty, axname, body))::actions, graph)
obua@16108
   442
    end 
obua@16198
   443
    
obua@16308
   444
fun define g (mainref, ty) axname body =
obua@16308
   445
    let
obua@16308
   446
      val ty = checkT ty
obua@16308
   447
      val body = distinct (map (fn (n,t) => (n, checkT t)) body)
obua@16308
   448
    in
obua@16308
   449
      define' g (mainref, ty) axname body
obua@16308
   450
    end
obua@16308
   451
obua@16308
   452
fun finalize' (cost, history, graph) (noderef, ty) = 
obua@16308
   453
    case Symtab.lookup (graph, noderef) of 
obua@16308
   454
      NONE => def_err ("cannot finalize constant "^noderef^"; it is not declared")
obua@16308
   455
    | SOME (Node (nodety, defs, backs, finals)) =>
obua@16198
   456
      let 
obua@16308
   457
	val _ = 
obua@16308
   458
            if (not (is_instance_r ty nodety)) then
obua@16308
   459
	      def_err ("only type instances of the declared constant "^
obua@16308
   460
                       noderef^" can be finalized")
obua@16308
   461
	    else ()
obua@16308
   462
	val _ = Symtab.exists 
obua@16308
   463
                  (fn (def_name, Defnode (def_ty, _)) =>  
obua@16308
   464
		      if can_be_unified_r ty def_ty then 
obua@16308
   465
			def_err ("cannot finalize constant "^noderef^
obua@16308
   466
                                 "; clash with definition "^def_name)
obua@16308
   467
		      else 
obua@16308
   468
			false)
obua@16308
   469
		  defs 
obua@16198
   470
        
obua@16198
   471
        fun update_finals [] = SOME [ty]
obua@16198
   472
          | update_finals (final_ty::finals) = 
obua@16198
   473
            (if is_instance_r ty final_ty then NONE
obua@16198
   474
             else
obua@16198
   475
               case update_finals finals of
obua@16198
   476
                 NONE => NONE
obua@16198
   477
               | (r as SOME finals) =>
obua@16198
   478
                 if (is_instance_r final_ty ty) then
obua@16198
   479
                   r
obua@16198
   480
                 else
obua@16198
   481
                   SOME (final_ty :: finals))                              
obua@16198
   482
      in    
obua@16198
   483
        case update_finals finals of
obua@16308
   484
          NONE => (cost, history, graph)
obua@16198
   485
        | SOME finals => 
obua@16198
   486
	  let
obua@16308
   487
	    val graph = Symtab.update ((noderef, Node(nodety, defs, backs, finals)), 
obua@16308
   488
                                       graph)
obua@16198
   489
	                
obua@16308
   490
	    fun update_backref ((graph, backs), (backrefname, backdefnames)) =
obua@16198
   491
		let
obua@16198
   492
		  fun update_backdef ((graph, defnames), (backdefname, _)) = 
obua@16158
   493
	              let 
obua@16308
   494
			val (backnode as Node (backty, backdefs, backbacks, backfinals)) = 
obua@16308
   495
                            getnode graph backrefname
obua@16308
   496
			val (Defnode (def_ty, all_edges)) = 
obua@16308
   497
                            the (get_defnode backnode backdefname)
obua@16308
   498
obua@16198
   499
			val (defnames', all_edges') = 
obua@16198
   500
			    case Symtab.lookup (all_edges, noderef) of
obua@16198
   501
			      NONE => sys_error "finalize: corrupt backref"
obua@16308
   502
			    | SOME edges =>
obua@16198
   503
			      let
obua@16308
   504
				val edges' = List.filter (fn (_, _, beta, _) => 
obua@16308
   505
                                                             not (is_instance_r beta ty)) edges
obua@16198
   506
			      in
obua@16198
   507
				if edges' = [] then 
obua@16308
   508
				  (defnames, Symtab.delete noderef all_edges)
obua@16198
   509
				else
obua@16198
   510
				  (Symtab.update ((backdefname, ()), defnames), 
obua@16308
   511
				   Symtab.update ((noderef, edges'), all_edges))
obua@16198
   512
			      end
obua@16198
   513
			val defnode' = Defnode (def_ty, all_edges')
obua@16308
   514
			val backnode' = 
obua@16308
   515
                            Node (backty, 
obua@16308
   516
                                  Symtab.update ((backdefname, defnode'), backdefs), 
obua@16308
   517
				  backbacks, backfinals)
obua@16158
   518
		      in
obua@16308
   519
			(Symtab.update ((backrefname, backnode'), graph), defnames') 
obua@16158
   520
		      end
obua@16198
   521
	              
obua@16308
   522
		  val (graph', defnames') = 
obua@16308
   523
                      Symtab.foldl update_backdef ((graph, Symtab.empty), backdefnames)
obua@16198
   524
		in
obua@16198
   525
		  (graph', if Symtab.is_empty defnames' then backs 
obua@16308
   526
			   else Symtab.update ((backrefname, defnames'), backs))
obua@16198
   527
		end
obua@16198
   528
	    val (graph', backs') = Symtab.foldl update_backref ((graph, Symtab.empty), backs)
obua@16308
   529
	    val Node ( _, defs, _, _) = getnode graph' noderef
obua@16308
   530
	    val graph' = Symtab.update ((noderef, Node (nodety, defs, backs', finals)), graph')
obua@16198
   531
	  in
obua@16308
   532
	    (cost+1,(Finalize (noderef, ty)) :: history, graph')
obua@16158
   533
	  end
obua@16198
   534
      end
obua@16308
   535
 
obua@16308
   536
fun finalize g (noderef, ty) = finalize' g (noderef, checkT ty)
obua@16308
   537
obua@16308
   538
fun merge' (Declare cty, g) = (declare' g cty handle _ => g)
obua@16308
   539
  | merge' (Define (name, ty, axname, body), g as (_,_, graph)) = 
obua@16198
   540
    (case Symtab.lookup (graph, name) of
obua@16308
   541
       NONE => define' g (name, ty) axname body
obua@16308
   542
     | SOME (Node (_, defs, _, _)) => 
obua@16198
   543
       (case Symtab.lookup (defs, axname) of
obua@16308
   544
	  NONE => define' g (name, ty) axname body
obua@16198
   545
	| SOME _ => g))
obua@16308
   546
  | merge' (Finalize finals, g) = finalize' g finals 
obua@16198
   547
                       
obua@16308
   548
fun merge (g1 as (cost1, actions1, _)) (g2 as (cost2, actions2, _)) =
obua@16308
   549
    if cost1 < cost2 then
obua@16308
   550
      foldr merge' g2 actions1
obua@16308
   551
    else
obua@16308
   552
      foldr merge' g1 actions2
obua@16198
   553
                           
obua@16308
   554
fun finals (cost, history, graph) = 
obua@16198
   555
    Symtab.foldl 
obua@16308
   556
      (fn (finals, (name, Node(_, _, _, ftys))) => Symtab.update_new ((name, ftys), finals))  
obua@16198
   557
      (Symtab.empty, graph)
obua@16158
   558
obua@16108
   559
end;
obua@16108
   560
		
obua@16308
   561
(*
obua@16108
   562
obua@16308
   563
fun tvar name = TVar ((name, 0), [])
obua@16108
   564
obua@16108
   565
val bool = Type ("bool", [])
obua@16108
   566
val int = Type ("int", [])
obua@16308
   567
val lam = Type("lam", [])
obua@16108
   568
val alpha = tvar "'a"
obua@16108
   569
val beta = tvar "'b"
obua@16108
   570
val gamma = tvar "'c"
obua@16108
   571
fun pair a b = Type ("pair", [a,b])
obua@16308
   572
fun prm a = Type ("prm", [a])
obua@16308
   573
val name = Type ("name", [])
obua@16108
   574
obua@16108
   575
val _ = print "make empty"
obua@16108
   576
val g = Defs.empty 
obua@16108
   577
obua@16308
   578
val _ = print "declare perm"
obua@16308
   579
val g = Defs.declare g ("perm", prm alpha --> beta --> beta)
obua@16308
   580
obua@16308
   581
val _ = print "declare permF"
obua@16308
   582
val g = Defs.declare g ("permF", prm alpha --> lam --> lam)
obua@16308
   583
obua@16308
   584
val _ = print "define perm (1)"
obua@16308
   585
val g = Defs.define g ("perm", prm alpha --> (beta --> gamma) --> (beta --> gamma)) "perm_fun" 
obua@16308
   586
        [("perm", prm alpha --> gamma --> gamma), ("perm", prm alpha --> beta --> beta)]
obua@16108
   587
obua@16308
   588
val _ = print "define permF (1)"
obua@16308
   589
val g = Defs.define g ("permF", prm alpha --> lam --> lam) "permF_app"
obua@16308
   590
        ([("perm", prm alpha --> lam --> lam),
obua@16308
   591
         ("perm", prm alpha --> lam --> lam),
obua@16308
   592
         ("perm", prm alpha --> lam --> lam),
obua@16308
   593
         ("perm", prm alpha --> name --> name)])
obua@16108
   594
obua@16308
   595
val _ = print "define perm (2)"
obua@16308
   596
val g = Defs.define g ("perm", prm alpha --> lam --> lam) "perm_lam"
obua@16308
   597
        [("permF", (prm alpha --> lam --> lam))]
obua@16108
   598
obua@16308
   599
*)