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