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