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