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