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