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