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