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