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