src/Pure/Isar/class_target.ML
author haftmann
Wed Jan 21 16:47:03 2009 +0100 (2009-01-21)
changeset 29577 08f783c5fcf0
parent 29558 9846af6c6d6a
child 29610 83d282f12352
permissions -rw-r--r--
code cleanup
     1 (*  Title:      Pure/Isar/class_target.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Type classes derived from primitive axclasses and locales - mechanisms.
     5 *)
     6 
     7 signature CLASS_TARGET =
     8 sig
     9   (*classes*)
    10   val register: class -> class list -> ((string * typ) * (string * typ)) list
    11     -> sort -> morphism -> thm option -> thm option -> thm
    12     -> theory -> theory
    13   val register_subclass: class * class -> morphism option -> Element.witness option
    14     -> morphism -> theory -> theory
    15 
    16   val is_class: theory -> class -> bool
    17   val base_sort: theory -> class -> sort
    18   val rules: theory -> class -> thm option * thm
    19   val these_params: theory -> sort -> (string * (class * (string * typ))) list
    20   val these_defs: theory -> sort -> thm list
    21   val these_operations: theory -> sort -> (string * (class * (typ * term))) list
    22   val print_classes: theory -> unit
    23 
    24   val begin: class list -> sort -> Proof.context -> Proof.context
    25   val init: class -> theory -> Proof.context
    26   val declare: class -> Properties.T
    27     -> (string * mixfix) * term -> theory -> theory
    28   val abbrev: class -> Syntax.mode -> Properties.T
    29     -> (string * mixfix) * term -> theory -> theory
    30   val class_prefix: string -> string
    31   val refresh_syntax: class -> Proof.context -> Proof.context
    32 
    33   (*instances*)
    34   val init_instantiation: string list * (string * sort) list * sort
    35     -> theory -> local_theory
    36   val instantiation_instance: (local_theory -> local_theory)
    37     -> local_theory -> Proof.state
    38   val prove_instantiation_instance: (Proof.context -> tactic)
    39     -> local_theory -> local_theory
    40   val prove_instantiation_exit: (Proof.context -> tactic)
    41     -> local_theory -> theory
    42   val prove_instantiation_exit_result: (morphism -> 'a -> 'b)
    43     -> (Proof.context -> 'b -> tactic) -> 'a -> local_theory -> 'b * theory
    44   val conclude_instantiation: local_theory -> local_theory
    45   val instantiation_param: local_theory -> string -> string option
    46   val confirm_declaration: string -> local_theory -> local_theory
    47   val pretty_instantiation: local_theory -> Pretty.T
    48   val type_name: string -> string
    49 
    50   val intro_classes_tac: thm list -> tactic
    51   val default_intro_tac: Proof.context -> thm list -> tactic
    52 
    53   (*old axclass layer*)
    54   val axclass_cmd: bstring * xstring list
    55     -> (Attrib.binding * string list) list
    56     -> theory -> class * theory
    57   val classrel_cmd: xstring * xstring -> theory -> Proof.state
    58 
    59   (*old instance layer*)
    60   val instance_arity: (theory -> theory) -> arity -> theory -> Proof.state
    61   val instance_arity_cmd: bstring * xstring list * xstring -> theory -> Proof.state
    62 end;
    63 
    64 structure Class_Target : CLASS_TARGET =
    65 struct
    66 
    67 (** primitive axclass and instance commands **)
    68 
    69 fun axclass_cmd (class, raw_superclasses) raw_specs thy =
    70   let
    71     val ctxt = ProofContext.init thy;
    72     val superclasses = map (Sign.read_class thy) raw_superclasses;
    73     val name_atts = map ((apsnd o map) (Attrib.attribute thy) o fst)
    74       raw_specs;
    75     val axiomss = ProofContext.read_propp (ctxt, map (map (rpair []) o snd)
    76           raw_specs)
    77       |> snd
    78       |> (map o map) fst;
    79   in
    80     AxClass.define_class (class, superclasses) []
    81       (name_atts ~~ axiomss) thy
    82   end;
    83 
    84 local
    85 
    86 fun gen_instance mk_prop add_thm after_qed insts thy =
    87   let
    88     fun after_qed' results =
    89       ProofContext.theory ((fold o fold) add_thm results #> after_qed);
    90   in
    91     thy
    92     |> ProofContext.init
    93     |> Proof.theorem_i NONE after_qed' ((map (fn t => [(t, [])])
    94         o mk_prop thy) insts)
    95   end;
    96 
    97 in
    98 
    99 val instance_arity =
   100   gen_instance (Logic.mk_arities oo Sign.cert_arity) AxClass.add_arity;
   101 val instance_arity_cmd =
   102   gen_instance (Logic.mk_arities oo Sign.read_arity) AxClass.add_arity I;
   103 val classrel =
   104   gen_instance (single oo (Logic.mk_classrel oo AxClass.cert_classrel)) AxClass.add_classrel I;
   105 val classrel_cmd =
   106   gen_instance (single oo (Logic.mk_classrel oo AxClass.read_classrel)) AxClass.add_classrel I;
   107 
   108 end; (*local*)
   109 
   110 
   111 (** class data **)
   112 
   113 datatype class_data = ClassData of {
   114 
   115   (* static part *)
   116   consts: (string * string) list
   117     (*locale parameter ~> constant name*),
   118   base_sort: sort,
   119   base_morph: morphism
   120     (*static part of canonical morphism*),
   121   assm_intro: thm option,
   122   of_class: thm,
   123   axiom: thm option,
   124   
   125   (* dynamic part *)
   126   defs: thm list,
   127   operations: (string * (class * (typ * term))) list
   128 
   129 };
   130 
   131 fun rep_class_data (ClassData data) = data;
   132 fun mk_class_data ((consts, base_sort, base_morph, assm_intro, of_class, axiom),
   133     (defs, operations)) =
   134   ClassData { consts = consts, base_sort = base_sort,
   135     base_morph = base_morph, assm_intro = assm_intro, of_class = of_class, axiom = axiom,
   136     defs = defs, operations = operations };
   137 fun map_class_data f (ClassData { consts, base_sort, base_morph, assm_intro,
   138     of_class, axiom, defs, operations }) =
   139   mk_class_data (f ((consts, base_sort, base_morph, assm_intro, of_class, axiom),
   140     (defs, operations)));
   141 fun merge_class_data _ (ClassData { consts = consts,
   142     base_sort = base_sort, base_morph = base_morph, assm_intro = assm_intro,
   143     of_class = of_class, axiom = axiom, defs = defs1, operations = operations1 },
   144   ClassData { consts = _, base_sort = _, base_morph = _, assm_intro = _,
   145     of_class = _, axiom = _, defs = defs2, operations = operations2 }) =
   146   mk_class_data ((consts, base_sort, base_morph, assm_intro, of_class, axiom),
   147     (Thm.merge_thms (defs1, defs2),
   148       AList.merge (op =) (K true) (operations1, operations2)));
   149 
   150 structure ClassData = TheoryDataFun
   151 (
   152   type T = class_data Graph.T
   153   val empty = Graph.empty;
   154   val copy = I;
   155   val extend = I;
   156   fun merge _ = Graph.join merge_class_data;
   157 );
   158 
   159 
   160 (* queries *)
   161 
   162 val lookup_class_data = Option.map rep_class_data oo try o Graph.get_node o ClassData.get;
   163 
   164 fun the_class_data thy class = case lookup_class_data thy class
   165  of NONE => error ("Undeclared class " ^ quote class)
   166   | SOME data => data;
   167 
   168 val is_class = is_some oo lookup_class_data;
   169 
   170 val ancestry = Graph.all_succs o ClassData.get;
   171 val heritage = Graph.all_preds o ClassData.get;
   172 
   173 fun these_params thy =
   174   let
   175     fun params class =
   176       let
   177         val const_typs = (#params o AxClass.get_info thy) class;
   178         val const_names = (#consts o the_class_data thy) class;
   179       in
   180         (map o apsnd)
   181           (fn c => (class, (c, (the o AList.lookup (op =) const_typs) c))) const_names
   182       end;
   183   in maps params o ancestry thy end;
   184 
   185 val base_sort = #base_sort oo the_class_data;
   186 
   187 fun rules thy class =
   188   let val { axiom, of_class, ... } = the_class_data thy class
   189   in (axiom, of_class) end;
   190 
   191 fun all_assm_intros thy =
   192   Graph.fold (fn (_, (data, _)) => fold (insert Thm.eq_thm)
   193     ((the_list o #assm_intro o rep_class_data) data)) (ClassData.get thy) [];
   194 
   195 fun these_defs thy = maps (#defs o the_class_data thy) o ancestry thy;
   196 fun these_operations thy = maps (#operations o the_class_data thy) o ancestry thy;
   197 
   198 val base_morphism = #base_morph oo the_class_data;
   199 fun morphism thy class = base_morphism thy class
   200   $> Element.eq_morphism thy (these_defs thy [class]);
   201 
   202 fun print_classes thy =
   203   let
   204     val ctxt = ProofContext.init thy;
   205     val algebra = Sign.classes_of thy;
   206     val arities =
   207       Symtab.empty
   208       |> Symtab.fold (fn (tyco, arities) => fold (fn (class, _) =>
   209            Symtab.map_default (class, []) (insert (op =) tyco)) arities)
   210              ((#arities o Sorts.rep_algebra) algebra);
   211     val the_arities = these o Symtab.lookup arities;
   212     fun mk_arity class tyco =
   213       let
   214         val Ss = Sorts.mg_domain algebra tyco [class];
   215       in Syntax.pretty_arity ctxt (tyco, Ss, [class]) end;
   216     fun mk_param (c, ty) = Pretty.str (Sign.extern_const thy c ^ " :: "
   217       ^ setmp show_sorts false (Syntax.string_of_typ ctxt o Type.strip_sorts) ty);
   218     fun mk_entry class = (Pretty.block o Pretty.fbreaks o map_filter I) [
   219       (SOME o Pretty.str) ("class " ^ Sign.extern_class thy class ^ ":"),
   220       (SOME o Pretty.block) [Pretty.str "supersort: ",
   221         (Syntax.pretty_sort ctxt o Sign.minimize_sort thy o Sign.super_classes thy) class],
   222       ((fn [] => NONE | ps => (SOME o Pretty.block o Pretty.fbreaks)
   223           (Pretty.str "parameters:" :: ps)) o map mk_param
   224         o these o Option.map #params o try (AxClass.get_info thy)) class,
   225       (SOME o Pretty.block o Pretty.breaks) [
   226         Pretty.str "instances:",
   227         Pretty.list "" "" (map (mk_arity class) (the_arities class))
   228       ]
   229     ]
   230   in
   231     (Pretty.writeln o Pretty.chunks o separate (Pretty.str "")
   232       o map mk_entry o Sorts.all_classes) algebra
   233   end;
   234 
   235 
   236 (* updaters *)
   237 
   238 fun register class sups params base_sort morph
   239     axiom assm_intro of_class thy =
   240   let
   241     val operations = map (fn (v_ty as (_, ty), (c, _)) =>
   242       (c, (class, (ty, Free v_ty)))) params;
   243     val add_class = Graph.new_node (class,
   244         mk_class_data (((map o pairself) fst params, base_sort,
   245           morph, assm_intro, of_class, axiom), ([], operations)))
   246       #> fold (curry Graph.add_edge class) sups;
   247   in ClassData.map add_class thy end;
   248 
   249 fun activate_defs class thms thy =
   250   let
   251     val eq_morph = Element.eq_morphism thy thms;
   252     fun amend cls thy = Locale.amend_registration eq_morph
   253       (cls, morphism thy cls) thy;
   254   in fold amend (heritage thy [class]) thy end;
   255 
   256 fun register_operation class (c, (t, some_def)) thy =
   257   let
   258     val base_sort = base_sort thy class;
   259     val prep_typ = map_type_tfree
   260       (fn (v, sort) => if Name.aT = v
   261         then TFree (v, base_sort) else TVar ((v, 0), sort));
   262     val t' = map_types prep_typ t;
   263     val ty' = Term.fastype_of t';
   264   in
   265     thy
   266     |> (ClassData.map o Graph.map_node class o map_class_data o apsnd)
   267       (fn (defs, operations) =>
   268         (fold cons (the_list some_def) defs,
   269           (c, (class, (ty', t'))) :: operations))
   270     |> is_some some_def ? activate_defs class (the_list some_def)
   271   end;
   272 
   273 fun register_subclass (sub, sup) some_dep_morph some_wit export thy =
   274   let
   275     val intros = (snd o rules thy) sup :: map_filter I
   276       [Option.map (Drule.standard' o Element.conclude_witness) some_wit,
   277         (fst o rules thy) sub];
   278     val tac = ALLGOALS (EVERY' (map Tactic.rtac intros));
   279     val classrel = Goal.prove_global thy [] [] (Logic.mk_classrel (sub, sup))
   280       (K tac);
   281     val diff_sort = Sign.complete_sort thy [sup]
   282       |> subtract (op =) (Sign.complete_sort thy [sub]);
   283   in
   284     thy
   285     |> AxClass.add_classrel classrel
   286     |> ClassData.map (Graph.add_edge (sub, sup))
   287     |> activate_defs sub (these_defs thy diff_sort)
   288     |> fold2 (fn dep_morph => fn wit => Locale.add_dependency sub (sup,
   289         dep_morph $> Element.satisfy_morphism [wit] $> export))
   290           (the_list some_dep_morph) (the_list some_wit)
   291     |> (fn thy => fold_rev Locale.activate_global_facts
   292       (Locale.get_registrations thy) thy)
   293   end;
   294 
   295 
   296 (** classes and class target **)
   297 
   298 (* class context syntax *)
   299 
   300 fun these_unchecks thy =
   301   map (fn (c, (_, (ty, t))) => (t, Const (c, ty))) o these_operations thy;
   302 
   303 fun synchronize_class_syntax sort base_sort ctxt =
   304   let
   305     val thy = ProofContext.theory_of ctxt;
   306     val algebra = Sign.classes_of thy;
   307     val operations = these_operations thy sort;
   308     fun subst_class_typ sort = map_type_tfree (K (TVar ((Name.aT, 0), sort)));
   309     val primary_constraints =
   310       (map o apsnd) (subst_class_typ base_sort o fst o snd) operations;
   311     val secondary_constraints =
   312       (map o apsnd) (fn (class, (ty, _)) => subst_class_typ [class] ty) operations;
   313     fun declare_const (c, _) =
   314       let val b = Sign.base_name c
   315       in Sign.intern_const thy b = c ? Variable.declare_const (b, c) end;
   316     fun improve (c, ty) = (case AList.lookup (op =) primary_constraints c
   317      of SOME ty' => (case try (Type.raw_match (ty', ty)) Vartab.empty
   318          of SOME tyenv => (case Vartab.lookup tyenv (Name.aT, 0)
   319              of SOME (_, ty' as TVar (tvar as (vi, sort))) =>
   320                   if TypeInfer.is_param vi
   321                     andalso Sorts.sort_le algebra (base_sort, sort)
   322                       then SOME (ty', TFree (Name.aT, base_sort))
   323                       else NONE
   324               | _ => NONE)
   325           | NONE => NONE)
   326       | NONE => NONE)
   327     fun subst (c, ty) = Option.map snd (AList.lookup (op =) operations c);
   328     val unchecks = these_unchecks thy sort;
   329   in
   330     ctxt
   331     |> fold declare_const primary_constraints
   332     |> Overloading.map_improvable_syntax (K (((primary_constraints, secondary_constraints),
   333         (((improve, subst), true), unchecks)), false))
   334     |> Overloading.set_primary_constraints
   335   end;
   336 
   337 fun refresh_syntax class ctxt =
   338   let
   339     val thy = ProofContext.theory_of ctxt;
   340     val base_sort = base_sort thy class;
   341   in synchronize_class_syntax [class] base_sort ctxt end;
   342 
   343 fun begin sort base_sort ctxt =
   344   ctxt
   345   |> Variable.declare_term
   346       (Logic.mk_type (TFree (Name.aT, base_sort)))
   347   |> synchronize_class_syntax sort base_sort
   348   |> Overloading.add_improvable_syntax;
   349 
   350 fun init class thy =
   351   thy
   352   |> Locale.init class
   353   |> begin [class] (base_sort thy class);
   354 
   355 
   356 (* class target *)
   357 
   358 val class_prefix = Logic.const_of_class o Sign.base_name;
   359 
   360 fun declare class pos ((c, mx), dict) thy =
   361   let
   362     val morph = morphism thy class;
   363     val b = Morphism.binding morph (Binding.name c);
   364     val b_def = Morphism.binding morph (Binding.name (c ^ "_dict"));
   365     val c' = Sign.full_name thy b;
   366     val dict' = Morphism.term morph dict;
   367     val ty' = Term.fastype_of dict';
   368     val def_eq = Logic.mk_equals (Const (c', ty'), dict')
   369       |> map_types Type.strip_sorts;
   370   in
   371     thy
   372     |> Sign.declare_const pos ((b, Type.strip_sorts ty'), mx)
   373     |> snd
   374     |> Thm.add_def false false (b_def, def_eq)
   375     |>> Thm.varifyT
   376     |-> (fn def_thm => PureThy.store_thm (b_def, def_thm)
   377       #> snd
   378       #> register_operation class (c', (dict', SOME (Thm.symmetric def_thm))))
   379     |> Sign.add_const_constraint (c', SOME ty')
   380   end;
   381 
   382 fun abbrev class prmode pos ((c, mx), rhs) thy =
   383   let
   384     val morph = morphism thy class;
   385     val unchecks = these_unchecks thy [class];
   386     val b = Morphism.binding morph (Binding.name c);
   387     val c' = Sign.full_name thy b;
   388     val rhs' = Pattern.rewrite_term thy unchecks [] rhs;
   389     val ty' = Term.fastype_of rhs';
   390     val rhs'' = map_types ((*Type.strip_sorts o *)Logic.varifyT) rhs';
   391   in
   392     thy
   393     |> Sign.add_abbrev (#1 prmode) pos (b, rhs'')
   394     |> snd
   395     |> Sign.add_const_constraint (c', SOME ty')
   396     |> Sign.notation true prmode [(Const (c', ty'), mx)]
   397     |> not (#1 prmode = PrintMode.input) ? register_operation class (c', (rhs', NONE))
   398   end;
   399 
   400 
   401 (** instantiation target **)
   402 
   403 (* bookkeeping *)
   404 
   405 datatype instantiation = Instantiation of {
   406   arities: string list * (string * sort) list * sort,
   407   params: ((string * string) * (string * typ)) list
   408     (*(instantiation parameter, type constructor), (local instantiation parameter, typ)*)
   409 }
   410 
   411 structure Instantiation = ProofDataFun
   412 (
   413   type T = instantiation
   414   fun init _ = Instantiation { arities = ([], [], []), params = [] };
   415 );
   416 
   417 fun mk_instantiation (arities, params) =
   418   Instantiation { arities = arities, params = params };
   419 fun get_instantiation lthy = case Instantiation.get (LocalTheory.target_of lthy)
   420  of Instantiation data => data;
   421 fun map_instantiation f = (LocalTheory.target o Instantiation.map)
   422   (fn Instantiation { arities, params } => mk_instantiation (f (arities, params)));
   423 
   424 fun the_instantiation lthy = case get_instantiation lthy
   425  of { arities = ([], [], []), ... } => error "No instantiation target"
   426   | data => data;
   427 
   428 val instantiation_params = #params o get_instantiation;
   429 
   430 fun instantiation_param lthy v = instantiation_params lthy
   431   |> find_first (fn (_, (v', _)) => v = v')
   432   |> Option.map (fst o fst);
   433 
   434 
   435 (* syntax *)
   436 
   437 fun synchronize_inst_syntax ctxt =
   438   let
   439     val Instantiation { arities = (_, _, sort), params = params } = Instantiation.get ctxt;
   440     val thy = ProofContext.theory_of ctxt;
   441     fun subst (c, ty) = case AxClass.inst_tyco_of thy (c, ty)
   442          of SOME tyco => (case AList.lookup (op =) params (c, tyco)
   443              of SOME (v_ty as (_, ty)) => SOME (ty, Free v_ty)
   444               | NONE => NONE)
   445           | NONE => NONE;
   446     val unchecks =
   447       map (fn ((c, _), v_ty as (_, ty)) => (Free v_ty, Const (c, ty))) params;
   448   in
   449     ctxt
   450     |> Overloading.map_improvable_syntax
   451          (fn (((primary_constraints, _), (((improve, _), _), _)), _) =>
   452             (((primary_constraints, []), (((improve, subst), false), unchecks)), false))
   453   end;
   454 
   455 
   456 (* target *)
   457 
   458 val sanatize_name = (*FIXME*)
   459   let
   460     fun is_valid s = Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s
   461       orelse s = "'" orelse s = "_";
   462     val is_junk = not o is_valid andf Symbol.is_regular;
   463     val junk = Scan.many is_junk;
   464     val scan_valids = Symbol.scanner "Malformed input"
   465       ((junk |--
   466         (Scan.optional (Scan.one Symbol.is_ascii_letter) "x" ^^ (Scan.many is_valid >> implode)
   467         --| junk))
   468       ::: Scan.repeat ((Scan.many1 is_valid >> implode) --| junk));
   469   in
   470     explode #> scan_valids #> implode
   471   end;
   472 
   473 fun type_name "*" = "prod"
   474   | type_name "+" = "sum"
   475   | type_name s = sanatize_name (NameSpace.base s);
   476 
   477 fun resort_terms pp algebra consts constraints ts =
   478   let
   479     fun matchings (Const (c_ty as (c, _))) = (case constraints c
   480          of NONE => I
   481           | SOME sorts => fold2 (curry (Sorts.meet_sort algebra))
   482               (Consts.typargs consts c_ty) sorts)
   483       | matchings _ = I
   484     val tvartab = (fold o fold_aterms) matchings ts Vartab.empty
   485       handle Sorts.CLASS_ERROR e => error (Sorts.class_error pp e);
   486     val inst = map_type_tvar
   487       (fn (vi, sort) => TVar (vi, the_default sort (Vartab.lookup tvartab vi)));
   488   in if Vartab.is_empty tvartab then NONE else SOME ((map o map_types) inst ts) end;
   489 
   490 fun init_instantiation (tycos, vs, sort) thy =
   491   let
   492     val _ = if null tycos then error "At least one arity must be given" else ();
   493     val params = these_params thy sort;
   494     fun get_param tyco (param, (_, (c, ty))) = if can (AxClass.param_of_inst thy) (c, tyco)
   495       then NONE else SOME ((c, tyco),
   496         (param ^ "_" ^ type_name tyco, map_atyps (K (Type (tyco, map TFree vs))) ty));
   497     val inst_params = map_product get_param tycos params |> map_filter I;
   498     val primary_constraints = map (apsnd
   499       (map_atyps (K (TVar ((Name.aT, 0), [])))) o snd o snd) params;
   500     val pp = Syntax.pp_global thy;
   501     val algebra = Sign.classes_of thy
   502       |> fold (fn tyco => Sorts.add_arities pp
   503             (tyco, map (fn class => (class, map snd vs)) sort)) tycos;
   504     val consts = Sign.consts_of thy;
   505     val improve_constraints = AList.lookup (op =)
   506       (map (fn (_, (class, (c, _))) => (c, [[class]])) params);
   507     fun resort_check ts ctxt = case resort_terms pp algebra consts improve_constraints ts
   508      of NONE => NONE
   509       | SOME ts' => SOME (ts', ctxt);
   510     fun improve (c, ty) = case AxClass.inst_tyco_of thy (c, ty)
   511      of SOME tyco => (case AList.lookup (op =) inst_params (c, tyco)
   512          of SOME (_, ty') => if Type.raw_instance (ty', ty) then SOME (ty, ty') else NONE
   513           | NONE => NONE)
   514       | NONE => NONE;
   515   in
   516     thy
   517     |> ProofContext.init
   518     |> Instantiation.put (mk_instantiation ((tycos, vs, sort), inst_params))
   519     |> fold (Variable.declare_typ o TFree) vs
   520     |> fold (Variable.declare_names o Free o snd) inst_params
   521     |> (Overloading.map_improvable_syntax o apfst)
   522          (fn ((_, _), ((_, subst), unchecks)) =>
   523             ((primary_constraints, []), (((improve, K NONE), false), [])))
   524     |> Overloading.add_improvable_syntax
   525     |> Context.proof_map (Syntax.add_term_check 0 "resorting" resort_check)
   526     |> synchronize_inst_syntax
   527   end;
   528 
   529 fun confirm_declaration c = (map_instantiation o apsnd)
   530   (filter_out (fn (_, (c', _)) => c' = c))
   531   #> LocalTheory.target synchronize_inst_syntax
   532 
   533 fun gen_instantiation_instance do_proof after_qed lthy =
   534   let
   535     val (tycos, vs, sort) = (#arities o the_instantiation) lthy;
   536     val arities_proof = maps (fn tyco => Logic.mk_arities (tyco, map snd vs, sort)) tycos;
   537     fun after_qed' results =
   538       LocalTheory.theory (fold (AxClass.add_arity o Thm.varifyT) results)
   539       #> after_qed;
   540   in
   541     lthy
   542     |> do_proof after_qed' arities_proof
   543   end;
   544 
   545 val instantiation_instance = gen_instantiation_instance (fn after_qed => fn ts =>
   546   Proof.theorem_i NONE (after_qed o map the_single) (map (fn t => [(t, [])]) ts));
   547 
   548 fun prove_instantiation_instance tac = gen_instantiation_instance (fn after_qed =>
   549   fn ts => fn lthy => after_qed (map (fn t => Goal.prove lthy [] [] t
   550     (fn {context, ...} => tac context)) ts) lthy) I;
   551 
   552 fun prove_instantiation_exit tac = prove_instantiation_instance tac
   553   #> LocalTheory.exit_global;
   554 
   555 fun prove_instantiation_exit_result f tac x lthy =
   556   let
   557     val morph = ProofContext.export_morphism lthy
   558       (ProofContext.init (ProofContext.theory_of lthy));
   559     val y = f morph x;
   560   in
   561     lthy
   562     |> prove_instantiation_exit (fn ctxt => tac ctxt y)
   563     |> pair y
   564   end;
   565 
   566 fun conclude_instantiation lthy =
   567   let
   568     val { arities, params } = the_instantiation lthy;
   569     val (tycos, vs, sort) = arities;
   570     val thy = ProofContext.theory_of lthy;
   571     val _ = map (fn tyco => if Sign.of_sort thy
   572         (Type (tyco, map TFree vs), sort)
   573       then () else error ("Missing instance proof for type " ^ quote (Sign.extern_type thy tyco)))
   574         tycos;
   575   in lthy end;
   576 
   577 fun pretty_instantiation lthy =
   578   let
   579     val { arities, params } = the_instantiation lthy;
   580     val (tycos, vs, sort) = arities;
   581     val thy = ProofContext.theory_of lthy;
   582     fun pr_arity tyco = Syntax.pretty_arity lthy (tyco, map snd vs, sort);
   583     fun pr_param ((c, _), (v, ty)) =
   584       (Pretty.block o Pretty.breaks) [Pretty.str v, Pretty.str "==",
   585         (Pretty.str o Sign.extern_const thy) c, Pretty.str "::", Syntax.pretty_typ_global thy ty];
   586   in
   587     (Pretty.block o Pretty.fbreaks)
   588       (Pretty.str "instantiation" :: map pr_arity tycos @ map pr_param params)
   589   end;
   590 
   591 
   592 (** tactics and methods **)
   593 
   594 fun intro_classes_tac facts st =
   595   let
   596     val thy = Thm.theory_of_thm st;
   597     val classes = Sign.all_classes thy;
   598     val class_trivs = map (Thm.class_triv thy) classes;
   599     val class_intros = map_filter (try (#intro o AxClass.get_info thy)) classes;
   600     val assm_intros = all_assm_intros thy;
   601   in
   602     Method.intros_tac (class_trivs @ class_intros @ assm_intros) facts st
   603   end;
   604 
   605 fun default_intro_tac ctxt [] =
   606       intro_classes_tac [] ORELSE Locale.intro_locales_tac true ctxt []
   607   | default_intro_tac _ _ = no_tac;
   608 
   609 fun default_tac rules ctxt facts =
   610   HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
   611     default_intro_tac ctxt facts;
   612 
   613 val _ = Context.>> (Context.map_theory
   614   (Method.add_methods
   615    [("intro_classes", Method.no_args (Method.METHOD intro_classes_tac),
   616       "back-chain introduction rules of classes"),
   617     ("default", Method.thms_ctxt_args (Method.METHOD oo default_tac),
   618       "apply some intro/elim rule")]));
   619 
   620 end;
   621