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