src/Pure/Isar/class.ML
author haftmann
Wed Apr 02 15:58:41 2008 +0200 (2008-04-02)
changeset 26518 3db6a46d8460
parent 26470 e44d24620515
child 26596 07d7d0a6d5fd
permissions -rw-r--r--
improved improvements for instantiaton
     1 (*  Title:      Pure/Isar/class.ML
     2     ID:         $Id$
     3     Author:     Florian Haftmann, TU Muenchen
     4 
     5 Type classes derived from primitive axclasses and locales.
     6 *)
     7 
     8 signature CLASS =
     9 sig
    10   (*classes*)
    11   val class: bstring -> class list -> Element.context_i list
    12     -> theory -> string * Proof.context
    13   val class_cmd: bstring -> xstring list -> Element.context list
    14     -> theory -> string * Proof.context
    15 
    16   val init: class -> theory -> Proof.context
    17   val declare: string -> Markup.property list
    18     -> (string * mixfix) * term -> theory -> theory
    19   val abbrev: string -> Syntax.mode -> Markup.property list
    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 prove_subclass: class * class -> thm -> theory -> theory
    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 print_classes: theory -> unit
    31 
    32   (*instances*)
    33   val init_instantiation: string list * (string * sort) list * sort
    34     -> theory -> local_theory
    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 conclude_instantiation: local_theory -> local_theory
    40   val instantiation_param: local_theory -> string -> string option
    41   val confirm_declaration: string -> local_theory -> local_theory
    42   val pretty_instantiation: local_theory -> Pretty.T
    43   val type_name: string -> string
    44 
    45   (*old axclass layer*)
    46   val axclass_cmd: bstring * xstring list
    47     -> ((bstring * Attrib.src list) * string list) list
    48     -> theory -> class * theory
    49   val classrel_cmd: xstring * xstring -> theory -> Proof.state
    50 
    51   (*old instance layer*)
    52   val instance_arity: (theory -> theory) -> arity -> theory -> Proof.state
    53   val instance_arity_cmd: bstring * xstring list * xstring -> theory -> Proof.state
    54 end;
    55 
    56 structure Class : CLASS =
    57 struct
    58 
    59 (** auxiliary **)
    60 
    61 val classN = "class";
    62 val introN = "intro";
    63 
    64 fun prove_interpretation tac prfx_atts expr inst =
    65   Locale.interpretation_i I prfx_atts expr inst
    66   #> Proof.global_terminal_proof
    67       (Method.Basic (K (Method.SIMPLE_METHOD tac), Position.none), NONE)
    68   #> ProofContext.theory_of;
    69 
    70 fun prove_interpretation_in tac after_qed (name, expr) =
    71   Locale.interpretation_in_locale
    72       (ProofContext.theory after_qed) (name, expr)
    73   #> Proof.global_terminal_proof
    74       (Method.Basic (K (Method.SIMPLE_METHOD tac), Position.none), NONE)
    75   #> ProofContext.theory_of;
    76 
    77 
    78 (** primitive axclass and instance commands **)
    79 
    80 fun axclass_cmd (class, raw_superclasses) raw_specs thy =
    81   let
    82     val ctxt = ProofContext.init thy;
    83     val superclasses = map (Sign.read_class thy) raw_superclasses;
    84     val name_atts = map ((apsnd o map) (Attrib.attribute thy) o fst)
    85       raw_specs;
    86     val axiomss = ProofContext.read_propp (ctxt, map (map (rpair []) o snd)
    87           raw_specs)
    88       |> snd
    89       |> (map o map) fst;
    90   in
    91     AxClass.define_class (class, superclasses) []
    92       (name_atts ~~ axiomss) thy
    93   end;
    94 
    95 local
    96 
    97 fun gen_instance mk_prop add_thm after_qed insts thy =
    98   let
    99     fun after_qed' results =
   100       ProofContext.theory ((fold o fold) add_thm results #> after_qed);
   101   in
   102     thy
   103     |> ProofContext.init
   104     |> Proof.theorem_i NONE after_qed' ((map (fn t => [(t, [])])
   105         o mk_prop thy) insts)
   106   end;
   107 
   108 in
   109 
   110 val instance_arity =
   111   gen_instance (Logic.mk_arities oo Sign.cert_arity) AxClass.add_arity;
   112 val instance_arity_cmd =
   113   gen_instance (Logic.mk_arities oo Sign.read_arity) AxClass.add_arity I;
   114 val classrel =
   115   gen_instance (single oo (Logic.mk_classrel oo AxClass.cert_classrel)) AxClass.add_classrel I;
   116 val classrel_cmd =
   117   gen_instance (single oo (Logic.mk_classrel oo AxClass.read_classrel)) AxClass.add_classrel I;
   118 
   119 end; (*local*)
   120 
   121 
   122 (** class data **)
   123 
   124 datatype class_data = ClassData of {
   125   consts: (string * string) list
   126     (*locale parameter ~> constant name*),
   127   base_sort: sort,
   128   inst: term option list
   129     (*canonical interpretation*),
   130   morphism: theory -> thm list -> morphism,
   131     (*partial morphism of canonical interpretation*)
   132   assm_intro: thm option,
   133   of_class: thm,
   134   axiom: thm option,
   135   defs: thm list,
   136   operations: (string * (class * (typ * term))) list
   137 };
   138 
   139 fun rep_class_data (ClassData d) = d;
   140 fun mk_class_data ((consts, base_sort, inst, morphism, assm_intro, of_class, axiom),
   141     (defs, operations)) =
   142   ClassData { consts = consts, base_sort = base_sort, inst = inst,
   143     morphism = morphism, assm_intro = assm_intro, of_class = of_class, axiom = axiom,
   144     defs = defs, operations = operations };
   145 fun map_class_data f (ClassData { consts, base_sort, inst, morphism,
   146     assm_intro, of_class, axiom, defs, operations }) =
   147   mk_class_data (f ((consts, base_sort, inst, morphism, assm_intro, of_class, axiom),
   148     (defs, operations)));
   149 fun merge_class_data _ (ClassData { consts = consts,
   150     base_sort = base_sort, inst = inst, morphism = morphism, assm_intro = assm_intro,
   151     of_class = of_class, axiom = axiom, defs = defs1, operations = operations1 },
   152   ClassData { consts = _, base_sort = _, inst = _, morphism = _, assm_intro = _,
   153     of_class = _, axiom = _, defs = defs2, operations = operations2 }) =
   154   mk_class_data ((consts, base_sort, inst, morphism, assm_intro, of_class, axiom),
   155     (Thm.merge_thms (defs1, defs2),
   156       AList.merge (op =) (K true) (operations1, operations2)));
   157 
   158 structure ClassData = TheoryDataFun
   159 (
   160   type T = class_data Graph.T
   161   val empty = Graph.empty;
   162   val copy = I;
   163   val extend = I;
   164   fun merge _ = Graph.join merge_class_data;
   165 );
   166 
   167 
   168 (* queries *)
   169 
   170 val lookup_class_data = Option.map rep_class_data oo try o Graph.get_node o ClassData.get;
   171 
   172 fun the_class_data thy class = case lookup_class_data thy class
   173  of NONE => error ("Undeclared class " ^ quote class)
   174   | SOME data => data;
   175 
   176 val is_class = is_some oo lookup_class_data;
   177 
   178 val ancestry = Graph.all_succs o ClassData.get;
   179 
   180 fun these_params thy =
   181   let
   182     fun params class =
   183       let
   184         val const_typs = (#params o AxClass.get_info thy) class;
   185         val const_names = (#consts o the_class_data thy) class;
   186       in
   187         (map o apsnd)
   188           (fn c => (class, (c, (the o AList.lookup (op =) const_typs) c))) const_names
   189       end;
   190   in maps params o ancestry thy end;
   191 
   192 fun these_defs thy = maps (these o Option.map #defs o lookup_class_data thy) o ancestry thy;
   193 
   194 fun partial_morphism thy class = #morphism (the_class_data thy class) thy [];
   195 fun morphism thy class = #morphism (the_class_data thy class) thy (these_defs thy [class]);
   196 
   197 fun these_assm_intros thy =
   198   Graph.fold (fn (_, (data, _)) => fold (insert Thm.eq_thm)
   199     ((the_list o #assm_intro o rep_class_data) data)) (ClassData.get thy) [];
   200 
   201 fun these_operations thy =
   202   maps (#operations o the_class_data thy) o ancestry thy;
   203 
   204 fun print_classes thy =
   205   let
   206     val ctxt = ProofContext.init thy;
   207     val algebra = Sign.classes_of thy;
   208     val arities =
   209       Symtab.empty
   210       |> Symtab.fold (fn (tyco, arities) => fold (fn (class, _) =>
   211            Symtab.map_default (class, []) (insert (op =) tyco)) arities)
   212              ((#arities o Sorts.rep_algebra) algebra);
   213     val the_arities = these o Symtab.lookup arities;
   214     fun mk_arity class tyco =
   215       let
   216         val Ss = Sorts.mg_domain algebra tyco [class];
   217       in Syntax.pretty_arity ctxt (tyco, Ss, [class]) end;
   218     fun mk_param (c, ty) = Pretty.str (Sign.extern_const thy c ^ " :: "
   219       ^ setmp show_sorts false (Syntax.string_of_typ ctxt o Type.strip_sorts) ty);
   220     fun mk_entry class = (Pretty.block o Pretty.fbreaks o map_filter I) [
   221       (SOME o Pretty.str) ("class " ^ Sign.extern_class thy class ^ ":"),
   222       (SOME o Pretty.block) [Pretty.str "supersort: ",
   223         (Syntax.pretty_sort ctxt o Sign.minimize_sort thy o Sign.super_classes thy) class],
   224       if is_class thy class then (SOME o Pretty.str)
   225         ("locale: " ^ Locale.extern thy class) else NONE,
   226       ((fn [] => NONE | ps => (SOME o Pretty.block o Pretty.fbreaks)
   227           (Pretty.str "parameters:" :: ps)) o map mk_param
   228         o these o Option.map #params o try (AxClass.get_info thy)) class,
   229       (SOME o Pretty.block o Pretty.breaks) [
   230         Pretty.str "instances:",
   231         Pretty.list "" "" (map (mk_arity class) (the_arities class))
   232       ]
   233     ]
   234   in
   235     (Pretty.writeln o Pretty.chunks o separate (Pretty.str "")
   236       o map mk_entry o Sorts.all_classes) algebra
   237   end;
   238 
   239 
   240 (* updaters *)
   241 
   242 fun add_class_data ((class, superclasses),
   243     (params, base_sort, inst, phi, axiom, assm_intro, of_class)) thy =
   244   let
   245     val operations = map (fn (v_ty as (_, ty), (c, _)) =>
   246       (c, (class, (ty, Free v_ty)))) params;
   247     val add_class = Graph.new_node (class,
   248         mk_class_data (((map o pairself) fst params, base_sort,
   249           map (SOME o Const) inst, phi, assm_intro, of_class, axiom), ([], operations)))
   250       #> fold (curry Graph.add_edge class) superclasses;
   251   in ClassData.map add_class thy end;
   252 
   253 fun register_operation class (c, (t, some_def)) thy =
   254   let
   255     val base_sort = (#base_sort o the_class_data thy) class;
   256     val prep_typ = map_type_tvar
   257       (fn (vi as (v, _), sort) => if Name.aT = v
   258         then TFree (v, base_sort) else TVar (vi, sort));
   259     val t' = map_types prep_typ t;
   260     val ty' = Term.fastype_of t';
   261   in
   262     thy
   263     |> (ClassData.map o Graph.map_node class o map_class_data o apsnd)
   264       (fn (defs, operations) =>
   265         (fold cons (the_list some_def) defs,
   266           (c, (class, (ty', t'))) :: operations))
   267   end;
   268 
   269 
   270 (** rule calculation, tactics and methods **)
   271 
   272 val class_prefix = Logic.const_of_class o Sign.base_name;
   273 
   274 fun calculate sups base_sort assm_axiom param_map class thy =
   275   let
   276     (*static parts of morphism*)
   277     val subst_typ = map_type_tfree (fn (v, sort) =>
   278           if v = Name.aT then TVar ((v, 0), [class]) else TVar ((v, 0), sort));
   279     fun subst_aterm (t as Free (v, ty)) = (case AList.lookup (op =) param_map v
   280          of SOME (c, _) => Const (c, ty)
   281           | NONE => t)
   282       | subst_aterm t = t;
   283     fun instantiate thy sort = Thm.instantiate ([pairself (Thm.ctyp_of thy o TVar o pair (Name.aT, 0))
   284       (base_sort, sort)], map (fn (v, (c, ty)) => pairself (Thm.cterm_of thy)
   285         (Var ((v, 0), map_atyps (fn _ => TVar ((Name.aT, 0), sort)) ty),
   286           Const (c, map_atyps (fn _ => TVar ((Name.aT, 0), sort)) ty))) param_map);
   287     val instantiate_base_sort = instantiate thy base_sort;
   288     val instantiate_class = instantiate thy [class];
   289     val (proto_assm_intro, locale_intro) = Locale.intros thy class
   290       |> pairself (try the_single);
   291     val axiom_premises = map_filter (#axiom o the_class_data thy) sups
   292       @ the_list assm_axiom;
   293     val axiom = locale_intro
   294       |> Option.map (Drule.standard o (fn thm => thm OF axiom_premises) o instantiate_class)
   295       |> (fn x as SOME _ => x | NONE => assm_axiom);
   296     val lift_axiom = case axiom
   297      of SOME axiom => (fn thm => Thm.implies_elim thm axiom)
   298       | NONE => I;
   299 
   300     (*dynamic parts of morphism*)
   301     fun rew_term thy defs = Pattern.rewrite_term thy
   302       (map (Logic.dest_equals o Thm.prop_of) defs) [];
   303     fun subst_term thy defs = map_aterms subst_aterm #> rew_term thy defs
   304       #> map_types subst_typ;
   305     fun subst_thm defs = Drule.standard' #> instantiate_class #> lift_axiom
   306       #> MetaSimplifier.rewrite_rule defs;
   307     fun morphism thy defs =
   308       Morphism.typ_morphism subst_typ
   309       $> Morphism.term_morphism (subst_term thy defs)
   310       $> Morphism.thm_morphism (subst_thm defs);
   311 
   312     (*class rules*)
   313     val defs = these_defs thy sups;
   314     val assm_intro = proto_assm_intro
   315       |> Option.map instantiate_base_sort
   316       |> Option.map (MetaSimplifier.rewrite_rule defs)
   317       |> Option.map Goal.close_result;
   318     val class_intro = (#intro o AxClass.get_info thy) class;
   319     val fixate = Thm.instantiate
   320       (map (pairself (Thm.ctyp_of thy)) [(TVar ((Name.aT, 0), []), TFree (Name.aT, base_sort)),
   321         (TVar ((Name.aT, 0), base_sort), TFree (Name.aT, base_sort))], [])
   322     val of_class_sups = if null sups
   323       then map (fixate o Thm.class_triv thy) base_sort
   324       else map (fixate o #of_class o the_class_data thy) sups;
   325     val locale_dests = map Drule.standard' (Locale.dests thy class);
   326     val num_trivs = case length locale_dests
   327      of 0 => if is_none axiom then 0 else 1
   328       | n => n;
   329     val pred_trivs = if num_trivs = 0 then []
   330       else the axiom
   331         |> Thm.prop_of
   332         |> (map_types o map_atyps o K) (TFree (Name.aT, base_sort))
   333         |> (Thm.assume o Thm.cterm_of thy)
   334         |> replicate num_trivs;
   335     val of_class = (fixate class_intro OF of_class_sups OF locale_dests OF pred_trivs)
   336       |> Drule.standard'
   337       |> Goal.close_result;
   338     val this_intro = assm_intro |> the_default class_intro;
   339   in
   340     thy
   341     |> Sign.sticky_prefix (class_prefix class ^ "_" ^ AxClass.axiomsN)
   342     |> PureThy.note Thm.internalK (AxClass.introN, this_intro)
   343     |> snd
   344     |> Sign.restore_naming thy
   345     |> pair (morphism, axiom, assm_intro, of_class)
   346   end;
   347 
   348 fun class_interpretation class facts defs thy =
   349   let
   350     val consts = map (apsnd fst o snd) (these_params thy [class]);
   351     val constraints = map (fn (class, c) => map_atyps (K (TFree (Name.aT,
   352       [class]))) (Sign.the_const_type thy c)) consts;
   353     val no_constraints = map (map_atyps (K (TFree (Name.aT, [])))) constraints;
   354     fun add_constraint c T = Sign.add_const_constraint (c, SOME T);
   355     val inst = (#inst o the_class_data thy) class;
   356     val tac = ALLGOALS (ProofContext.fact_tac facts);
   357     val prfx = class_prefix class;
   358   in
   359     thy
   360     |> fold2 add_constraint (map snd consts) no_constraints
   361     |> prove_interpretation tac ((false, prfx), []) (Locale.Locale class)
   362           (inst, map (fn def => (("", []), def)) defs)
   363     |> fold2 add_constraint (map snd consts) constraints
   364   end;
   365 
   366 fun prove_subclass (sub, sup) thm thy =
   367   let
   368     val of_class = (#of_class o the_class_data thy) sup;
   369     val intro = Drule.standard' (of_class OF [Drule.standard' thm]);
   370     val classrel = intro OF (the_list o #axiom o the_class_data thy) sub;
   371   in
   372     thy
   373     |> AxClass.add_classrel classrel
   374     |> prove_interpretation_in (ALLGOALS (ProofContext.fact_tac [thm]))
   375          I (sub, Locale.Locale sup)
   376     |> ClassData.map (Graph.add_edge (sub, sup))
   377   end;
   378 
   379 fun intro_classes_tac facts st =
   380   let
   381     val thy = Thm.theory_of_thm st;
   382     val classes = Sign.all_classes thy;
   383     val class_trivs = map (Thm.class_triv thy) classes;
   384     val class_intros = map_filter (try (#intro o AxClass.get_info thy)) classes;
   385     val assm_intros = these_assm_intros thy;
   386   in
   387     Method.intros_tac (class_trivs @ class_intros @ assm_intros) facts st
   388   end;
   389 
   390 fun default_intro_tac ctxt [] =
   391       intro_classes_tac [] ORELSE Locale.intro_locales_tac true ctxt []
   392   | default_intro_tac _ _ = no_tac;
   393 
   394 fun default_tac rules ctxt facts =
   395   HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
   396     default_intro_tac ctxt facts;
   397 
   398 val _ = Context.>> (Context.map_theory
   399   (Method.add_methods
   400    [("intro_classes", Method.no_args (Method.METHOD intro_classes_tac),
   401       "back-chain introduction rules of classes"),
   402     ("default", Method.thms_ctxt_args (Method.METHOD oo default_tac),
   403       "apply some intro/elim rule")]));
   404 
   405 
   406 
   407 (** classes and class target **)
   408 
   409 (* class context syntax *)
   410 
   411 fun synchronize_class_syntax sups base_sort ctxt =
   412   let
   413     val thy = ProofContext.theory_of ctxt;
   414     val operations = these_operations thy sups;
   415     fun subst_class_typ sort = map_type_tfree (K (TVar ((Name.aT, 0), sort)));
   416     val primary_constraints =
   417       (map o apsnd) (subst_class_typ base_sort o fst o snd) operations;
   418     val secondary_constraints =
   419       (map o apsnd) (fn (class, (ty, _)) => subst_class_typ [class] ty) operations;
   420     fun declare_const (c, _) =
   421       let val b = Sign.base_name c
   422       in Sign.intern_const thy b = c ? Variable.declare_const (b, c) end;
   423     fun improve (c, ty) = (case AList.lookup (op =) primary_constraints c
   424      of SOME ty' => (case try (Type.raw_match (ty', ty)) Vartab.empty
   425          of SOME tyenv => (case Vartab.lookup tyenv (Name.aT, 0)
   426              of SOME (_, ty' as TVar (tvar as (vi, _))) =>
   427                   if TypeInfer.is_param vi
   428                     then SOME (ty', TFree (Name.aT, base_sort))
   429                     else NONE
   430               | _ => NONE)
   431           | NONE => NONE)
   432       | NONE => NONE)
   433     fun subst (c, ty) = Option.map snd (AList.lookup (op =) operations c);
   434     val unchecks = map (fn (c, (_, (ty, t))) => (t, Const (c, ty))) operations;
   435   in
   436     ctxt
   437     |> fold declare_const primary_constraints
   438     |> Overloading.map_improvable_syntax (K (((primary_constraints, secondary_constraints),
   439         ((improve, subst), unchecks)), false))
   440     |> Overloading.set_primary_constraints
   441   end;
   442 
   443 fun refresh_syntax class ctxt =
   444   let
   445     val thy = ProofContext.theory_of ctxt;
   446     val base_sort = (#base_sort o the_class_data thy) class;
   447   in synchronize_class_syntax [class] base_sort ctxt end;
   448 
   449 fun init_ctxt sups base_sort ctxt =
   450   ctxt
   451   |> Variable.declare_term
   452       (Logic.mk_type (TFree (Name.aT, base_sort)))
   453   |> synchronize_class_syntax sups base_sort
   454   |> Overloading.add_improvable_syntax;
   455 
   456 fun init class thy =
   457   thy
   458   |> Locale.init class
   459   |> init_ctxt [class] ((#base_sort o the_class_data thy) class);
   460 
   461 
   462 (* class definition *)
   463 
   464 local
   465 
   466 fun gen_class_spec prep_class process_expr thy raw_supclasses raw_elems =
   467   let
   468     val supclasses = map (prep_class thy) raw_supclasses;
   469     val supsort = Sign.minimize_sort thy supclasses;
   470     val sups = filter (is_class thy) supsort;
   471     val base_sort = if null sups then supsort else
   472       foldr1 (Sorts.inter_sort (Sign.classes_of thy))
   473         (map (#base_sort o the_class_data thy) sups);
   474     val suplocales = map Locale.Locale sups;
   475     val supexpr = Locale.Merge suplocales;
   476     val supparams = (map fst o Locale.parameters_of_expr thy) supexpr;
   477     val mergeexpr = Locale.Merge (suplocales);
   478     val constrain = Element.Constrains ((map o apsnd o map_atyps)
   479       (K (TFree (Name.aT, base_sort))) supparams);
   480     fun fork_syn (Element.Fixes xs) =
   481           fold_map (fn (c, ty, syn) => cons (c, syn) #> pair (c, ty, NoSyn)) xs
   482           #>> Element.Fixes
   483       | fork_syn x = pair x;
   484     fun fork_syntax elems =
   485       let
   486         val (elems', global_syntax) = fold_map fork_syn elems [];
   487       in (constrain :: elems', global_syntax) end;
   488     val (elems, global_syntax) =
   489       ProofContext.init thy
   490       |> Locale.cert_expr supexpr [constrain]
   491       |> snd
   492       |> init_ctxt sups base_sort
   493       |> process_expr Locale.empty raw_elems
   494       |> fst
   495       |> fork_syntax
   496   in (((sups, supparams), (supsort, base_sort, mergeexpr)), (elems, global_syntax)) end;
   497 
   498 val read_class_spec = gen_class_spec Sign.intern_class Locale.read_expr;
   499 val check_class_spec = gen_class_spec (K I) Locale.cert_expr;
   500 
   501 fun adjungate_axclass bname class base_sort sups supsort supparams global_syntax thy =
   502   let
   503     val supconsts = map fst supparams
   504       |> AList.make (snd o the o AList.lookup (op =) (these_params thy sups))
   505       |> (map o apsnd o apsnd o map_atyps o K o TFree) (Name.aT, [class]);
   506     val all_params = map fst (Locale.parameters_of thy class);
   507     fun add_const (v, raw_ty) thy =
   508       let
   509         val c = Sign.full_name thy v;
   510         val ty = map_atyps (K (TFree (Name.aT, base_sort))) raw_ty;
   511         val ty0 = Type.strip_sorts ty;
   512         val ty' = map_atyps (K (TFree (Name.aT, [class]))) ty0;
   513         val syn = (the_default NoSyn o AList.lookup (op =) global_syntax) v;
   514       in
   515         thy
   516         |> Sign.declare_const [] (v, ty0, syn)
   517         |> snd
   518         |> pair ((v, ty), (c, ty'))
   519       end;
   520     fun add_consts raw_params thy =
   521       thy
   522       |> Sign.add_path (Logic.const_of_class bname)
   523       |> fold_map add_const raw_params
   524       ||> Sign.restore_naming thy
   525       |-> (fn params => pair (supconsts @ (map o apfst) fst params, params));
   526     fun globalize param_map = map_aterms
   527       (fn Free (v, ty) => Const ((fst o the o AList.lookup (op =) param_map) v, ty)
   528         | t => t);
   529     val raw_pred = Locale.intros thy class
   530       |> fst
   531       |> map (Logic.unvarify o Logic.strip_imp_concl o Thm.prop_of);
   532     fun get_axiom thy = case (#axioms o AxClass.get_info thy) class
   533      of [] => NONE
   534       | [thm] => SOME thm;
   535   in
   536     thy
   537     |> add_consts ((snd o chop (length supparams)) all_params)
   538     |-> (fn (param_map, params) => AxClass.define_class (bname, supsort)
   539           (map (fst o snd) params)
   540           [((bname ^ "_" ^ AxClass.axiomsN, []), map (globalize param_map) raw_pred)]
   541     #> snd
   542     #> `get_axiom
   543     #-> (fn assm_axiom => fold (Sign.add_const_constraint o apsnd SOME o snd) params
   544     #> pair (param_map, params, assm_axiom)))
   545   end;
   546 
   547 fun gen_class prep_spec bname raw_supclasses raw_elems thy =
   548   let
   549     val class = Sign.full_name thy bname;
   550     val (((sups, supparams), (supsort, base_sort, mergeexpr)), (elems, global_syntax)) =
   551       prep_spec thy raw_supclasses raw_elems;
   552   in
   553     thy
   554     |> Locale.add_locale_i (SOME "") bname mergeexpr elems
   555     |> snd
   556     |> ProofContext.theory_of
   557     |> adjungate_axclass bname class base_sort sups supsort supparams global_syntax
   558     |-> (fn (param_map, params, assm_axiom) =>
   559         calculate sups base_sort assm_axiom param_map class
   560     #-> (fn (morphism, axiom, assm_intro, of_class) =>
   561         add_class_data ((class, sups), (params, base_sort,
   562           map snd param_map, morphism, axiom, assm_intro, of_class))
   563     #> class_interpretation class (the_list axiom) []))
   564     |> init class
   565     |> pair class
   566   end;
   567 
   568 in
   569 
   570 val class_cmd = gen_class read_class_spec;
   571 val class = gen_class check_class_spec;
   572 
   573 end; (*local*)
   574 
   575 
   576 (* class target *)
   577 
   578 fun declare class pos ((c, mx), dict) thy =
   579   let
   580     val prfx = class_prefix class;
   581     val thy' = thy |> Sign.add_path prfx;
   582     val phi = partial_morphism thy' class;
   583 
   584     val c' = Sign.full_name thy' c;
   585     val dict' = Morphism.term phi dict;
   586     val dict_def = map_types Logic.unvarifyT dict';
   587     val ty' = Term.fastype_of dict_def;
   588     val ty'' = Type.strip_sorts ty';
   589     val def_eq = Logic.mk_equals (Const (c', ty'), dict_def);
   590     fun get_axiom thy = ((Thm.varifyT o Thm.get_axiom_i thy) c', thy);
   591   in
   592     thy'
   593     |> Sign.declare_const pos (c, ty'', mx) |> snd
   594     |> Thm.add_def false false (c, def_eq)
   595     |>> Thm.symmetric
   596     ||>> get_axiom
   597     |-> (fn (def, def') => class_interpretation class [def] [Thm.prop_of def]
   598       #> register_operation class (c', (dict', SOME (Thm.symmetric def')))
   599       #> PureThy.note Thm.internalK (c ^ "_raw", def')
   600       #> snd)
   601     |> Sign.restore_naming thy
   602     |> Sign.add_const_constraint (c', SOME ty')
   603   end;
   604 
   605 fun abbrev class prmode pos ((c, mx), rhs) thy =
   606   let
   607     val prfx = class_prefix class;
   608     val thy' = thy |> Sign.add_path prfx;
   609     val phi = morphism thy class;
   610 
   611     val c' = Sign.full_name thy' c;
   612     val rhs' = Morphism.term phi rhs;
   613     val ty' = Logic.unvarifyT (Term.fastype_of rhs');
   614   in
   615     thy'
   616     |> Sign.add_abbrev (#1 prmode) pos (c, map_types Type.strip_sorts rhs') |> snd
   617     |> Sign.add_const_constraint (c', SOME ty')
   618     |> Sign.notation true prmode [(Const (c', ty'), mx)]
   619     |> register_operation class (c', (rhs', NONE))
   620     |> Sign.restore_naming thy
   621   end;
   622 
   623 
   624 (** instantiation target **)
   625 
   626 (* bookkeeping *)
   627 
   628 datatype instantiation = Instantiation of {
   629   arities: string list * (string * sort) list * sort,
   630   params: ((string * string) * (string * typ)) list
   631     (*(instantiation parameter, type constructor), (local instantiation parameter, typ)*)
   632 }
   633 
   634 structure Instantiation = ProofDataFun
   635 (
   636   type T = instantiation
   637   fun init _ = Instantiation { arities = ([], [], []), params = [] };
   638 );
   639 
   640 fun mk_instantiation (arities, params) =
   641   Instantiation { arities = arities, params = params };
   642 fun get_instantiation lthy = case Instantiation.get (LocalTheory.target_of lthy)
   643  of Instantiation data => data;
   644 fun map_instantiation f = (LocalTheory.target o Instantiation.map)
   645   (fn Instantiation { arities, params } => mk_instantiation (f (arities, params)));
   646 
   647 fun the_instantiation lthy = case get_instantiation lthy
   648  of { arities = ([], [], []), ... } => error "No instantiation target"
   649   | data => data;
   650 
   651 val instantiation_params = #params o get_instantiation;
   652 
   653 fun instantiation_param lthy v = instantiation_params lthy
   654   |> find_first (fn (_, (v', _)) => v = v')
   655   |> Option.map (fst o fst);
   656 
   657 
   658 (* syntax *)
   659 
   660 fun synchronize_inst_syntax ctxt =
   661   let
   662     val Instantiation { arities = (_, _, sort), params = params } = Instantiation.get ctxt;
   663     val thy = ProofContext.theory_of ctxt;
   664     fun subst (c, ty) = case AxClass.inst_tyco_of thy (c, ty)
   665          of SOME tyco => (case AList.lookup (op =) params (c, tyco)
   666              of SOME (v_ty as (_, ty)) => SOME (ty, Free v_ty)
   667               | NONE => NONE)
   668           | NONE => NONE;
   669     val unchecks =
   670       map (fn ((c, _), v_ty as (_, ty)) => (Free v_ty, Const (c, ty))) params;
   671   in
   672     ctxt
   673     |> Overloading.map_improvable_syntax
   674          (fn (((primary_constraints, _), ((improve, _), _)), _) =>
   675             (((primary_constraints, []), ((improve, subst), unchecks)), false))
   676   end;
   677 
   678 
   679 (* target *)
   680 
   681 val sanatize_name = (*FIXME*)
   682   let
   683     fun is_valid s = Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s
   684       orelse s = "'" orelse s = "_";
   685     val is_junk = not o is_valid andf Symbol.is_regular;
   686     val junk = Scan.many is_junk;
   687     val scan_valids = Symbol.scanner "Malformed input"
   688       ((junk |--
   689         (Scan.optional (Scan.one Symbol.is_ascii_letter) "x" ^^ (Scan.many is_valid >> implode)
   690         --| junk))
   691       ::: Scan.repeat ((Scan.many1 is_valid >> implode) --| junk));
   692   in
   693     explode #> scan_valids #> implode
   694   end;
   695 
   696 fun type_name "*" = "prod"
   697   | type_name "+" = "sum"
   698   | type_name s = sanatize_name (NameSpace.base s); (*FIXME*)
   699 
   700 fun resort_terms pp algebra consts constraints ts =
   701   let
   702     fun matchings (Const (c_ty as (c, _))) = (case constraints c
   703          of NONE => I
   704           | SOME sorts => fold2 (curry (Sorts.meet_sort algebra))
   705               (Consts.typargs consts c_ty) sorts)
   706       | matchings _ = I
   707     val tvartab = (fold o fold_aterms) matchings ts Vartab.empty
   708       handle Sorts.CLASS_ERROR e => Sorts.class_error pp e;
   709     val inst = map_type_tvar (fn (vi, _) => TVar (vi, the (Vartab.lookup tvartab vi)));
   710   in if Vartab.is_empty tvartab then NONE else SOME ((map o map_types) inst ts) end;
   711 
   712 fun init_instantiation (tycos, vs, sort) thy =
   713   let
   714     val _ = if null tycos then error "At least one arity must be given" else ();
   715     val params = these_params thy sort;
   716     fun get_param tyco (param, (_, (c, ty))) = if can (AxClass.param_of_inst thy) (c, tyco)
   717       then NONE else SOME ((c, tyco),
   718         (param ^ "_" ^ type_name tyco, map_atyps (K (Type (tyco, map TFree vs))) ty));
   719     val inst_params = map_product get_param tycos params |> map_filter I;
   720     val primary_constraints = map (apsnd
   721       (map_atyps (K (TVar ((Name.aT, 0), [])))) o snd o snd) params;
   722     val pp = Sign.pp thy;
   723     val algebra = Sign.classes_of thy
   724       |> fold (fn tyco => Sorts.add_arities pp
   725             (tyco, map (fn class => (class, map snd vs)) sort)) tycos;
   726     val consts = Sign.consts_of thy;
   727     val improve_constraints = AList.lookup (op =)
   728       (map (fn (_, (class, (c, _))) => (c, [[class]])) params);
   729     fun resort_check ts ctxt = case resort_terms pp algebra consts improve_constraints ts
   730      of NONE => NONE
   731       | SOME ts' => SOME (ts', ctxt);
   732     fun improve (c, ty) = case AxClass.inst_tyco_of thy (c, ty)
   733      of SOME tyco => (case AList.lookup (op =) inst_params (c, tyco)
   734          of SOME (_, ty') => if Type.raw_instance (ty', ty) then SOME (ty, ty') else NONE
   735           | NONE => NONE)
   736       | NONE => NONE;
   737   in
   738     thy
   739     |> ProofContext.init
   740     |> Instantiation.put (mk_instantiation ((tycos, vs, sort), inst_params))
   741     |> fold (Variable.declare_term o Logic.mk_type o TFree) vs
   742     |> fold (Variable.declare_names o Free o snd) inst_params
   743     |> (Overloading.map_improvable_syntax o apfst)
   744          (fn ((_, _), ((_, subst), unchecks)) =>
   745             ((primary_constraints, []), ((improve, K NONE), [])))
   746     |> Overloading.add_improvable_syntax
   747     |> Context.proof_map (Syntax.add_term_check 0 "resorting" resort_check)
   748     |> synchronize_inst_syntax
   749   end;
   750 
   751 fun confirm_declaration c = (map_instantiation o apsnd)
   752   (filter_out (fn (_, (c', _)) => c' = c))
   753   #> LocalTheory.target synchronize_inst_syntax
   754 
   755 fun gen_instantiation_instance do_proof after_qed lthy =
   756   let
   757     val (tycos, vs, sort) = (#arities o the_instantiation) lthy;
   758     val arities_proof = maps (fn tyco => Logic.mk_arities (tyco, map snd vs, sort)) tycos;
   759     fun after_qed' results =
   760       LocalTheory.theory (fold (AxClass.add_arity o Thm.varifyT) results)
   761       #> after_qed;
   762   in
   763     lthy
   764     |> do_proof after_qed' arities_proof
   765   end;
   766 
   767 val instantiation_instance = gen_instantiation_instance (fn after_qed => fn ts =>
   768   Proof.theorem_i NONE (after_qed o map the_single) (map (fn t => [(t, [])]) ts));
   769 
   770 fun prove_instantiation_instance tac = gen_instantiation_instance (fn after_qed =>
   771   fn ts => fn lthy => after_qed (map (fn t => Goal.prove lthy [] [] t
   772     (fn {context, ...} => tac context)) ts) lthy) I;
   773 
   774 fun conclude_instantiation lthy =
   775   let
   776     val { arities, params } = the_instantiation lthy;
   777     val (tycos, vs, sort) = arities;
   778     val thy = ProofContext.theory_of lthy;
   779     val _ = map (fn tyco => if Sign.of_sort thy
   780         (Type (tyco, map TFree vs), sort)
   781       then () else error ("Missing instance proof for type " ^ quote (Sign.extern_type thy tyco)))
   782         tycos;
   783   in lthy end;
   784 
   785 fun pretty_instantiation lthy =
   786   let
   787     val { arities, params } = the_instantiation lthy;
   788     val (tycos, vs, sort) = arities;
   789     val thy = ProofContext.theory_of lthy;
   790     fun pr_arity tyco = Syntax.pretty_arity lthy (tyco, map snd vs, sort);
   791     fun pr_param ((c, _), (v, ty)) =
   792       (Pretty.block o Pretty.breaks) [Pretty.str v, Pretty.str "==",
   793         (Pretty.str o Sign.extern_const thy) c, Pretty.str "::", Sign.pretty_typ thy ty];
   794   in
   795     (Pretty.block o Pretty.fbreaks)
   796       (Pretty.str "instantiation" :: map pr_arity tycos @ map pr_param params)
   797   end;
   798 
   799 end;
   800