src/Pure/axclass.ML
author wenzelm
Thu Aug 14 16:52:46 2008 +0200 (2008-08-14 ago)
changeset 27865 27a8ad9612a3
parent 27691 ce171cbd4b93
child 28014 fe36718702aa
permissions -rw-r--r--
moved basic thm operations from structure PureThy to Thm (cf. more_thm.ML);
     1 (*  Title:      Pure/axclass.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 Type classes defined as predicates, associated with a record of
     6 parameters.
     7 *)
     8 
     9 signature AX_CLASS =
    10 sig
    11   val define_class: bstring * class list -> string list ->
    12     ((bstring * attribute list) * term list) list -> theory -> class * theory
    13   val add_classrel: thm -> theory -> theory
    14   val add_arity: thm -> theory -> theory
    15   val prove_classrel: class * class -> tactic -> theory -> theory
    16   val prove_arity: string * sort list * sort -> tactic -> theory -> theory
    17   val get_info: theory -> class ->
    18     {def: thm, intro: thm, axioms: thm list, params: (string * typ) list}
    19   val class_intros: theory -> thm list
    20   val class_of_param: theory -> string -> class option
    21   val cert_classrel: theory -> class * class -> class * class
    22   val read_classrel: theory -> xstring * xstring -> class * class
    23   val axiomatize_class: bstring * class list -> theory -> theory
    24   val axiomatize_class_cmd: bstring * xstring list -> theory -> theory
    25   val axiomatize_classrel: (class * class) list -> theory -> theory
    26   val axiomatize_classrel_cmd: (xstring * xstring) list -> theory -> theory
    27   val axiomatize_arity: arity -> theory -> theory
    28   val axiomatize_arity_cmd: xstring * string list * string -> theory -> theory
    29   val instance_name: string * class -> string
    30   val declare_overloaded: string * typ -> theory -> term * theory
    31   val define_overloaded: string -> string * term -> theory -> thm * theory
    32   val inst_tyco_of: theory -> string * typ -> string option
    33   val unoverload: theory -> thm -> thm
    34   val overload: theory -> thm -> thm
    35   val unoverload_conv: theory -> conv
    36   val overload_conv: theory -> conv
    37   val unoverload_const: theory -> string * typ -> string
    38   val param_of_inst: theory -> string * string -> string
    39   val inst_of_param: theory -> string -> (string * string) option
    40   val arity_property: theory -> class * string -> string -> string list
    41   type cache
    42   val of_sort: theory -> typ * sort -> cache -> thm list * cache  (*exception Sorts.CLASS_ERROR*)
    43   val cache: cache
    44   val introN: string
    45   val axiomsN: string
    46 end;
    47 
    48 structure AxClass: AX_CLASS =
    49 struct
    50 
    51 (** theory data **)
    52 
    53 (* class parameters (canonical order) *)
    54 
    55 type param = string * class;
    56 
    57 fun add_param pp ((x, c): param) params =
    58   (case AList.lookup (op =) params x of
    59     NONE => (x, c) :: params
    60   | SOME c' => error ("Duplicate class parameter " ^ quote x ^
    61       " for " ^ Pretty.string_of_sort pp [c] ^
    62       (if c = c' then "" else " and " ^ Pretty.string_of_sort pp [c'])));
    63 
    64 fun merge_params _ ([], qs) = qs
    65   | merge_params pp (ps, qs) =
    66       fold_rev (fn q => if member (op =) ps q then I else add_param pp q) qs ps;
    67 
    68 
    69 (* axclasses *)
    70 
    71 val introN = "intro";
    72 val superN = "super";
    73 val axiomsN = "axioms";
    74 
    75 datatype axclass = AxClass of
    76  {def: thm,
    77   intro: thm,
    78   axioms: thm list,
    79   params: (string * typ) list};
    80 
    81 type axclasses = axclass Symtab.table * param list;
    82 
    83 fun make_axclass ((def, intro, axioms), params) = AxClass
    84   {def = def, intro = intro, axioms = axioms, params = params};
    85 
    86 fun merge_axclasses pp ((tab1, params1), (tab2, params2)) : axclasses =
    87   (Symtab.merge (K true) (tab1, tab2), merge_params pp (params1, params2));
    88 
    89 
    90 (* instances *)
    91 
    92 val classrel_prefix = "classrel_";
    93 val arity_prefix = "arity_";
    94 
    95 type instances =
    96   ((class * class) * thm) list *
    97   ((class * sort list) * thm) list Symtab.table;
    98 
    99 fun merge_instances ((classrel1, arities1): instances, (classrel2, arities2)) =
   100  (merge (eq_fst op =) (classrel1, classrel2),
   101   Symtab.join (K (merge (eq_fst op =))) (arities1, arities2));
   102 
   103 
   104 (* instance parameters *)
   105 
   106 type inst_params =
   107   (string * thm) Symtab.table Symtab.table
   108     (*constant name ~> type constructor ~> (constant name, equation)*)
   109   * (string * string) Symtab.table; (*constant name ~> (constant name, type constructor)*)
   110 
   111 fun merge_inst_params ((const_param1, param_const1), (const_param2, param_const2)) =
   112   (Symtab.join  (K (Symtab.merge (K true))) (const_param1, const_param2),
   113     Symtab.merge (K true) (param_const1, param_const2));
   114 
   115 
   116 (* setup data *)
   117 
   118 structure AxClassData = TheoryDataFun
   119 (
   120   type T = axclasses * (instances * inst_params);
   121   val empty = ((Symtab.empty, []), (([], Symtab.empty), (Symtab.empty, Symtab.empty)));
   122   val copy = I;
   123   val extend = I;
   124   fun merge pp ((axclasses1, (instances1, inst_params1)), (axclasses2, (instances2, inst_params2))) =
   125     (merge_axclasses pp (axclasses1, axclasses2),
   126       (merge_instances (instances1, instances2), merge_inst_params (inst_params1, inst_params2)));
   127 );
   128 
   129 
   130 (* maintain axclasses *)
   131 
   132 val get_axclasses = #1 o AxClassData.get;
   133 val map_axclasses = AxClassData.map o apfst;
   134 
   135 val lookup_def = Symtab.lookup o #1 o get_axclasses;
   136 
   137 fun get_info thy c =
   138   (case lookup_def thy c of
   139     SOME (AxClass info) => info
   140   | NONE => error ("No such axclass: " ^ quote c));
   141 
   142 fun class_intros thy =
   143   let
   144     fun add_intro c =
   145       (case lookup_def thy c of SOME (AxClass {intro, ...}) => cons intro | _ => I);
   146     val classes = Sign.all_classes thy;
   147   in map (Thm.class_triv thy) classes @ fold add_intro classes [] end;
   148 
   149 
   150 fun get_params thy pred =
   151   let val params = #2 (get_axclasses thy);
   152   in fold (fn (x, c) => if pred c then cons x else I) params [] end;
   153 
   154 fun params_of thy c = get_params thy (fn c' => c' = c);
   155 fun all_params_of thy S = get_params thy (fn c => Sign.subsort thy (S, [c]));
   156 
   157 fun class_of_param thy = AList.lookup (op =) (#2 (get_axclasses thy));
   158 
   159 
   160 (* maintain instances *)
   161 
   162 fun instance_name (a, c) = NameSpace.base c ^ "_" ^ NameSpace.base a;
   163 
   164 val get_instances = #1 o #2 o AxClassData.get;
   165 val map_instances = AxClassData.map o apsnd o apfst;
   166 
   167 
   168 fun the_classrel thy (c1, c2) =
   169   (case AList.lookup (op =) (#1 (get_instances thy)) (c1, c2) of
   170     SOME th => Thm.transfer thy th
   171   | NONE => error ("Unproven class relation " ^
   172       Syntax.string_of_classrel (ProofContext.init thy) [c1, c2]));
   173 
   174 fun put_classrel arg = map_instances (fn (classrel, arities) =>
   175   (insert (eq_fst op =) arg classrel, arities));
   176 
   177 
   178 fun the_arity thy a (c, Ss) =
   179   (case AList.lookup (op =) (Symtab.lookup_list (#2 (get_instances thy)) a) (c, Ss) of
   180     SOME th => Thm.transfer thy th
   181   | NONE => error ("Unproven type arity " ^
   182       Syntax.string_of_arity (ProofContext.init thy) (a, Ss, [c])));
   183 
   184 fun arity_property thy (c, a) x =
   185   Symtab.lookup_list (snd (get_instances thy)) a
   186   |> map_filter (fn ((c', _), th) => if c = c'
   187       then AList.lookup (op =) (Thm.get_tags th) x else NONE)
   188   |> rev;
   189 
   190 fun insert_arity_completions thy (t, ((c, Ss), th)) arities =
   191   let
   192     val algebra = Sign.classes_of thy;
   193     val super_class_completions = Sign.super_classes thy c
   194       |> filter_out (fn c1 => exists (fn ((c2, Ss2), _) => c1 = c2
   195           andalso Sorts.sorts_le algebra (Ss2, Ss)) (Symtab.lookup_list arities t))
   196     val tags = Thm.get_tags th;
   197     val completions = map (fn c1 => (Sorts.weaken algebra
   198       (fn (th, c2) => fn c3 => th RS the_classrel thy (c2, c3)) (th, c) c1
   199         |> Thm.map_tags (K tags) |> Thm.close_derivation, c1)) super_class_completions;
   200     val arities' = fold (fn (th1, c1) => Symtab.cons_list (t, ((c1, Ss), th1)))
   201       completions arities;
   202   in (completions, arities') end;
   203 
   204 fun put_arity ((t, Ss, c), th) thy =
   205   let
   206     val th' = (Thm.map_tags o AList.default (op =))
   207       (Markup.theory_nameN, Context.theory_name thy) th;
   208     val arity' = (t, ((c, Ss), th'));
   209   in
   210     thy
   211     |> map_instances (fn (classrel, arities) => (classrel,
   212       arities
   213       |> Symtab.insert_list (eq_fst op =) arity'
   214       |> insert_arity_completions thy arity'
   215       |> snd))
   216   end;
   217 
   218 fun complete_arities thy = 
   219   let
   220     val arities = snd (get_instances thy);
   221     val (completions, arities') = arities
   222       |> fold_map (insert_arity_completions thy) (Symtab.dest_list arities)
   223       |>> flat;
   224   in if null completions
   225     then NONE
   226     else SOME (thy |> map_instances (fn (classrel, _) => (classrel, arities')))
   227   end;
   228 
   229 val _ = Context.>> (Context.map_theory (Theory.at_begin complete_arities));
   230 
   231 
   232 (* maintain instance parameters *)
   233 
   234 val get_inst_params = #2 o #2 o AxClassData.get;
   235 val map_inst_params = AxClassData.map o apsnd o apsnd;
   236 
   237 fun get_inst_param thy (c, tyco) =
   238   (the o Symtab.lookup ((the o Symtab.lookup (fst (get_inst_params thy))) c)) tyco;
   239 
   240 fun add_inst_param (c, tyco) inst = (map_inst_params o apfst
   241       o Symtab.map_default (c, Symtab.empty)) (Symtab.update_new (tyco, inst))
   242   #> (map_inst_params o apsnd) (Symtab.update_new (fst inst, (c, tyco)));
   243 
   244 val inst_of_param = Symtab.lookup o snd o get_inst_params;
   245 val param_of_inst = fst oo get_inst_param;
   246 
   247 fun inst_thms thy = (Symtab.fold (Symtab.fold (cons o snd o snd) o snd) o fst)
   248   (get_inst_params thy) [];
   249 
   250 fun inst_tyco_of thy = try (fst o dest_Type o the_single o Sign.const_typargs thy);
   251 
   252 fun unoverload thy = MetaSimplifier.simplify true (inst_thms thy);
   253 fun overload thy = MetaSimplifier.simplify true (map Thm.symmetric (inst_thms thy));
   254 
   255 fun unoverload_conv thy = MetaSimplifier.rewrite true (inst_thms thy);
   256 fun overload_conv thy = MetaSimplifier.rewrite true (map Thm.symmetric (inst_thms thy));
   257 
   258 fun unoverload_const thy (c_ty as (c, _)) =
   259   case class_of_param thy c
   260    of SOME class => (case inst_tyco_of thy c_ty
   261        of SOME tyco => try (param_of_inst thy) (c, tyco) |> the_default c
   262         | NONE => c)
   263     | NONE => c;
   264 
   265 
   266 (** instances **)
   267 
   268 (* class relations *)
   269 
   270 fun cert_classrel thy raw_rel =
   271   let
   272     val string_of_sort = Syntax.string_of_sort_global thy;
   273     val (c1, c2) = pairself (Sign.certify_class thy) raw_rel;
   274     val _ = Sign.primitive_classrel (c1, c2) (Theory.copy thy);
   275     val _ =
   276       (case subtract (op =) (all_params_of thy [c1]) (all_params_of thy [c2]) of
   277         [] => ()
   278       | xs => raise TYPE ("Class " ^ string_of_sort [c1] ^ " lacks parameter(s) " ^
   279           commas_quote xs ^ " of " ^ string_of_sort [c2], [], []));
   280   in (c1, c2) end;
   281 
   282 fun read_classrel thy raw_rel =
   283   cert_classrel thy (pairself (Sign.read_class thy) raw_rel)
   284     handle TYPE (msg, _, _) => error msg;
   285 
   286 
   287 (* primitive rules *)
   288 
   289 fun add_classrel th thy =
   290   let
   291     fun err () = raise THM ("add_classrel: malformed class relation", 0, [th]);
   292     val prop = Thm.plain_prop_of (Thm.transfer thy th);
   293     val rel = Logic.dest_classrel prop handle TERM _ => err ();
   294     val (c1, c2) = cert_classrel thy rel handle TYPE _ => err ();
   295   in
   296     thy
   297     |> Sign.primitive_classrel (c1, c2)
   298     |> put_classrel ((c1, c2), Drule.unconstrainTs th)
   299   end;
   300 
   301 fun add_arity th thy =
   302   let
   303     fun err () = raise THM ("add_arity: malformed type arity", 0, [th]);
   304     val prop = Thm.plain_prop_of (Thm.transfer thy th);
   305     val (t, Ss, c) = Logic.dest_arity prop handle TERM _ => err ();
   306     val _ = map (Sign.certify_sort thy) Ss = Ss orelse err ();
   307     val _ = case filter_out (fn c => can (get_inst_param thy) (c, t)) (params_of thy c)
   308      of [] => ()
   309       | cs => Output.legacy_feature
   310           ("Missing specifications for overloaded parameters " ^ commas_quote cs)
   311     val th' = Drule.unconstrainTs th;
   312   in
   313     thy
   314     |> Sign.primitive_arity (t, Ss, [c])
   315     |> put_arity ((t, Ss, c), th')
   316   end;
   317 
   318 
   319 (* tactical proofs *)
   320 
   321 fun prove_classrel raw_rel tac thy =
   322   let
   323     val ctxt = ProofContext.init thy;
   324     val (c1, c2) = cert_classrel thy raw_rel;
   325     val th = Goal.prove ctxt [] []
   326         (Logic.mk_classrel (c1, c2)) (fn _ => tac) handle ERROR msg =>
   327       cat_error msg ("The error(s) above occurred while trying to prove class relation " ^
   328         quote (Syntax.string_of_classrel ctxt [c1, c2]));
   329   in
   330     thy
   331     |> PureThy.add_thms [((prefix classrel_prefix (Logic.name_classrel (c1, c2)), th), [])]
   332     |-> (fn [th'] => add_classrel th')
   333   end;
   334 
   335 fun prove_arity raw_arity tac thy =
   336   let
   337     val ctxt = ProofContext.init thy;
   338     val arity = Sign.cert_arity thy raw_arity;
   339     val names = map (prefix arity_prefix) (Logic.name_arities arity);
   340     val props = Logic.mk_arities arity;
   341     val ths = Goal.prove_multi ctxt [] [] props
   342       (fn _ => Goal.precise_conjunction_tac (length props) 1 THEN tac) handle ERROR msg =>
   343         cat_error msg ("The error(s) above occurred while trying to prove type arity " ^
   344           quote (Syntax.string_of_arity ctxt arity));
   345   in
   346     thy
   347     |> PureThy.add_thms (map (rpair []) (names ~~ ths))
   348     |-> fold add_arity
   349   end;
   350 
   351 
   352 (* instance parameters and overloaded definitions *)
   353 
   354 (* declaration and definition of instances of overloaded constants *)
   355 
   356 fun declare_overloaded (c, T) thy =
   357   let
   358     val class = case class_of_param thy c
   359      of SOME class => class
   360       | NONE => error ("Not a class parameter: " ^ quote c);
   361     val tyco = case inst_tyco_of thy (c, T)
   362      of SOME tyco => tyco
   363       | NONE => error ("Illegal type for instantiation of class parameter: "
   364         ^ quote (c ^ " :: " ^ Syntax.string_of_typ_global thy T));
   365     val name_inst = instance_name (tyco, class) ^ "_inst";
   366     val c' = NameSpace.base c ^ "_" ^ NameSpace.base tyco;
   367     val T' = Type.strip_sorts T;
   368   in
   369     thy
   370     |> Sign.sticky_prefix name_inst
   371     |> Sign.no_base_names
   372     |> Sign.declare_const [] (c', T', NoSyn)
   373     |-> (fn const' as Const (c'', _) => Thm.add_def false true
   374           (Thm.def_name c', Logic.mk_equals (Const (c, T'), const'))
   375     #>> Thm.varifyT
   376     #-> (fn thm => add_inst_param (c, tyco) (c'', thm)
   377     #> PureThy.add_thm ((c', thm), [Thm.kind_internal])
   378     #> snd
   379     #> Sign.restore_naming thy
   380     #> pair (Const (c, T))))
   381   end;
   382 
   383 fun define_overloaded name (c, t) thy =
   384   let
   385     val T = Term.fastype_of t;
   386     val SOME tyco = inst_tyco_of thy (c, T);
   387     val (c', eq) = get_inst_param thy (c, tyco);
   388     val prop = Logic.mk_equals (Const (c', T), t);
   389     val name' = Thm.def_name_optional
   390       (NameSpace.base c ^ "_" ^ NameSpace.base tyco) name;
   391   in
   392     thy
   393     |> Thm.add_def false false (name', prop)
   394     |>> (fn thm =>  Drule.transitive_thm OF [eq, thm])
   395   end;
   396 
   397 
   398 
   399 (** class definitions **)
   400 
   401 fun split_defined n eq =
   402   let
   403     val intro =
   404       (eq RS Drule.equal_elim_rule2)
   405       |> Conjunction.curry_balanced n
   406       |> n = 0 ? Thm.eq_assumption 1;
   407     val dests =
   408       if n = 0 then []
   409       else
   410         (eq RS Drule.equal_elim_rule1)
   411         |> BalancedTree.dest (fn th =>
   412           (th RS Conjunction.conjunctionD1, th RS Conjunction.conjunctionD2)) n;
   413   in (intro, dests) end;
   414 
   415 fun define_class (bclass, raw_super) raw_params raw_specs thy =
   416   let
   417     val ctxt = ProofContext.init thy;
   418     val pp = Syntax.pp ctxt;
   419 
   420 
   421     (* class *)
   422 
   423     val bconst = Logic.const_of_class bclass;
   424     val class = Sign.full_name thy bclass;
   425     val super = Sign.minimize_sort thy (Sign.certify_sort thy raw_super);
   426 
   427     fun check_constraint (a, S) =
   428       if Sign.subsort thy (super, S) then ()
   429       else error ("Sort constraint of type variable " ^
   430         setmp show_sorts true (Pretty.string_of_typ pp) (TFree (a, S)) ^
   431         " needs to be weaker than " ^ Pretty.string_of_sort pp super);
   432 
   433 
   434     (* params *)
   435 
   436     val params = raw_params |> map (fn p =>
   437       let
   438         val T = Sign.the_const_type thy p;
   439         val _ =
   440           (case Term.add_tvarsT T [] of
   441             [((a, _), S)] => check_constraint (a, S)
   442           | _ => error ("Exactly one type variable expected in class parameter " ^ quote p));
   443         val T' = Term.map_type_tvar (fn _ => TFree (Name.aT, [class])) T;
   444       in (p, T') end);
   445 
   446 
   447     (* axioms *)
   448 
   449     fun prep_axiom t =
   450       (case Term.add_tfrees t [] of
   451         [(a, S)] => check_constraint (a, S)
   452       | [] => ()
   453       | _ => error ("Multiple type variables in class axiom:\n" ^ Pretty.string_of_term pp t);
   454       t
   455       |> Term.map_types (Term.map_atyps (fn TFree _ => Term.aT [] | U => U))
   456       |> Logic.close_form);
   457 
   458     val axiomss = map (map (prep_axiom o Sign.cert_prop thy) o snd) raw_specs;
   459     val name_atts = map fst raw_specs;
   460 
   461 
   462     (* definition *)
   463 
   464     val conjs = map (curry Logic.mk_inclass (Term.aT [])) super @ flat axiomss;
   465     val class_eq =
   466       Logic.mk_equals (Logic.mk_inclass (Term.aT [], class), Logic.mk_conjunction_balanced conjs);
   467 
   468     val ([def], def_thy) =
   469       thy
   470       |> Sign.primitive_class (bclass, super)
   471       |> PureThy.add_defs false [((Thm.def_name bconst, class_eq), [])];
   472     val (raw_intro, (raw_classrel, raw_axioms)) =
   473       split_defined (length conjs) def ||> chop (length super);
   474 
   475 
   476     (* facts *)
   477 
   478     val class_triv = Thm.class_triv def_thy class;
   479     val ([(_, [intro]), (_, classrel), (_, axioms)], facts_thy) =
   480       def_thy
   481       |> Sign.add_path bconst
   482       |> Sign.no_base_names
   483       |> PureThy.note_thmss ""
   484         [((introN, []), [([Drule.standard raw_intro], [])]),
   485          ((superN, []), [(map Drule.standard raw_classrel, [])]),
   486          ((axiomsN, []), [(map (fn th => Drule.standard (class_triv RS th)) raw_axioms, [])])]
   487       ||> Sign.restore_naming def_thy;
   488 
   489 
   490     (* result *)
   491 
   492     val axclass = make_axclass ((def, intro, axioms), params);
   493     val result_thy =
   494       facts_thy
   495       |> fold put_classrel (map (pair class) super ~~ classrel)
   496       |> Sign.add_path bconst
   497       |> PureThy.note_thmss "" (name_atts ~~ map Thm.simple_fact (unflat axiomss axioms)) |> snd
   498       |> Sign.restore_naming facts_thy
   499       |> map_axclasses (fn (axclasses, parameters) =>
   500         (Symtab.update (class, axclass) axclasses,
   501           fold (fn (x, _) => add_param pp (x, class)) params parameters));
   502 
   503   in (class, result_thy) end;
   504 
   505 
   506 
   507 (** axiomatizations **)
   508 
   509 local
   510 
   511 fun axiomatize prep mk name add raw_args thy =
   512   let
   513     val args = prep thy raw_args;
   514     val specs = mk args;
   515     val names = name args;
   516   in thy |> PureThy.add_axioms (map (rpair []) (names ~~ specs)) |-> fold add end;
   517 
   518 fun ax_classrel prep =
   519   axiomatize (map o prep) (map Logic.mk_classrel)
   520     (map (prefix classrel_prefix o Logic.name_classrel)) add_classrel;
   521 
   522 fun ax_arity prep =
   523   axiomatize prep Logic.mk_arities
   524     (map (prefix arity_prefix) o Logic.name_arities) add_arity;
   525 
   526 fun class_const c =
   527   (Logic.const_of_class c, Term.itselfT (Term.aT []) --> propT);
   528 
   529 fun ax_class prep_class prep_classrel (bclass, raw_super) thy =
   530   let
   531     val class = Sign.full_name thy bclass;
   532     val super = map (prep_class thy) raw_super |> Sign.minimize_sort thy;
   533   in
   534     thy
   535     |> Sign.primitive_class (bclass, super)
   536     |> ax_classrel prep_classrel (map (fn c => (class, c)) super)
   537     |> Theory.add_deps "" (class_const class) (map class_const super)
   538   end;
   539 
   540 in
   541 
   542 val axiomatize_class = ax_class Sign.certify_class cert_classrel;
   543 val axiomatize_class_cmd = ax_class Sign.read_class read_classrel;
   544 val axiomatize_classrel = ax_classrel cert_classrel;
   545 val axiomatize_classrel_cmd = ax_classrel read_classrel;
   546 val axiomatize_arity = ax_arity Sign.cert_arity;
   547 val axiomatize_arity_cmd = ax_arity Sign.read_arity;
   548 
   549 end;
   550 
   551 
   552 
   553 (** explicit derivations -- cached **)
   554 
   555 datatype cache = Types of (class * thm) list Typtab.table;
   556 
   557 local
   558 
   559 fun lookup_type (Types cache) = AList.lookup (op =) o Typtab.lookup_list cache;
   560 fun insert_type T der (Types cache) = Types (Typtab.insert_list (eq_fst op =) (T, der) cache);
   561 
   562 fun derive_type _ (_, []) = []
   563   | derive_type thy (typ, sort) =
   564       let
   565         val vars = Term.fold_atyps
   566             (fn T as TFree (_, S) => insert (eq_fst op =) (T, S)
   567               | T as TVar (_, S) => insert (eq_fst op =) (T, S)
   568               | _ => I) typ [];
   569         val hyps = vars
   570           |> map (fn (T, S) => (T, Drule.sort_triv thy (T, S) ~~ S));
   571         val ths = (typ, sort)
   572           |> Sorts.of_sort_derivation (Syntax.pp_global thy) (Sign.classes_of thy)
   573            {class_relation =
   574               fn (th, c1) => fn c2 => th RS the_classrel thy (c1, c2),
   575             type_constructor =
   576               fn a => fn dom => fn c =>
   577                 let val Ss = map (map snd) dom and ths = maps (map fst) dom
   578                 in ths MRS the_arity thy a (c, Ss) end,
   579             type_variable =
   580               the_default [] o AList.lookup (op =) hyps};
   581       in ths end;
   582 
   583 in
   584 
   585 fun of_sort thy (typ, sort) cache =
   586   let
   587     val sort' = filter (is_none o lookup_type cache typ) sort;
   588     val ths' = derive_type thy (typ, sort')
   589       handle ERROR msg => cat_error msg ("The error(s) above occurred for sort derivation: " ^
   590         Syntax.string_of_typ_global thy typ ^ " :: " ^ Syntax.string_of_sort_global thy sort');
   591     val cache' = cache |> fold (insert_type typ) (sort' ~~ ths');
   592     val ths =
   593       sort |> map (fn c =>
   594         Goal.finish (the (lookup_type cache' typ c) RS
   595           Goal.init (Thm.cterm_of thy (Logic.mk_inclass (typ, c))))
   596         |> Thm.adjust_maxidx_thm ~1);
   597   in (ths, cache') end;
   598 
   599 end;
   600 
   601 val cache = Types Typtab.empty;
   602 
   603 end;