src/Pure/type.ML
author haftmann
Tue Sep 06 08:30:43 2005 +0200 (2005-09-06)
changeset 17271 2756a73f63a5
parent 17221 6cd180204582
child 17412 e26cb20ef0cc
permissions -rw-r--r--
introduced some new-style AList operations
     1 (*  Title:      Pure/type.ML
     2     ID:         $Id$
     3     Author:     Tobias Nipkow, Lawrence C Paulson, and Markus Wenzel
     4 
     5 Type signatures and certified types, special treatment of type vars,
     6 matching and unification of types, extend and merge type signatures.
     7 *)
     8 
     9 signature TYPE =
    10 sig
    11   (*type signatures and certified types*)
    12   datatype decl =
    13     LogicalType of int |
    14     Abbreviation of string list * typ * bool |
    15     Nonterminal
    16   type tsig
    17   val rep_tsig: tsig ->
    18    {classes: NameSpace.T * Sorts.classes,
    19     default: sort,
    20     types: (decl * stamp) NameSpace.table,
    21     arities: Sorts.arities,
    22     log_types: string list,
    23     witness: (typ * sort) option}
    24   val empty_tsig: tsig
    25   val classes: tsig -> class list
    26   val defaultS: tsig -> sort
    27   val logical_types: tsig -> string list
    28   val universal_witness: tsig -> (typ * sort) option
    29   val eq_sort: tsig -> sort * sort -> bool
    30   val subsort: tsig -> sort * sort -> bool
    31   val of_sort: tsig -> typ * sort -> bool
    32   val cert_class: tsig -> class -> class
    33   val cert_sort: tsig -> sort -> sort
    34   val witness_sorts: tsig -> sort list -> sort list -> (typ * sort) list
    35   val cert_typ: tsig -> typ -> typ
    36   val cert_typ_syntax: tsig -> typ -> typ
    37   val cert_typ_abbrev: tsig -> typ -> typ
    38 
    39   (*special treatment of type vars*)
    40   val strip_sorts: typ -> typ
    41   val no_tvars: typ -> typ
    42   val varifyT: typ -> typ
    43   val unvarifyT: typ -> typ
    44   val varify: term * (string * sort) list -> term * ((string * sort) * indexname) list
    45   val freeze_thaw_type: typ -> typ * (typ -> typ)
    46   val freeze_type: typ -> typ
    47   val freeze_thaw: term -> term * (term -> term)
    48   val freeze: term -> term
    49 
    50   (*matching and unification*)
    51   exception TYPE_MATCH
    52   type tyenv
    53   val lookup: tyenv * (indexname * sort) -> typ option
    54   val typ_match: tsig -> typ * typ -> tyenv -> tyenv
    55   val typ_instance: tsig -> typ * typ -> bool
    56   val raw_match: typ * typ -> tyenv -> tyenv
    57   val raw_instance: typ * typ -> bool
    58   exception TUNIFY
    59   val unify: tsig -> typ * typ -> tyenv * int -> tyenv * int
    60   val raw_unify: typ * typ -> tyenv -> tyenv
    61   val eq_type: tyenv -> typ * typ -> bool
    62 
    63   (*extend and merge type signatures*)
    64   val add_classes: Pretty.pp -> NameSpace.naming -> (bstring * class list) list -> tsig -> tsig
    65   val hide_classes: bool -> string list -> tsig -> tsig
    66   val add_classrel: Pretty.pp -> (class * class) list -> tsig -> tsig
    67   val set_defsort: sort -> tsig -> tsig
    68   val add_types: NameSpace.naming -> (bstring * int) list -> tsig -> tsig
    69   val add_abbrevs: NameSpace.naming -> (string * string list * typ) list -> tsig -> tsig
    70   val add_nonterminals: NameSpace.naming -> string list -> tsig -> tsig
    71   val hide_types: bool -> string list -> tsig -> tsig
    72   val add_arities: Pretty.pp -> arity list -> tsig -> tsig
    73   val merge_tsigs: Pretty.pp -> tsig * tsig -> tsig
    74 end;
    75 
    76 structure Type: TYPE =
    77 struct
    78 
    79 (** type signatures and certified types **)
    80 
    81 (* type declarations *)
    82 
    83 datatype decl =
    84   LogicalType of int |
    85   Abbreviation of string list * typ * bool |
    86   Nonterminal;
    87 
    88 fun str_of_decl (LogicalType _) = "logical type constructor"
    89   | str_of_decl (Abbreviation _) = "type abbreviation"
    90   | str_of_decl Nonterminal = "syntactic type";
    91 
    92 
    93 (* type tsig *)
    94 
    95 datatype tsig =
    96   TSig of {
    97     classes: NameSpace.T * Sorts.classes,   (*declared classes with proper subclass relation*)
    98     default: sort,                          (*default sort on input*)
    99     types: (decl * stamp) NameSpace.table,  (*declared types*)
   100     arities: Sorts.arities,                 (*image specification of types wrt. sorts*)
   101     log_types: string list,                 (*logical types sorted by number of arguments*)
   102     witness: (typ * sort) option};          (*witness for non-emptiness of strictest sort*)
   103 
   104 fun rep_tsig (TSig comps) = comps;
   105 
   106 fun make_tsig (classes, default, types, arities, log_types, witness) =
   107   TSig {classes = classes, default = default, types = types, arities = arities,
   108     log_types = log_types, witness = witness};
   109 
   110 fun build_tsig (classes, default, types, arities) =
   111   let
   112     val log_types =
   113       Symtab.fold (fn (c, (LogicalType n, _)) => cons (c, n) | _ => I) (#2 types) []
   114       |> Library.sort (Library.int_ord o pairself #2) |> map #1;
   115     val witness =
   116       (case Sorts.witness_sorts (#2 classes, arities) log_types [] [Graph.keys (#2 classes)] of
   117         [w] => SOME w | _ => NONE);
   118   in make_tsig (classes, default, types, arities, log_types, witness) end;
   119 
   120 fun map_tsig f (TSig {classes, default, types, arities, log_types = _, witness = _}) =
   121   build_tsig (f (classes, default, types, arities));
   122 
   123 val empty_tsig =
   124   build_tsig ((NameSpace.empty, Graph.empty), [], NameSpace.empty_table, Symtab.empty);
   125 
   126 
   127 (* classes and sorts *)
   128 
   129 fun classes (TSig {classes = (_, C), ...}) = Graph.keys C;
   130 fun defaultS (TSig {default, ...}) = default;
   131 fun logical_types (TSig {log_types, ...}) = log_types;
   132 fun universal_witness (TSig {witness, ...}) = witness;
   133 
   134 fun eq_sort (TSig {classes, ...}) = Sorts.sort_eq (#2 classes);
   135 fun subsort (TSig {classes, ...}) = Sorts.sort_le (#2 classes);
   136 fun of_sort (TSig {classes, arities, ...}) = Sorts.of_sort (#2 classes, arities);
   137 
   138 fun cert_class (TSig {classes, ...}) = Sorts.certify_class (#2 classes);
   139 fun cert_sort (TSig {classes, ...}) = Sorts.certify_sort (#2 classes);
   140 
   141 fun witness_sorts (tsig as TSig {classes, arities, log_types, ...}) =
   142   Sorts.witness_sorts (#2 classes, arities) log_types;
   143 
   144 
   145 (* certified types *)
   146 
   147 fun bad_nargs t = "Bad number of arguments for type constructor: " ^ quote t;
   148 fun undecl_type c = "Undeclared type constructor: " ^ quote c;
   149 
   150 local
   151 
   152 fun inst_typ env (Type (c, Ts)) = Type (c, map (inst_typ env) Ts)
   153   | inst_typ env (T as TFree (x, _)) = if_none (AList.lookup (op =) env x) T
   154   | inst_typ _ T = T;
   155 
   156 fun certify_typ normalize syntax tsig ty =
   157   let
   158     val TSig {classes = (_, classes), types = (_, types), ...} = tsig;
   159     fun err msg = raise TYPE (msg, [ty], []);
   160 
   161     val check_syntax =
   162       if syntax then K ()
   163       else fn c => err ("Illegal occurrence of syntactic type: " ^ quote c);
   164 
   165     fun cert (T as Type (c, Ts)) =
   166           let
   167             val Ts' = map cert Ts;
   168             fun nargs n = if length Ts <> n then err (bad_nargs c) else ();
   169           in
   170             (case Symtab.curried_lookup types c of
   171               SOME (LogicalType n, _) => (nargs n; Type (c, Ts'))
   172             | SOME (Abbreviation (vs, U, syn), _) => (nargs (length vs);
   173                 if syn then check_syntax c else ();
   174                 if normalize then inst_typ (vs ~~ Ts') U
   175                 else Type (c, Ts'))
   176             | SOME (Nonterminal, _) => (nargs 0; check_syntax c; T)
   177             | NONE => err (undecl_type c))
   178           end
   179       | cert (TFree (x, S)) = TFree (x, Sorts.certify_sort classes S)
   180       | cert (TVar (xi as (_, i), S)) =
   181           if i < 0 then
   182             err ("Malformed type variable: " ^ quote (Term.string_of_vname xi))
   183           else TVar (xi, Sorts.certify_sort classes S);
   184 
   185     val ty' = cert ty;
   186   in if ty = ty' then ty else ty' end;  (*avoid copying of already normal type*)
   187 
   188 in
   189 
   190 val cert_typ        = certify_typ true false;
   191 val cert_typ_syntax = certify_typ true true;
   192 val cert_typ_abbrev = certify_typ false true;
   193 
   194 end;
   195 
   196 
   197 
   198 (** special treatment of type vars **)
   199 
   200 (* strip_sorts *)
   201 
   202 fun strip_sorts (Type (a, Ts)) = Type (a, map strip_sorts Ts)
   203   | strip_sorts (TFree (x, _)) = TFree (x, [])
   204   | strip_sorts (TVar (xi, _)) = TVar (xi, []);
   205 
   206 
   207 (* no_tvars *)
   208 
   209 fun no_tvars T =
   210   (case typ_tvars T of [] => T
   211   | vs => raise TYPE ("Illegal schematic type variable(s): " ^
   212       commas_quote (map (Term.string_of_vname o #1) vs), [T], []));
   213 
   214 
   215 (* varify, unvarify *)
   216 
   217 val varifyT = map_type_tfree (fn (a, S) => TVar ((a, 0), S));
   218 val unvarifyT = map_type_tvar (fn ((a, 0), S) => TFree (a, S) | v => TVar v);
   219 
   220 fun varify (t, fixed) =
   221   let
   222     val fs = add_term_tfrees (t, []) \\ fixed;
   223     val ixns = add_term_tvar_ixns (t, []);
   224     val fmap = fs ~~ map (rpair 0) (variantlist (map fst fs, map #1 ixns))
   225     fun thaw (f as (a, S)) =
   226       (case AList.lookup (op =) fmap f of
   227         NONE => TFree f
   228       | SOME xi => TVar (xi, S));
   229   in (map_term_types (map_type_tfree thaw) t, fmap) end;
   230 
   231 
   232 (* freeze_thaw: freeze TVars in a term; return the "thaw" inverse *)
   233 
   234 local
   235 
   236 fun new_name (ix, (pairs, used)) =
   237   let val v = variant used (string_of_indexname ix)
   238   in ((ix, v) :: pairs, v :: used) end;
   239 
   240 fun freeze_one alist (ix, sort) =
   241   TFree (the (AList.lookup (op =) alist ix), sort)
   242     handle Option =>
   243       raise TYPE ("Failure during freezing of ?" ^ string_of_indexname ix, [], []);
   244 
   245 fun thaw_one alist (a, sort) = TVar (the (AList.lookup (op =) alist a), sort)
   246   handle Option => TFree (a, sort);
   247 
   248 in
   249 
   250 (*this sort of code could replace unvarifyT*)
   251 fun freeze_thaw_type T =
   252   let
   253     val used = add_typ_tfree_names (T, [])
   254     and tvars = map #1 (add_typ_tvars (T, []));
   255     val (alist, _) = foldr new_name ([], used) tvars;
   256   in (map_type_tvar (freeze_one alist) T, map_type_tfree (thaw_one (map swap alist))) end;
   257 
   258 val freeze_type = #1 o freeze_thaw_type;
   259 
   260 fun freeze_thaw t =
   261   let
   262     val used = it_term_types add_typ_tfree_names (t, [])
   263     and tvars = map #1 (it_term_types add_typ_tvars (t, []));
   264     val (alist, _) = foldr new_name ([], used) tvars;
   265   in
   266     (case alist of
   267       [] => (t, fn x => x) (*nothing to do!*)
   268     | _ => (map_term_types (map_type_tvar (freeze_one alist)) t,
   269       map_term_types (map_type_tfree (thaw_one (map swap alist)))))
   270   end;
   271 
   272 val freeze = #1 o freeze_thaw;
   273 
   274 end;
   275 
   276 
   277 
   278 (** matching and unification of types **)
   279 
   280 type tyenv = (sort * typ) Vartab.table;
   281 
   282 fun tvar_clash ixn S S' = raise TYPE ("Type variable " ^
   283   quote (Term.string_of_vname ixn) ^ " has two distinct sorts",
   284   [TVar (ixn, S), TVar (ixn, S')], []);
   285 
   286 fun lookup (tye, (ixn, S)) =
   287   (case Vartab.curried_lookup tye ixn of
   288     NONE => NONE
   289   | SOME (S', T) => if S = S' then SOME T else tvar_clash ixn S S');
   290 
   291 
   292 (* matching *)
   293 
   294 exception TYPE_MATCH;
   295 
   296 fun typ_match tsig =
   297   let
   298     fun match (TVar (v, S), T) subs =
   299           (case lookup (subs, (v, S)) of
   300             NONE =>
   301               if of_sort tsig (T, S) then Vartab.curried_update_new (v, (S, T)) subs
   302               else raise TYPE_MATCH
   303           | SOME U => if U = T then subs else raise TYPE_MATCH)
   304       | match (Type (a, Ts), Type (b, Us)) subs =
   305           if a <> b then raise TYPE_MATCH
   306           else matches (Ts, Us) subs
   307       | match (TFree x, TFree y) subs =
   308           if x = y then subs else raise TYPE_MATCH
   309       | match _ _ = raise TYPE_MATCH
   310     and matches (T :: Ts, U :: Us) subs = matches (Ts, Us) (match (T, U) subs)
   311       | matches _ subs = subs;
   312   in match end;
   313 
   314 fun typ_instance tsig (T, U) =
   315   (typ_match tsig (U, T) Vartab.empty; true) handle TYPE_MATCH => false;
   316 
   317 (*purely structural matching*)
   318 fun raw_match (TVar (v, S), T) subs =
   319       (case lookup (subs, (v, S)) of
   320         NONE => Vartab.curried_update_new (v, (S, T)) subs
   321       | SOME U => if U = T then subs else raise TYPE_MATCH)
   322   | raw_match (Type (a, Ts), Type (b, Us)) subs =
   323       if a <> b then raise TYPE_MATCH
   324       else raw_matches (Ts, Us) subs
   325   | raw_match (TFree x, TFree y) subs =
   326       if x = y then subs else raise TYPE_MATCH
   327   | raw_match _ _ = raise TYPE_MATCH
   328 and raw_matches (T :: Ts, U :: Us) subs = raw_matches (Ts, Us) (raw_match (T, U) subs)
   329   | raw_matches _ subs = subs;
   330 
   331 fun raw_instance (T, U) =
   332   (raw_match (U, T) Vartab.empty; true) handle TYPE_MATCH => false;
   333 
   334 
   335 (* unification *)
   336 
   337 exception TUNIFY;
   338 
   339 (*occurs_check*)
   340 fun occurs v tye =
   341   let
   342     fun occ (Type (_, Ts)) = exists occ Ts
   343       | occ (TFree _) = false
   344       | occ (TVar (w, S)) =
   345           eq_ix (v, w) orelse
   346             (case lookup (tye, (w, S)) of
   347               NONE => false
   348             | SOME U => occ U);
   349   in occ end;
   350 
   351 (*chase variable assignments; if devar returns a type var then it must be unassigned*)
   352 fun devar tye (T as TVar v) =
   353       (case lookup (tye, v) of
   354         SOME U => devar tye U
   355       | NONE => T)
   356   | devar tye T = T;
   357 
   358 fun unify (tsig as TSig {classes = (_, classes), arities, ...}) TU (tyenv, maxidx) =
   359   let
   360     val tyvar_count = ref maxidx;
   361     fun gen_tyvar S = TVar (("'a", inc tyvar_count), S);
   362 
   363     fun mg_domain a S =
   364       Sorts.mg_domain (classes, arities) a S handle Sorts.DOMAIN _ => raise TUNIFY;
   365 
   366     fun meet (_, []) tye = tye
   367       | meet (TVar (xi, S'), S) tye =
   368           if Sorts.sort_le classes (S', S) then tye
   369           else Vartab.curried_update_new
   370             (xi, (S', gen_tyvar (Sorts.inter_sort classes (S', S)))) tye
   371       | meet (TFree (_, S'), S) tye =
   372           if Sorts.sort_le classes (S', S) then tye
   373           else raise TUNIFY
   374       | meet (Type (a, Ts), S) tye = meets (Ts, mg_domain a S) tye
   375     and meets (T :: Ts, S :: Ss) tye = meets (Ts, Ss) (meet (devar tye T, S) tye)
   376       | meets _ tye = tye;
   377 
   378     fun unif (ty1, ty2) tye =
   379       (case (devar tye ty1, devar tye ty2) of
   380         (T as TVar (v, S1), U as TVar (w, S2)) =>
   381           if eq_ix (v, w) then
   382             if S1 = S2 then tye else tvar_clash v S1 S2
   383           else if Sorts.sort_le classes (S1, S2) then
   384             Vartab.curried_update_new (w, (S2, T)) tye
   385           else if Sorts.sort_le classes (S2, S1) then
   386             Vartab.curried_update_new (v, (S1, U)) tye
   387           else
   388             let val S = gen_tyvar (Sorts.inter_sort classes (S1, S2)) in
   389               Vartab.curried_update_new (v, (S1, S)) (Vartab.curried_update_new (w, (S2, S)) tye)
   390             end
   391       | (TVar (v, S), T) =>
   392           if occurs v tye T then raise TUNIFY
   393           else meet (T, S) (Vartab.curried_update_new (v, (S, T)) tye)
   394       | (T, TVar (v, S)) =>
   395           if occurs v tye T then raise TUNIFY
   396           else meet (T, S) (Vartab.curried_update_new (v, (S, T)) tye)
   397       | (Type (a, Ts), Type (b, Us)) =>
   398           if a <> b then raise TUNIFY
   399           else unifs (Ts, Us) tye
   400       | (T, U) => if T = U then tye else raise TUNIFY)
   401     and unifs (T :: Ts, U :: Us) tye = unifs (Ts, Us) (unif (T, U) tye)
   402       | unifs _ tye = tye;
   403   in (unif TU tyenv, ! tyvar_count) end;
   404 
   405 (*purely structural unification*)
   406 fun raw_unify (ty1, ty2) tye =
   407   (case (devar tye ty1, devar tye ty2) of
   408     (T as TVar (v, S1), U as TVar (w, S2)) =>
   409       if eq_ix (v, w) then
   410         if S1 = S2 then tye else tvar_clash v S1 S2
   411       else Vartab.curried_update_new (w, (S2, T)) tye
   412   | (TVar (v, S), T) =>
   413       if occurs v tye T then raise TUNIFY
   414       else Vartab.curried_update_new (v, (S, T)) tye
   415   | (T, TVar (v, S)) =>
   416       if occurs v tye T then raise TUNIFY
   417       else Vartab.curried_update_new (v, (S, T)) tye
   418   | (Type (a, Ts), Type (b, Us)) =>
   419       if a <> b then raise TUNIFY
   420       else raw_unifys (Ts, Us) tye
   421   | (T, U) => if T = U then tye else raise TUNIFY)
   422 and raw_unifys (T :: Ts, U :: Us) tye = raw_unifys (Ts, Us) (raw_unify (T, U) tye)
   423   | raw_unifys _ tye = tye;
   424 
   425 
   426 (*check whether two types are equal with respect to a type environment*)
   427 fun eq_type tye (T, T') =
   428   (case (devar tye T, devar tye T') of
   429      (Type (s, Ts), Type (s', Ts')) =>
   430        s = s' andalso ListPair.all (eq_type tye) (Ts, Ts')
   431    | (U, U') => U = U');
   432 
   433 
   434 
   435 (** extend and merge type signatures **)
   436 
   437 (* arities *)
   438 
   439 local
   440 
   441 fun err_decl t decl = error ("Illegal " ^ str_of_decl decl ^ ": " ^ quote t);
   442 
   443 fun for_classes _ NONE = ""
   444   | for_classes pp (SOME (c1, c2)) =
   445       " for classes " ^ Pretty.string_of_classrel pp [c1, c2];
   446 
   447 fun err_conflict pp t cc (c, Ss) (c', Ss') =
   448   error ("Conflict of type arities" ^ for_classes pp cc ^ ":\n  " ^
   449     Pretty.string_of_arity pp (t, Ss, [c]) ^ " and\n  " ^
   450     Pretty.string_of_arity pp (t, Ss', [c']));
   451 
   452 fun coregular pp C t (c, Ss) ars =
   453   let
   454     fun conflict (c', Ss') =
   455       if Sorts.class_le C (c, c') andalso not (Sorts.sorts_le C (Ss, Ss')) then
   456         SOME ((c, c'), (c', Ss'))
   457       else if Sorts.class_le C (c', c) andalso not (Sorts.sorts_le C (Ss', Ss)) then
   458         SOME ((c', c), (c', Ss'))
   459       else NONE;
   460   in
   461     (case Library.get_first conflict ars of
   462       SOME ((c1, c2), (c', Ss')) => err_conflict pp t (SOME (c1, c2)) (c, Ss) (c', Ss')
   463     | NONE => (c, Ss) :: ars)
   464   end;
   465 
   466 fun insert pp C t (c, Ss) ars =
   467   (case AList.lookup (op =) ars c of
   468     NONE => coregular pp C t (c, Ss) ars
   469   | SOME Ss' =>
   470       if Sorts.sorts_le C (Ss, Ss') then ars
   471       else if Sorts.sorts_le C (Ss', Ss)
   472       then coregular pp C t (c, Ss) (ars \ (c, Ss'))
   473       else err_conflict pp t NONE (c, Ss) (c, Ss'));
   474 
   475 fun complete C (c, Ss) = map (rpair Ss) (Graph.all_succs C [c]);
   476 
   477 fun insert_arities pp classes (t, ars) arities =
   478   let val ars' =
   479     Symtab.curried_lookup_multi arities t
   480     |> fold_rev (fold_rev (insert pp classes t)) (map (complete classes) ars)
   481   in Symtab.curried_update (t, ars') arities end;
   482 
   483 fun insert_table pp classes = Symtab.fold (fn (t, ars) =>
   484   insert_arities pp classes (t, map (apsnd (map (Sorts.norm_sort classes))) ars));
   485 
   486 in
   487 
   488 fun add_arities pp decls tsig = tsig |> map_tsig (fn (classes, default, types, arities) =>
   489   let
   490     fun prep (t, Ss, S) =
   491       (case Symtab.curried_lookup (#2 types) t of
   492         SOME (LogicalType n, _) =>
   493           if length Ss = n then
   494             (t, map (cert_sort tsig) Ss, cert_sort tsig S)
   495               handle TYPE (msg, _, _) => error msg
   496           else error (bad_nargs t)
   497       | SOME (decl, _) => err_decl t decl
   498       | NONE => error (undecl_type t));
   499 
   500     val ars = decls |> map ((fn (t, Ss, S) => (t, map (fn c => (c, Ss)) S)) o prep);
   501     val arities' = fold (insert_arities pp (#2 classes)) ars arities;
   502   in (classes, default, types, arities') end);
   503 
   504 fun rebuild_arities pp classes arities =
   505   Symtab.empty
   506   |> insert_table pp classes arities;
   507 
   508 fun merge_arities pp classes (arities1, arities2) =
   509   Symtab.empty
   510   |> insert_table pp classes arities1
   511   |> insert_table pp classes arities2;
   512 
   513 end;
   514 
   515 
   516 (* classes *)
   517 
   518 local
   519 
   520 fun err_dup_classes cs =
   521   error ("Duplicate declaration of class(es): " ^ commas_quote cs);
   522 
   523 fun err_cyclic_classes pp css =
   524   error (cat_lines (map (fn cs =>
   525     "Cycle in class relation: " ^ Pretty.string_of_classrel pp cs) css));
   526 
   527 fun add_class pp naming (c, cs) tsig =
   528   tsig |> map_tsig (fn ((space, classes), default, types, arities) =>
   529     let
   530       val c' = NameSpace.full naming c;
   531       val cs' = map (cert_class tsig) cs
   532         handle TYPE (msg, _, _) => error msg;
   533       val space' = space |> NameSpace.declare naming c';
   534       val classes' = classes |> Graph.new_node (c', stamp ())
   535         handle Graph.DUP dup => err_dup_classes [dup];
   536       val classes'' = classes' |> fold Graph.add_edge_trans_acyclic (map (pair c') cs')
   537         handle Graph.CYCLES css => err_cyclic_classes pp css;
   538     in ((space', classes''), default, types, arities) end);
   539 
   540 in
   541 
   542 val add_classes = fold oo add_class;
   543 
   544 fun add_classrel pp ps tsig =
   545   tsig |> map_tsig (fn ((space, classes), default, types, arities) =>
   546     let
   547       val ps' = map (pairself (cert_class tsig)) ps
   548         handle TYPE (msg, _, _) => error msg;
   549       val classes' = classes |> fold Graph.add_edge_trans_acyclic ps'
   550         handle Graph.CYCLES css => err_cyclic_classes pp css;
   551       val default' = default |> Sorts.norm_sort classes';
   552       val arities' = arities |> rebuild_arities pp classes';
   553     in ((space, classes'), default', types, arities') end);
   554 
   555 fun merge_classes pp ((space1, classes1), (space2, classes2)) =
   556   let
   557     val space = NameSpace.merge (space1, space2);
   558     val classes =
   559       Graph.merge_trans_acyclic (op =) (classes1, classes2)
   560         handle Graph.DUPS cs => err_dup_classes cs
   561           | Graph.CYCLES css => err_cyclic_classes pp css;
   562   in (space, classes) end;
   563 
   564 end;
   565 
   566 fun hide_classes fully cs = map_tsig (fn ((space, classes), default, types, arities) =>
   567   ((fold (NameSpace.hide fully) cs space, classes), default, types, arities));
   568 
   569 
   570 (* default sort *)
   571 
   572 fun set_defsort S tsig = tsig |> map_tsig (fn (classes, _, types, arities) =>
   573   (classes, cert_sort tsig S handle TYPE (msg, _, _) => error msg, types, arities));
   574 
   575 
   576 (* types *)
   577 
   578 local
   579 
   580 fun err_neg_args c =
   581   error ("Negative number of arguments in type constructor declaration: " ^ quote c);
   582 
   583 fun err_in_decls c decl decl' =
   584   let val s = str_of_decl decl and s' = str_of_decl decl' in
   585     if s = s' then error ("Duplicate declaration of " ^ s ^ ": " ^ quote c)
   586     else error ("Conflict of " ^ s ^ " with " ^ s' ^ ": " ^ quote c)
   587   end;
   588 
   589 fun new_decl naming (c, decl) (space, types) =
   590   let
   591     val c' = NameSpace.full naming c;
   592     val space' = NameSpace.declare naming c' space;
   593     val types' =
   594       (case Symtab.curried_lookup types c' of
   595         SOME (decl', _) => err_in_decls c' decl decl'
   596       | NONE => Symtab.curried_update (c', (decl, stamp ())) types);
   597   in (space', types') end;
   598 
   599 fun the_decl (_, types) = fst o the o Symtab.curried_lookup types;
   600 
   601 fun change_types f = map_tsig (fn (classes, default, types, arities) =>
   602   (classes, default, f types, arities));
   603 
   604 fun syntactic types (Type (c, Ts)) =
   605       (case Symtab.curried_lookup types c of SOME (Nonterminal, _) => true | _ => false)
   606         orelse exists (syntactic types) Ts
   607   | syntactic _ _ = false;
   608 
   609 fun add_abbrev naming (a, vs, rhs) tsig = tsig |> change_types (fn types =>
   610   let
   611     fun err msg =
   612       error (msg ^ "\nThe error(s) above occurred in type abbreviation: " ^ quote a);
   613     val rhs' = strip_sorts (no_tvars (cert_typ_syntax tsig rhs))
   614       handle TYPE (msg, _, _) => err msg;
   615   in
   616     (case duplicates vs of
   617       [] => []
   618     | dups => err ("Duplicate variables on lhs: " ^ commas_quote dups));
   619     (case gen_rems (op =) (map (#1 o #1) (typ_tvars rhs'), vs) of
   620       [] => []
   621     | extras => err ("Extra variables on rhs: " ^ commas_quote extras));
   622     types |> new_decl naming (a, Abbreviation (vs, rhs', syntactic (#2 types) rhs'))
   623   end);
   624 
   625 in
   626 
   627 fun add_types naming ps = change_types (fold (new_decl naming) (ps |> map (fn (c, n) =>
   628   if n < 0 then err_neg_args c else (c, LogicalType n))));
   629 
   630 val add_abbrevs = fold o add_abbrev;
   631 
   632 fun add_nonterminals naming = change_types o fold (new_decl naming) o map (rpair Nonterminal);
   633 
   634 fun merge_types (types1, types2) =
   635   NameSpace.merge_tables Library.eq_snd (types1, types2) handle Symtab.DUPS (d :: _) =>
   636     err_in_decls d (the_decl types1 d) (the_decl types2 d);
   637 
   638 end;
   639 
   640 fun hide_types fully cs = map_tsig (fn (classes, default, (space, types), arities) =>
   641   (classes, default, (fold (NameSpace.hide fully) cs space, types), arities));
   642 
   643 
   644 (* merge type signatures *)
   645 
   646 fun merge_tsigs pp (tsig1, tsig2) =
   647   let
   648     val (TSig {classes = classes1, default = default1, types = types1, arities = arities1,
   649       log_types = _, witness = _}) = tsig1;
   650     val (TSig {classes = classes2, default = default2, types = types2, arities = arities2,
   651       log_types = _, witness = _}) = tsig2;
   652 
   653     val classes' = merge_classes pp (classes1, classes2);
   654     val default' = Sorts.inter_sort (#2 classes') (default1, default2);
   655     val types' = merge_types (types1, types2);
   656     val arities' = merge_arities pp (#2 classes') (arities1, arities2);
   657   in build_tsig (classes', default', types', arities') end;
   658 
   659 end;