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