src/Pure/type.ML
author skalberg
Thu Mar 03 12:43:01 2005 +0100 (2005-03-03 ago)
changeset 15570 8d8c70b41bab
parent 15531 08c8dad8e399
child 15574 b1d1b5bfc464
permissions -rw-r--r--
Move towards standard functions.
     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: Sorts.classes,
    19     default: sort,
    20     types: (decl * stamp) Symtab.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_raw: 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 list -> term * (string * indexname) list
    45   val freeze_thaw_type : typ -> typ * (typ -> typ)
    46   val freeze_thaw : term -> term * (term -> term)
    47 
    48   (*matching and unification*)
    49   val inst_typ_tvars: Pretty.pp -> tsig -> (indexname * typ) list -> typ -> typ
    50   val inst_term_tvars: Pretty.pp -> tsig -> (indexname * typ) list -> term -> term
    51   exception TYPE_MATCH
    52   val typ_match: tsig -> typ Vartab.table * (typ * typ) -> typ Vartab.table
    53   val typ_instance: tsig -> typ * typ -> bool
    54   exception TUNIFY
    55   val unify: tsig -> typ Vartab.table * int -> typ * typ -> typ Vartab.table * int
    56   val raw_unify: typ * typ -> bool
    57 
    58   (*extend and merge type signatures*)
    59   val add_classes: Pretty.pp -> (class * class list) list -> tsig -> tsig
    60   val add_classrel: Pretty.pp -> (class * class) list -> tsig -> tsig
    61   val set_defsort: sort -> tsig -> tsig
    62   val add_types: (string * int) list -> tsig -> tsig
    63   val add_abbrs: (string * string list * typ) list -> tsig -> tsig
    64   val add_nonterminals: string list -> tsig -> tsig
    65   val add_arities: Pretty.pp -> arity list -> tsig -> tsig
    66   val merge_tsigs: Pretty.pp -> tsig * tsig -> tsig
    67 end;
    68 
    69 structure Type: TYPE =
    70 struct
    71 
    72 (** type signatures and certified types **)
    73 
    74 (* type declarations *)
    75 
    76 datatype decl =
    77   LogicalType of int |
    78   Abbreviation of string list * typ * bool |
    79   Nonterminal;
    80 
    81 fun str_of_decl (LogicalType _) = "logical type constructor"
    82   | str_of_decl (Abbreviation _) = "type abbreviation"
    83   | str_of_decl Nonterminal = "syntactic type";
    84 
    85 
    86 (* type tsig *)
    87 
    88 datatype tsig =
    89   TSig of {
    90     classes: Sorts.classes,              (*declared classes with proper subclass relation*)
    91     default: sort,                       (*default sort on input*)
    92     types: (decl * stamp) Symtab.table,  (*declared types*)
    93     arities: Sorts.arities,              (*image specification of types wrt. sorts*)
    94     log_types: string list,              (*logical types sorted by number of arguments*)
    95     witness: (typ * sort) option};       (*witness for non-emptiness of strictest sort*)
    96 
    97 fun rep_tsig (TSig comps) = comps;
    98 
    99 fun make_tsig (classes, default, types, arities, log_types, witness) =
   100   TSig {classes = classes, default = default, types = types, arities = arities,
   101     log_types = log_types, witness = witness};
   102 
   103 fun map_tsig f (TSig {classes, default, types, arities, log_types, witness}) =
   104   make_tsig (f (classes, default, types, arities, log_types, witness));
   105 
   106 fun build_tsig (classes, default, types, arities) =
   107   let
   108     fun add_log_type (ts, (c, (LogicalType n, _))) = (c, n) :: ts
   109       | add_log_type (ts, _) = ts;
   110     val log_types =
   111       Symtab.foldl add_log_type ([], types)
   112       |> Library.sort (Library.int_ord o pairself #2) |> map #1;
   113     val witness =
   114       (case Sorts.witness_sorts (classes, arities) log_types [] [Graph.keys classes] of
   115         [w] => SOME w | _ => NONE);
   116   in make_tsig (classes, default, types, arities, log_types, witness) end;
   117 
   118 fun change_tsig f (TSig {classes, default, types, arities, log_types = _, witness = _}) =
   119   build_tsig (f (classes, default, types, arities));
   120 
   121 val empty_tsig = build_tsig (Graph.empty, [], Symtab.empty, Symtab.empty);
   122 
   123 
   124 (* classes and sorts *)
   125 
   126 fun classes (TSig {classes = C, ...}) = Graph.keys C;
   127 fun defaultS (TSig {default, ...}) = default;
   128 fun logical_types (TSig {log_types, ...}) = log_types;
   129 fun universal_witness (TSig {witness, ...}) = witness;
   130 
   131 fun eq_sort (TSig {classes, ...}) = Sorts.sort_eq classes;
   132 fun subsort (TSig {classes, ...}) = Sorts.sort_le classes;
   133 fun of_sort (TSig {classes, arities, ...}) = Sorts.of_sort (classes, arities);
   134 
   135 fun cert_class (TSig {classes, ...}) = Sorts.certify_class classes;
   136 fun cert_sort (TSig {classes, ...}) = Sorts.certify_sort classes;
   137 
   138 fun witness_sorts (tsig as TSig {classes, arities, log_types, ...}) =
   139   Sorts.witness_sorts (classes, arities) log_types;
   140 
   141 
   142 (* certified types *)
   143 
   144 fun bad_nargs t = "Bad number of arguments for type constructor: " ^ quote t;
   145 fun undecl_type c = "Undeclared type constructor: " ^ quote c;
   146 
   147 local
   148 
   149 fun inst_typ env (Type (c, Ts)) = Type (c, map (inst_typ env) Ts)
   150   | inst_typ env (T as TFree (x, _)) = getOpt (Library.assoc_string (env, x),T)
   151   | inst_typ _ T = T;
   152 
   153 fun certify_typ normalize syntax tsig ty =
   154   let
   155     val TSig {classes, types, ...} = tsig;
   156     fun err msg = raise TYPE (msg, [ty], []);
   157 
   158     val check_syntax =
   159       if syntax then K ()
   160       else fn c => err ("Illegal occurrence of syntactic type: " ^ quote c);
   161 
   162     fun cert (T as Type (c, Ts)) =
   163           let
   164             val Ts' = map cert Ts;
   165             fun nargs n = if length Ts <> n then err (bad_nargs c) else ();
   166           in
   167             (case Symtab.lookup (types, c) of
   168               SOME (LogicalType n, _) => (nargs n; Type (c, Ts'))
   169             | SOME (Abbreviation (vs, U, syn), _) => (nargs (length vs);
   170                 if syn then check_syntax c else ();
   171                 if normalize then inst_typ (vs ~~ Ts') U
   172                 else Type (c, Ts'))
   173             | SOME (Nonterminal, _) => (nargs 0; check_syntax c; T)
   174             | NONE => err (undecl_type c))
   175           end
   176       | cert (TFree (x, S)) = TFree (x, Sorts.certify_sort classes S)
   177       | cert (TVar (xi as (_, i), S)) =
   178           if i < 0 then
   179             err ("Malformed type variable: " ^ quote (Term.string_of_vname xi))
   180           else TVar (xi, Sorts.certify_sort classes S);
   181 
   182     val ty' = cert ty;
   183   in if ty = ty' then ty else ty' end;  (*avoid copying of already normal type*)
   184 
   185 in
   186 
   187 val cert_typ         = certify_typ true false;
   188 val cert_typ_syntax  = certify_typ true true;
   189 val cert_typ_raw     = certify_typ false true;
   190 
   191 end;
   192 
   193 
   194 
   195 (** special treatment of type vars **)
   196 
   197 (* strip_sorts *)
   198 
   199 fun strip_sorts (Type (a, Ts)) = Type (a, map strip_sorts Ts)
   200   | strip_sorts (TFree (x, _)) = TFree (x, [])
   201   | strip_sorts (TVar (xi, _)) = TVar (xi, []);
   202 
   203 
   204 (* no_tvars *)
   205 
   206 fun no_tvars T =
   207   (case typ_tvars T of [] => T
   208   | vs => raise TYPE ("Illegal schematic type variable(s): " ^
   209       commas_quote (map (Term.string_of_vname o #1) vs), [T], []));
   210 
   211 
   212 (* varify, unvarify *)
   213 
   214 val varifyT = map_type_tfree (fn (a, S) => TVar ((a, 0), S));
   215 
   216 fun unvarifyT (Type (a, Ts)) = Type (a, map unvarifyT Ts)
   217   | unvarifyT (TVar ((a, 0), S)) = TFree (a, S)
   218   | unvarifyT T = T;
   219 
   220 fun varify (t, fixed) =
   221   let
   222     val fs = add_term_tfree_names (t, []) \\ fixed;
   223     val ixns = add_term_tvar_ixns (t, []);
   224     val fmap = fs ~~ map (rpair 0) (variantlist (fs, map #1 ixns))
   225     fun thaw (f as (a, S)) =
   226       (case assoc (fmap, a) of
   227         NONE => TFree f
   228       | SOME b => TVar (b, 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 (valOf (assoc (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 (valOf (assoc (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, _) = Library.foldr new_name (tvars, ([], used));
   256   in (map_type_tvar (freeze_one alist) T, map_type_tfree (thaw_one (map swap alist))) end;
   257 
   258 fun freeze_thaw t =
   259   let
   260     val used = it_term_types add_typ_tfree_names (t, [])
   261     and tvars = map #1 (it_term_types add_typ_tvars (t, []));
   262     val (alist, _) = Library.foldr new_name (tvars, ([], used));
   263   in
   264     (case alist of
   265       [] => (t, fn x => x) (*nothing to do!*)
   266     | _ => (map_term_types (map_type_tvar (freeze_one alist)) t,
   267       map_term_types (map_type_tfree (thaw_one (map swap alist)))))
   268   end;
   269 
   270 end;
   271 
   272 
   273 
   274 (** matching and unification of types **)
   275 
   276 (* instantiation *)
   277 
   278 fun inst_typ_tvars pp tsig tye =
   279   let
   280     fun inst (var as (v, S)) =
   281       (case assoc_string_int (tye, v) of
   282         SOME U =>
   283           if of_sort tsig (U, S) then U
   284           else raise TYPE ("Type not of sort " ^ Pretty.string_of_sort pp S, [U], [])
   285       | NONE => TVar var);
   286   in map_type_tvar inst end;
   287 
   288 fun inst_term_tvars _ _ [] t = t
   289   | inst_term_tvars pp tsig tye t = map_term_types (inst_typ_tvars pp tsig tye) t;
   290 
   291 
   292 (* matching *)
   293 
   294 exception TYPE_MATCH;
   295 
   296 fun typ_match tsig =
   297   let
   298     fun match (subs, (TVar (v, S), T)) =
   299           (case Vartab.lookup (subs, v) of
   300             NONE =>
   301               if of_sort tsig (T, S) then Vartab.update ((v, T), subs)
   302               else raise TYPE_MATCH
   303           | SOME U => if U = T then subs else raise TYPE_MATCH)
   304       | match (subs, (Type (a, Ts), Type (b, Us))) =
   305           if a <> b then raise TYPE_MATCH
   306           else Library.foldl match (subs, Ts ~~ Us)
   307       | match (subs, (TFree x, TFree y)) =
   308           if x = y then subs else raise TYPE_MATCH
   309       | match _ = raise TYPE_MATCH;
   310   in match end;
   311 
   312 fun typ_instance tsig (T, U) =
   313   (typ_match tsig (Vartab.empty, (U, T)); true) handle TYPE_MATCH => false;
   314 
   315 
   316 (* unification *)
   317 
   318 exception TUNIFY;
   319 
   320 (*occurs_check*)
   321 fun occurs v tye =
   322   let
   323     fun occ (Type (_, Ts)) = exists occ Ts
   324       | occ (TFree _) = false
   325       | occ (TVar (w, _)) =
   326           eq_ix (v, w) orelse
   327             (case Vartab.lookup (tye, w) of
   328               NONE => false
   329             | SOME U => occ U);
   330   in occ end;
   331 
   332 (*chase variable assignments; if devar returns a type var then it must be unassigned*)
   333 fun devar (T as TVar (v, _), tye) =
   334       (case  Vartab.lookup (tye, v) of
   335         SOME U => devar (U, tye)
   336       | NONE => T)
   337   | devar (T, tye) = T;
   338 
   339 fun unify (tsig as TSig {classes, arities, ...}) (tyenv, maxidx) TU =
   340   let
   341     val tyvar_count = ref maxidx;
   342     fun gen_tyvar S = TVar (("'a", inc tyvar_count), S);
   343 
   344     fun mg_domain a S =
   345       Sorts.mg_domain (classes, arities) a S handle Sorts.DOMAIN _ => raise TUNIFY;
   346 
   347     fun meet ((_, []), tye) = tye
   348       | meet ((TVar (xi, S'), S), tye) =
   349           if Sorts.sort_le classes (S', S) then tye
   350           else Vartab.update_new ((xi,
   351             gen_tyvar (Sorts.inter_sort classes (S', S))), tye)
   352       | meet ((TFree (_, S'), S), tye) =
   353           if Sorts.sort_le classes (S', S) then tye
   354           else raise TUNIFY
   355       | meet ((Type (a, Ts), S), tye) = meets ((Ts, mg_domain a S), tye)
   356     and meets (([], []), tye) = tye
   357       | meets ((T :: Ts, S :: Ss), tye) =
   358           meets ((Ts, Ss), meet ((devar (T, tye), S), tye))
   359       | meets _ = sys_error "meets";
   360 
   361     fun unif ((ty1, ty2), tye) =
   362       (case (devar (ty1, tye), devar (ty2, tye)) of
   363         (T as TVar (v, S1), U as TVar (w, S2)) =>
   364           if eq_ix (v, w) then tye
   365           else if Sorts.sort_le classes (S1, S2) then
   366             Vartab.update_new ((w, T), tye)
   367           else if Sorts.sort_le classes (S2, S1) then
   368             Vartab.update_new ((v, U), tye)
   369           else
   370             let val S = gen_tyvar (Sorts.inter_sort classes (S1, S2)) in
   371               Vartab.update_new ((v, S), Vartab.update_new ((w, S), tye))
   372             end
   373       | (TVar (v, S), T) =>
   374           if occurs v tye T then raise TUNIFY
   375           else meet ((T, S), Vartab.update_new ((v, T), tye))
   376       | (T, TVar (v, S)) =>
   377           if occurs v tye T then raise TUNIFY
   378           else meet ((T, S), Vartab.update_new ((v, T), tye))
   379       | (Type (a, Ts), Type (b, Us)) =>
   380           if a <> b then raise TUNIFY
   381           else Library.foldr unif (Ts ~~ Us, tye)
   382       | (T, U) => if T = U then tye else raise TUNIFY);
   383   in (unif (TU, tyenv), ! tyvar_count) end;
   384 
   385 (*purely structural unification *)
   386 fun raw_unify (ty1, ty2) =
   387   (unify empty_tsig (Vartab.empty, 0) (strip_sorts ty1, strip_sorts ty2); true)
   388     handle TUNIFY => false;
   389 
   390 
   391 
   392 (** extend and merge type signatures **)
   393 
   394 (* arities *)
   395 
   396 local
   397 
   398 fun err_decl t decl = error ("Illegal " ^ str_of_decl decl ^ ": " ^ quote t);
   399 
   400 fun for_classes _ NONE = ""
   401   | for_classes pp (SOME (c1, c2)) =
   402       " for classes " ^ Pretty.string_of_classrel pp [c1, c2];
   403 
   404 fun err_conflict pp t cc (c, Ss) (c', Ss') =
   405   error ("Conflict of type arities" ^ for_classes pp cc ^ ":\n  " ^
   406     Pretty.string_of_arity pp (t, Ss, [c]) ^ " and\n  " ^
   407     Pretty.string_of_arity pp (t, Ss', [c']));
   408 
   409 fun coregular pp C t (c, Ss) ars =
   410   let
   411     fun conflict (c', Ss') =
   412       if Sorts.class_le C (c, c') andalso not (Sorts.sorts_le C (Ss, Ss')) then
   413         SOME ((c, c'), (c', Ss'))
   414       else if Sorts.class_le C (c', c) andalso not (Sorts.sorts_le C (Ss', Ss)) then
   415         SOME ((c', c), (c', Ss'))
   416       else NONE;
   417   in
   418     (case Library.get_first conflict ars of
   419       SOME ((c1, c2), (c', Ss')) => err_conflict pp t (SOME (c1, c2)) (c, Ss) (c', Ss')
   420     | NONE => (c, Ss) :: ars)
   421   end;
   422 
   423 fun insert pp C t ((c, Ss), ars) =
   424   (case assoc_string (ars, c) of
   425     NONE => coregular pp C t (c, Ss) ars
   426   | SOME Ss' =>
   427       if Sorts.sorts_le C (Ss, Ss') then ars
   428       else if Sorts.sorts_le C (Ss', Ss)
   429       then coregular pp C t (c, Ss) (ars \ (c, Ss'))
   430       else err_conflict pp t NONE (c, Ss) (c, Ss'));
   431 
   432 fun complete C (c, Ss) = map (rpair Ss) (Graph.all_succs C [c]);
   433 
   434 fun insert_arities pp classes (arities, (t, ars)) =
   435   let val ars' =
   436     Symtab.lookup_multi (arities, t)
   437     |> curry (Library.foldr (insert pp classes t)) (List.concat (map (complete classes) ars))
   438   in Symtab.update ((t, ars'), arities) end;
   439 
   440 fun insert_table pp classes = Symtab.foldl (fn (arities, (t, ars)) =>
   441   insert_arities pp classes (arities, (t, map (apsnd (map (Sorts.norm_sort classes))) ars)));
   442 
   443 in
   444 
   445 fun add_arities pp decls tsig = tsig |> change_tsig (fn (classes, default, types, arities) =>
   446   let
   447     fun prep (t, Ss, S) =
   448       (case Symtab.lookup (types, t) of
   449         SOME (LogicalType n, _) =>
   450           if length Ss = n then
   451             (t, map (cert_sort tsig) Ss, cert_sort tsig S)
   452               handle TYPE (msg, _, _) => error msg
   453           else error (bad_nargs t)
   454       | SOME (decl, _) => err_decl t decl
   455       | NONE => error (undecl_type t));
   456 
   457     val ars = decls |> map ((fn (t, Ss, S) => (t, map (fn c => (c, Ss)) S)) o prep);
   458     val arities' = Library.foldl (insert_arities pp classes) (arities, ars);
   459   in (classes, default, types, arities') end);
   460 
   461 fun rebuild_arities pp classes arities =
   462   insert_table pp classes (Symtab.empty, arities);
   463 
   464 fun merge_arities pp classes (arities1, arities2) =
   465   insert_table pp classes (insert_table pp classes (Symtab.empty, arities1), arities2);
   466 
   467 end;
   468 
   469 
   470 (* classes *)
   471 
   472 local
   473 
   474 fun err_dup_classes cs =
   475   error ("Duplicate declaration of class(es): " ^ commas_quote cs);
   476 
   477 fun err_cyclic_classes pp css =
   478   error (cat_lines (map (fn cs =>
   479     "Cycle in class relation: " ^ Pretty.string_of_classrel pp cs) css));
   480 
   481 fun add_class pp (c, cs) tsig = tsig |> change_tsig (fn (classes, default, types, arities) =>
   482   let
   483     val cs' = map (cert_class tsig) cs
   484       handle TYPE (msg, _, _) => error msg;
   485     val classes' = classes |> Graph.new_node (c, stamp ())
   486       handle Graph.DUP d => err_dup_classes [d];
   487     val classes'' = classes' |> fold Graph.add_edge_trans_acyclic (map (pair c) cs')
   488       handle Graph.CYCLES css => err_cyclic_classes pp css;
   489   in (classes'', default, types, arities) end);
   490 
   491 in
   492 
   493 val add_classes = fold o add_class;
   494 
   495 fun add_classrel pp ps tsig = tsig |> change_tsig (fn (classes, default, types, arities) =>
   496   let
   497     val ps' = map (pairself (cert_class tsig)) ps
   498       handle TYPE (msg, _, _) => error msg;
   499     val classes' = classes |> fold Graph.add_edge_trans_acyclic ps'
   500       handle Graph.CYCLES css => err_cyclic_classes pp css;
   501     val default' = default |> Sorts.norm_sort classes';
   502     val arities' = arities |> rebuild_arities pp classes';
   503   in (classes', default', types, arities') end);
   504 
   505 fun merge_classes pp CC = Graph.merge_trans_acyclic (op =) CC
   506   handle Graph.DUPS cs => err_dup_classes cs
   507     | Graph.CYCLES css => err_cyclic_classes pp css;
   508 
   509 end;
   510 
   511 
   512 (* default sort *)
   513 
   514 fun set_defsort S tsig = tsig |> change_tsig (fn (classes, _, types, arities) =>
   515   (classes, cert_sort tsig S handle TYPE (msg, _, _) => error msg, types, arities));
   516 
   517 
   518 (* types *)
   519 
   520 local
   521 
   522 fun err_neg_args c =
   523   error ("Negative number of arguments in type constructor declaration: " ^ quote c);
   524 
   525 fun err_in_decls c decl decl' =
   526   let val s = str_of_decl decl and s' = str_of_decl decl' in
   527     if s = s' then error ("Duplicate declaration of " ^ s ^ ": " ^ quote c)
   528     else error ("Conflict of " ^ s ^ " with " ^ s' ^ ": " ^ quote c)
   529   end;
   530 
   531 fun new_decl (c, decl) types =
   532   (case Symtab.lookup (types, c) of
   533     SOME (decl', _) => err_in_decls c decl decl'
   534   | NONE => Symtab.update ((c, (decl, stamp ())), types));
   535 
   536 fun the_decl types c = fst (valOf (Symtab.lookup (types, c)));
   537 
   538 fun change_types f = change_tsig (fn (classes, default, types, arities) =>
   539   (classes, default, f types, arities));
   540 
   541 fun syntactic types (Type (c, Ts)) =
   542       (case Symtab.lookup (types, c) of SOME (Nonterminal, _) => true | _ => false)
   543         orelse exists (syntactic types) Ts
   544   | syntactic _ _ = false;
   545 
   546 fun add_abbr (a, vs, rhs) tsig = tsig |> change_types (fn types =>
   547   let
   548     fun err msg =
   549       error (msg ^ "\nThe error(s) above occurred in type abbreviation: " ^ quote a);
   550     val rhs' = strip_sorts (no_tvars (cert_typ_syntax tsig rhs))
   551       handle TYPE (msg, _, _) => err msg;
   552   in
   553     (case duplicates vs of
   554       [] => []
   555     | dups => err ("Duplicate variables on lhs: " ^ commas_quote dups));
   556     (case gen_rems (op =) (map (#1 o #1) (typ_tvars rhs'), vs) of
   557       [] => []
   558     | extras => err ("Extra variables on rhs: " ^ commas_quote extras));
   559     types |> new_decl (a, Abbreviation (vs, rhs', syntactic types rhs'))
   560   end);
   561 
   562 in
   563 
   564 fun add_types ps = change_types (fold new_decl (ps |> map (fn (c, n) =>
   565   if n < 0 then err_neg_args c else (c, LogicalType n))));
   566 
   567 val add_abbrs = fold add_abbr;
   568 val add_nonterminals = change_types o fold new_decl o map (rpair Nonterminal);
   569 
   570 fun merge_types (types1, types2) =
   571   Symtab.merge Library.eq_snd (types1, types2) handle Symtab.DUPS (d :: _) =>
   572     err_in_decls d (the_decl types1 d) (the_decl types2 d);
   573 
   574 end;
   575 
   576 
   577 (* merge type signatures *)
   578 
   579 fun merge_tsigs pp (tsig1, tsig2) =
   580   let
   581     val (TSig {classes = classes1, default = default1, types = types1, arities = arities1,
   582       log_types = _, witness = _}) = tsig1;
   583     val (TSig {classes = classes2, default = default2, types = types2, arities = arities2,
   584       log_types = _, witness = _}) = tsig2;
   585 
   586     val classes' = merge_classes pp (classes1, classes2);
   587     val default' = Sorts.inter_sort classes' (default1, default2);
   588     val types' = merge_types (types1, types2);
   589     val arities' = merge_arities pp classes' (arities1, arities2);
   590   in build_tsig (classes', default', types', arities') end;
   591 
   592 end;