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