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