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