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