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