src/Pure/Isar/class.ML
author haftmann
Mon Dec 03 16:04:16 2007 +0100 (2007-12-03)
changeset 25518 00d5cc16e891
parent 25514 4b508bb31a6c
child 25536 01753a944433
permissions -rw-r--r--
interface for unchecked definitions
     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 Locale.element list
    12     -> string list -> theory -> string * Proof.context
    13   val class_cmd: bstring -> xstring list -> Element.context Locale.element list
    14     -> xstring list -> theory -> string * Proof.context
    15 
    16   val init: class -> theory -> Proof.context
    17   val logical_const: string -> Markup.property list
    18     -> (string * mixfix) * term -> theory -> theory
    19   val syntactic_const: 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_classes_tac: thm list -> tactic
    25   val prove_subclass: class * class -> thm list -> Proof.context
    26     -> theory -> theory
    27 
    28   val class_prefix: string -> string
    29   val is_class: theory -> class -> bool
    30   val these_params: theory -> sort -> (string * (string * typ)) list
    31   val print_classes: theory -> unit
    32 
    33   (*instances*)
    34   val init_instantiation: arity list -> theory -> local_theory
    35   val instantiation_instance: (local_theory -> local_theory) -> local_theory -> Proof.state
    36   val prove_instantiation_instance: (Proof.context -> tactic) -> local_theory -> local_theory
    37   val conclude_instantiation: local_theory -> local_theory
    38 
    39   val overloaded_const: string * typ -> theory -> term * theory
    40   val overloaded_def: string -> string * term -> theory -> thm * theory
    41   val instantiation_param: Proof.context -> string -> string option
    42   val confirm_declaration: string -> local_theory -> local_theory
    43 
    44   val unoverload: theory -> thm -> thm
    45   val overload: theory -> thm -> thm
    46   val unoverload_conv: theory -> conv
    47   val overload_conv: theory -> conv
    48   val unoverload_const: theory -> string * typ -> string
    49   val param_of_inst: theory -> string * string -> string
    50   val inst_of_param: theory -> string -> (string * string) option
    51 
    52   (*old axclass layer*)
    53   val axclass_cmd: bstring * xstring list
    54     -> ((bstring * Attrib.src list) * string list) list
    55     -> theory -> class * theory
    56   val classrel_cmd: xstring * xstring -> theory -> Proof.state
    57 
    58   (*old instance layer*)
    59   val instance_arity: (theory -> theory) -> arity list -> theory -> Proof.state
    60   val instance_arity_cmd: (bstring * xstring list * xstring) list -> theory -> Proof.state
    61 end;
    62 
    63 structure Class : CLASS =
    64 struct
    65 
    66 (** auxiliary **)
    67 
    68 val classN = "class";
    69 val introN = "intro";
    70 
    71 fun prove_interpretation tac prfx_atts expr inst =
    72   Locale.interpretation_i I prfx_atts expr inst
    73   #> Proof.global_terminal_proof
    74       (Method.Basic (K (Method.SIMPLE_METHOD tac), Position.none), NONE)
    75   #> ProofContext.theory_of;
    76 
    77 fun prove_interpretation_in tac after_qed (name, expr) =
    78   Locale.interpretation_in_locale
    79       (ProofContext.theory after_qed) (name, expr)
    80   #> Proof.global_terminal_proof
    81       (Method.Basic (K (Method.SIMPLE_METHOD tac), Position.none), NONE)
    82   #> ProofContext.theory_of;
    83 
    84 fun OF_LAST thm1 thm2 = thm1 RSN (Thm.nprems_of thm2, thm2);
    85 
    86 fun strip_all_ofclass thy sort =
    87   let
    88     val typ = TVar ((Name.aT, 0), sort);
    89     fun prem_inclass t =
    90       case Logic.strip_imp_prems t
    91        of ofcls :: _ => try Logic.dest_inclass ofcls
    92         | [] => NONE;
    93     fun strip_ofclass class thm =
    94       thm OF (fst o AxClass.of_sort thy (typ, [class])) AxClass.cache;
    95     fun strip thm = case (prem_inclass o Thm.prop_of) thm
    96      of SOME (_, class) => thm |> strip_ofclass class |> strip
    97       | NONE => thm;
    98   in strip end;
    99 
   100 fun get_remove_global_constraint c thy =
   101   let
   102     val ty = Sign.the_const_constraint thy c;
   103   in
   104     thy
   105     |> Sign.add_const_constraint (c, NONE)
   106     |> pair (c, Logic.unvarifyT ty)
   107   end;
   108 
   109 
   110 (** primitive axclass and instance commands **)
   111 
   112 fun axclass_cmd (class, raw_superclasses) raw_specs thy =
   113   let
   114     val ctxt = ProofContext.init thy;
   115     val superclasses = map (Sign.read_class thy) raw_superclasses;
   116     val name_atts = map ((apsnd o map) (Attrib.attribute thy) o fst)
   117       raw_specs;
   118     val axiomss = ProofContext.read_propp (ctxt, map (map (rpair []) o snd)
   119           raw_specs)
   120       |> snd
   121       |> (map o map) fst;
   122   in
   123     AxClass.define_class (class, superclasses) []
   124       (name_atts ~~ axiomss) thy
   125   end;
   126 
   127 local
   128 
   129 fun gen_instance mk_prop add_thm after_qed insts thy =
   130   let
   131     fun after_qed' results =
   132       ProofContext.theory ((fold o fold) add_thm results #> after_qed);
   133   in
   134     thy
   135     |> ProofContext.init
   136     |> Proof.theorem_i NONE after_qed' ((map (fn t => [(t, [])])
   137         o maps (mk_prop thy)) insts)
   138   end;
   139 
   140 in
   141 
   142 val instance_arity =
   143   gen_instance (Logic.mk_arities oo Sign.cert_arity) AxClass.add_arity;
   144 val instance_arity_cmd =
   145   gen_instance (Logic.mk_arities oo Sign.read_arity) AxClass.add_arity I;
   146 val classrel =
   147   gen_instance (single oo (Logic.mk_classrel oo AxClass.cert_classrel))
   148     AxClass.add_classrel I o single;
   149 val classrel_cmd =
   150   gen_instance (single oo (Logic.mk_classrel oo AxClass.read_classrel))
   151     AxClass.add_classrel I o single;
   152 
   153 end; (*local*)
   154 
   155 
   156 (** basic overloading **)
   157 
   158 (* bookkeeping *)
   159 
   160 structure InstData = TheoryDataFun
   161 (
   162   type T = (string * thm) Symtab.table Symtab.table * (string * string) Symtab.table;
   163     (*constant name ~> type constructor ~> (constant name, equation),
   164         constant name ~> (constant name, type constructor)*)
   165   val empty = (Symtab.empty, Symtab.empty);
   166   val copy = I;
   167   val extend = I;
   168   fun merge _ ((taba1, tabb1), (taba2, tabb2)) =
   169     (Symtab.join (K (Symtab.merge (K true))) (taba1, taba2),
   170       Symtab.merge (K true) (tabb1, tabb2));
   171 );
   172 
   173 val inst_tyco = Option.map fst o try (dest_Type o the_single) oo Sign.const_typargs;
   174 
   175 fun inst thy (c, tyco) =
   176   (the o Symtab.lookup ((the o Symtab.lookup (fst (InstData.get thy))) c)) tyco;
   177 
   178 val param_of_inst = fst oo inst;
   179 
   180 fun inst_thms thy = (Symtab.fold (Symtab.fold (cons o snd o snd) o snd) o fst)
   181   (InstData.get thy) [];
   182 
   183 val inst_of_param = Symtab.lookup o snd o InstData.get;
   184 
   185 fun add_inst (c, tyco) inst = (InstData.map o apfst
   186       o Symtab.map_default (c, Symtab.empty)) (Symtab.update_new (tyco, inst))
   187   #> (InstData.map o apsnd) (Symtab.update_new (fst inst, (c, tyco)));
   188 
   189 fun unoverload thy = MetaSimplifier.simplify true (inst_thms thy);
   190 fun overload thy = MetaSimplifier.simplify true (map Thm.symmetric (inst_thms thy));
   191 
   192 fun unoverload_conv thy = MetaSimplifier.rewrite true (inst_thms thy);
   193 fun overload_conv thy = MetaSimplifier.rewrite true (map Thm.symmetric (inst_thms thy));
   194 
   195 fun unoverload_const thy (c_ty as (c, _)) =
   196   case AxClass.class_of_param thy c
   197    of SOME class => (case inst_tyco thy c_ty
   198        of SOME tyco => try (param_of_inst thy) (c, tyco) |> the_default c
   199         | NONE => c)
   200     | NONE => c;
   201 
   202 
   203 (* declaration and definition of instances of overloaded constants *)
   204 
   205 fun primitive_note kind (name, thm) =
   206   PureThy.note_thmss_i kind [((name, []), [([thm], [])])]
   207   #>> (fn [(_, [thm])] => thm);
   208 
   209 fun overloaded_const (c, ty) thy =
   210   let
   211     val SOME class = AxClass.class_of_param thy c;
   212     val SOME tyco = inst_tyco thy (c, ty);
   213     val name_inst = AxClass.instance_name (tyco, class) ^ "_inst";
   214     val c' = NameSpace.base c ^ "_" ^ NameSpace.base tyco;
   215     val ty' = Type.strip_sorts ty;
   216   in
   217     thy
   218     |> Sign.sticky_prefix name_inst
   219     |> Sign.no_base_names
   220     |> Sign.declare_const [] (c', ty', NoSyn)
   221     |-> (fn const' as Const (c'', _) => Thm.add_def false true
   222           (Thm.def_name c', Logic.mk_equals (Const (c, ty'), const'))
   223     #>> Thm.varifyT
   224     #-> (fn thm => add_inst (c, tyco) (c'', thm)
   225     #> primitive_note Thm.internalK (c', thm)
   226     #> snd
   227     #> Sign.restore_naming thy
   228     #> pair (Const (c, ty))))
   229   end;
   230 
   231 fun overloaded_def name (c, t) thy =
   232   let
   233     val ty = Term.fastype_of t;
   234     val SOME tyco = inst_tyco thy (c, ty);
   235     val (c', eq) = inst thy (c, tyco);
   236     val prop = Logic.mk_equals (Const (c', ty), t);
   237     val name' = Thm.def_name_optional
   238       (NameSpace.base c ^ "_" ^ NameSpace.base tyco) name;
   239   in
   240     thy
   241     |> Thm.add_def false false (name', prop)
   242     |>> (fn thm =>  Drule.transitive_thm OF [eq, thm])
   243   end;
   244 
   245 
   246 (** class data **)
   247 
   248 datatype class_data = ClassData of {
   249   consts: (string * string) list
   250     (*locale parameter ~> constant name*),
   251   base_sort: sort,
   252   inst: term option list
   253     (*canonical interpretation*),
   254   morphism: morphism,
   255     (*partial morphism of canonical interpretation*)
   256   intro: thm,
   257   defs: thm list,
   258   operations: (string * (class * (typ * term))) list
   259 };
   260 
   261 fun rep_class_data (ClassData d) = d;
   262 fun mk_class_data ((consts, base_sort, inst, morphism, intro),
   263     (defs, operations)) =
   264   ClassData { consts = consts, base_sort = base_sort, inst = inst,
   265     morphism = morphism, intro = intro, defs = defs,
   266     operations = operations };
   267 fun map_class_data f (ClassData { consts, base_sort, inst, morphism, intro,
   268     defs, operations }) =
   269   mk_class_data (f ((consts, base_sort, inst, morphism, intro),
   270     (defs, operations)));
   271 fun merge_class_data _ (ClassData { consts = consts,
   272     base_sort = base_sort, inst = inst, morphism = morphism, intro = intro,
   273     defs = defs1, operations = operations1 },
   274   ClassData { consts = _, base_sort = _, inst = _, morphism = _, intro = _,
   275     defs = defs2, operations = operations2 }) =
   276   mk_class_data ((consts, base_sort, inst, morphism, intro),
   277     (Thm.merge_thms (defs1, defs2),
   278       AList.merge (op =) (K true) (operations1, operations2)));
   279 
   280 structure ClassData = TheoryDataFun
   281 (
   282   type T = class_data Graph.T
   283   val empty = Graph.empty;
   284   val copy = I;
   285   val extend = I;
   286   fun merge _ = Graph.join merge_class_data;
   287 );
   288 
   289 
   290 (* queries *)
   291 
   292 val lookup_class_data = Option.map rep_class_data oo try o Graph.get_node o ClassData.get;
   293 
   294 fun the_class_data thy class = case lookup_class_data thy class
   295  of NONE => error ("Undeclared class " ^ quote class)
   296   | SOME data => data;
   297 
   298 val is_class = is_some oo lookup_class_data;
   299 
   300 val ancestry = Graph.all_succs o ClassData.get;
   301 
   302 fun these_params thy =
   303   let
   304     fun params class =
   305       let
   306         val const_typs = (#params o AxClass.get_info thy) class;
   307         val const_names = (#consts o the_class_data thy) class;
   308       in
   309         (map o apsnd) (fn c => (c, (the o AList.lookup (op =) const_typs) c)) const_names
   310       end;
   311   in maps params o ancestry thy end;
   312 
   313 fun these_defs thy = maps (these o Option.map #defs o lookup_class_data thy) o ancestry thy;
   314 
   315 fun morphism thy = #morphism o the_class_data thy;
   316 
   317 fun these_intros thy =
   318   Graph.fold (fn (_, (data, _)) => insert Thm.eq_thm ((#intro o rep_class_data) data))
   319     (ClassData.get thy) [];
   320 
   321 fun these_operations thy =
   322   maps (#operations o the_class_data thy) o ancestry thy;
   323 
   324 fun print_classes thy =
   325   let
   326     val ctxt = ProofContext.init thy;
   327     val algebra = Sign.classes_of thy;
   328     val arities =
   329       Symtab.empty
   330       |> Symtab.fold (fn (tyco, arities) => fold (fn (class, _) =>
   331            Symtab.map_default (class, []) (insert (op =) tyco)) arities)
   332              ((#arities o Sorts.rep_algebra) algebra);
   333     val the_arities = these o Symtab.lookup arities;
   334     fun mk_arity class tyco =
   335       let
   336         val Ss = Sorts.mg_domain algebra tyco [class];
   337       in Syntax.pretty_arity ctxt (tyco, Ss, [class]) end;
   338     fun mk_param (c, ty) = Pretty.str (Sign.extern_const thy c ^ " :: "
   339       ^ setmp show_sorts false (Syntax.string_of_typ ctxt o Type.strip_sorts) ty);
   340     fun mk_entry class = (Pretty.block o Pretty.fbreaks o map_filter I) [
   341       (SOME o Pretty.str) ("class " ^ Sign.extern_class thy class ^ ":"),
   342       (SOME o Pretty.block) [Pretty.str "supersort: ",
   343         (Syntax.pretty_sort ctxt o Sign.minimize_sort thy o Sign.super_classes thy) class],
   344       if is_class thy class then (SOME o Pretty.str)
   345         ("locale: " ^ Locale.extern thy class) else NONE,
   346       ((fn [] => NONE | ps => (SOME o Pretty.block o Pretty.fbreaks)
   347           (Pretty.str "parameters:" :: ps)) o map mk_param
   348         o these o Option.map #params o try (AxClass.get_info thy)) class,
   349       (SOME o Pretty.block o Pretty.breaks) [
   350         Pretty.str "instances:",
   351         Pretty.list "" "" (map (mk_arity class) (the_arities class))
   352       ]
   353     ]
   354   in
   355     (Pretty.writeln o Pretty.chunks o separate (Pretty.str "")
   356       o map mk_entry o Sorts.all_classes) algebra
   357   end;
   358 
   359 
   360 (* updaters *)
   361 
   362 fun add_class_data ((class, superclasses), (cs, base_sort, inst, phi, intro)) thy =
   363   let
   364     val operations = map (fn (v_ty as (_, ty), (c, _)) =>
   365       (c, (class, (ty, Free v_ty)))) cs;
   366     val cs = (map o pairself) fst cs;
   367     val add_class = Graph.new_node (class,
   368         mk_class_data ((cs, base_sort, map (SOME o Const) inst, phi, intro), ([], operations)))
   369       #> fold (curry Graph.add_edge class) superclasses;
   370   in
   371     ClassData.map add_class thy
   372   end;
   373 
   374 fun register_operation class (c, (t, some_def)) thy =
   375   let
   376     val base_sort = (#base_sort o the_class_data thy) class;
   377     val prep_typ = map_atyps
   378       (fn TVar (vi as (v, _), sort) => if Name.aT = v
   379         then TFree (v, base_sort) else TVar (vi, sort));
   380     val t' = map_types prep_typ t;
   381     val ty' = Term.fastype_of t';
   382   in
   383     thy
   384     |> (ClassData.map o Graph.map_node class o map_class_data o apsnd)
   385       (fn (defs, operations) =>
   386         (fold cons (the_list some_def) defs,
   387           (c, (class, (ty', t'))) :: operations))
   388   end;
   389 
   390 
   391 (** rule calculation, tactics and methods **)
   392 
   393 val class_prefix = Logic.const_of_class o Sign.base_name;
   394 
   395 fun calculate_morphism class cs =
   396   let
   397     val subst_typ = Term.map_type_tfree (fn var as (v, sort) =>
   398       if v = Name.aT then TVar ((v, 0), [class]) else TVar ((v, 0), sort));
   399     fun subst_aterm (t as Free (v, ty)) = (case AList.lookup (op =) cs v
   400          of SOME (c, _) => Const (c, ty)
   401           | NONE => t)
   402       | subst_aterm t = t;
   403     val subst_term = map_aterms subst_aterm #> map_types subst_typ;
   404   in
   405     Morphism.term_morphism subst_term
   406     $> Morphism.typ_morphism subst_typ
   407   end;
   408 
   409 fun class_intro thy class sups =
   410   let
   411     fun class_elim class =
   412       case (#axioms o AxClass.get_info thy) class
   413        of [thm] => SOME (Drule.unconstrainTs thm)
   414         | [] => NONE;
   415     val pred_intro = case Locale.intros thy class
   416      of ([ax_intro], [intro]) => intro |> OF_LAST ax_intro |> SOME
   417       | ([intro], []) => SOME intro
   418       | ([], [intro]) => SOME intro
   419       | _ => NONE;
   420     val pred_intro' = pred_intro
   421       |> Option.map (fn intro => intro OF map_filter class_elim sups);
   422     val class_intro = (#intro o AxClass.get_info thy) class;
   423     val raw_intro = case pred_intro'
   424      of SOME pred_intro => class_intro |> OF_LAST pred_intro
   425       | NONE => class_intro;
   426     val sort = Sign.super_classes thy class;
   427     val typ = TVar ((Name.aT, 0), sort);
   428     val defs = these_defs thy sups;
   429   in
   430     raw_intro
   431     |> Drule.instantiate' [SOME (Thm.ctyp_of thy typ)] []
   432     |> strip_all_ofclass thy sort
   433     |> Thm.strip_shyps
   434     |> MetaSimplifier.rewrite_rule defs
   435     |> Drule.unconstrainTs
   436   end;
   437 
   438 fun class_interpretation class facts defs thy =
   439   let
   440     val params = these_params thy [class];
   441     val inst = (#inst o the_class_data thy) class;
   442     val tac = ALLGOALS (ProofContext.fact_tac facts);
   443     val prfx = class_prefix class;
   444   in
   445     thy
   446     |> fold_map (get_remove_global_constraint o fst o snd) params
   447     ||> prove_interpretation tac ((false, prfx), []) (Locale.Locale class)
   448           (inst, map (fn def => (("", []), def)) defs)
   449     |-> (fn cs => fold (Sign.add_const_constraint o apsnd SOME) cs)
   450   end;
   451 
   452 fun intro_classes_tac facts st =
   453   let
   454     val thy = Thm.theory_of_thm st;
   455     val classes = Sign.all_classes thy;
   456     val class_trivs = map (Thm.class_triv thy) classes;
   457     val class_intros = these_intros thy;
   458     val axclass_intros = map_filter (try (#intro o AxClass.get_info thy)) classes;
   459   in
   460     Method.intros_tac (class_trivs @ class_intros @ axclass_intros) facts st
   461   end;
   462 
   463 fun default_intro_classes_tac [] = intro_classes_tac []
   464   | default_intro_classes_tac _ = no_tac;
   465 
   466 fun default_tac rules ctxt facts =
   467   HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
   468     default_intro_classes_tac facts;
   469 
   470 val _ = Context.add_setup (Method.add_methods
   471  [("intro_classes", Method.no_args (Method.METHOD intro_classes_tac),
   472     "back-chain introduction rules of classes"),
   473   ("default", Method.thms_ctxt_args (Method.METHOD oo default_tac),
   474     "apply some intro/elim rule")]);
   475 
   476 fun subclass_rule thy (sub, sup) =
   477   let
   478     val ctxt = Locale.init sub thy;
   479     val ctxt_thy = ProofContext.init thy;
   480     val props =
   481       Locale.global_asms_of thy sup
   482       |> maps snd
   483       |> map (ObjectLogic.ensure_propT thy);
   484     fun tac { prems, context } =
   485       Locale.intro_locales_tac true context prems
   486         ORELSE ALLGOALS assume_tac;
   487   in
   488     Goal.prove_multi ctxt [] [] props tac
   489     |> map (Assumption.export false ctxt ctxt_thy)
   490     |> Variable.export ctxt ctxt_thy
   491   end;
   492 
   493 fun prove_single_subclass (sub, sup) thms ctxt thy =
   494   let
   495     val ctxt_thy = ProofContext.init thy;
   496     val subclass_rule = Conjunction.intr_balanced thms
   497       |> Assumption.export false ctxt ctxt_thy
   498       |> singleton (Variable.export ctxt ctxt_thy);
   499     val sub_inst = Thm.ctyp_of thy (TVar ((Name.aT, 0), [sub]));
   500     val sub_ax = #axioms (AxClass.get_info thy sub);
   501     val classrel =
   502       #intro (AxClass.get_info thy sup)
   503       |> Drule.instantiate' [SOME sub_inst] []
   504       |> OF_LAST (subclass_rule OF sub_ax)
   505       |> strip_all_ofclass thy (Sign.super_classes thy sup)
   506       |> Thm.strip_shyps
   507   in
   508     thy
   509     |> AxClass.add_classrel classrel
   510     |> prove_interpretation_in (ALLGOALS (ProofContext.fact_tac thms))
   511          I (sub, Locale.Locale sup)
   512     |> ClassData.map (Graph.add_edge (sub, sup))
   513   end;
   514 
   515 fun prove_subclass (sub, sup) thms ctxt thy =
   516   let
   517     val classes = ClassData.get thy;
   518     val is_sup = not o null o curry (Graph.irreducible_paths classes) sub;
   519     val supclasses = Graph.all_succs classes [sup] |> filter_out is_sup;
   520     fun transform sup' = subclass_rule thy (sup, sup') |> map (fn thm => thm OF thms);
   521   in
   522     thy
   523     |> fold_rev (fn sup' => prove_single_subclass (sub, sup')
   524          (transform sup') ctxt) supclasses
   525  end;
   526 
   527 
   528 (** classes and class target **)
   529 
   530 (* class context syntax *)
   531 
   532 structure ClassSyntax = ProofDataFun(
   533   type T = {
   534     local_constraints: (string * typ) list,
   535     global_constraints: (string * typ) list,
   536     base_sort: sort,
   537     operations: (string * (typ * term)) list,
   538     unchecks: (term * term) list,
   539     passed: bool
   540   };
   541   fun init _ = {
   542     local_constraints = [],
   543     global_constraints = [],
   544     base_sort = [],
   545     operations = [],
   546     unchecks = [],
   547     passed = true
   548   };;
   549 );
   550 
   551 fun synchronize_syntax sups base_sort ctxt =
   552   let
   553     val thy = ProofContext.theory_of ctxt;
   554     fun subst_class_typ sort = map_atyps
   555       (fn TFree _ => TVar ((Name.aT, 0), sort) | ty' => ty');
   556     val operations = these_operations thy sups;
   557     val local_constraints =
   558       (map o apsnd) (subst_class_typ base_sort o fst o snd) operations;
   559     val global_constraints =
   560       (map o apsnd) (fn (class, (ty, _)) => subst_class_typ [class] ty) operations;
   561     fun declare_const (c, _) =
   562       let val b = Sign.base_name c
   563       in Sign.intern_const thy b = c ? Variable.declare_const (b, c) end;
   564     val unchecks = map (fn (c, (_, (ty, t))) => (t, Const (c, ty))) operations;
   565   in
   566     ctxt
   567     |> fold declare_const local_constraints
   568     |> fold (ProofContext.add_const_constraint o apsnd SOME) local_constraints
   569     |> ClassSyntax.put {
   570         local_constraints = local_constraints,
   571         global_constraints = global_constraints,
   572         base_sort = base_sort,
   573         operations = (map o apsnd) snd operations,
   574         unchecks = unchecks,
   575         passed = false
   576       }
   577   end;
   578 
   579 fun refresh_syntax class ctxt =
   580   let
   581     val thy = ProofContext.theory_of ctxt;
   582     val base_sort = (#base_sort o the_class_data thy) class;
   583   in synchronize_syntax [class] base_sort ctxt end;
   584 
   585 val mark_passed = ClassSyntax.map
   586   (fn { local_constraints, global_constraints, base_sort, operations, unchecks, passed } =>
   587     { local_constraints = local_constraints, global_constraints = global_constraints,
   588       base_sort = base_sort, operations = operations, unchecks = unchecks, passed = true });
   589 
   590 fun sort_term_check ts ctxt =
   591   let
   592     val { local_constraints, global_constraints, base_sort, operations, passed, ... } =
   593       ClassSyntax.get ctxt;
   594     fun check_improve (Const (c, ty)) = (case AList.lookup (op =) local_constraints c
   595          of SOME ty0 => (case try (Type.raw_match (ty0, ty)) Vartab.empty
   596              of SOME tyenv => (case Vartab.lookup tyenv (Name.aT, 0)
   597                  of SOME (_, TVar (tvar as (vi, _))) =>
   598                       if TypeInfer.is_param vi then cons tvar else I
   599                   | _ => I)
   600               | NONE => I)
   601           | NONE => I)
   602       | check_improve _ = I;
   603     val improvements = (fold o fold_aterms) check_improve ts [];
   604     val ts' = (map o map_types o map_atyps) (fn ty as TVar tvar =>
   605         if member (op =) improvements tvar
   606           then TFree (Name.aT, base_sort) else ty | ty => ty) ts;
   607     fun check t0 = Envir.expand_term (fn Const (c, ty) => (case AList.lookup (op =) operations c
   608          of SOME (ty0, t) =>
   609               if Type.typ_instance (ProofContext.tsig_of ctxt) (ty, ty0)
   610               then SOME (ty0, check t) else NONE
   611           | NONE => NONE)
   612       | _ => NONE) t0;
   613     val ts'' = map check ts';
   614   in if eq_list (op aconv) (ts, ts'') andalso passed then NONE
   615   else
   616     ctxt
   617     |> fold (ProofContext.add_const_constraint o apsnd SOME) global_constraints
   618     |> mark_passed
   619     |> pair ts''
   620     |> SOME
   621   end;
   622 
   623 fun sort_term_uncheck ts ctxt =
   624   let
   625     val thy = ProofContext.theory_of ctxt;
   626     val unchecks = (#unchecks o ClassSyntax.get) ctxt;
   627     val ts' = map (Pattern.rewrite_term thy unchecks []) ts;
   628   in if eq_list (op aconv) (ts, ts') then NONE else SOME (ts', ctxt) end;
   629 
   630 fun init_ctxt sups base_sort ctxt =
   631   ctxt
   632   |> Variable.declare_term
   633       (Logic.mk_type (TFree (Name.aT, base_sort)))
   634   |> synchronize_syntax sups base_sort
   635   |> Context.proof_map (
   636       Syntax.add_term_check 0 "class" sort_term_check
   637       #> Syntax.add_term_uncheck 0 "class" sort_term_uncheck)
   638 
   639 fun init class thy =
   640   thy
   641   |> Locale.init class
   642   |> init_ctxt [class] ((#base_sort o the_class_data thy) class);
   643 
   644 
   645 (* class definition *)
   646 
   647 local
   648 
   649 fun gen_class_spec prep_class prep_expr process_expr thy raw_supclasses raw_includes_elems =
   650   let
   651     val supclasses = map (prep_class thy) raw_supclasses;
   652     val sups = filter (is_class thy) supclasses;
   653     fun the_base_sort class = lookup_class_data thy class
   654       |> Option.map #base_sort
   655       |> the_default [class];
   656     val base_sort = Sign.minimize_sort thy (maps the_base_sort supclasses);
   657     val supsort = Sign.minimize_sort thy supclasses;
   658     val suplocales = map Locale.Locale sups;
   659     val (raw_elems, includes) = fold_rev (fn Locale.Elem e => apfst (cons e)
   660       | Locale.Expr i => apsnd (cons (prep_expr thy i))) raw_includes_elems ([], []);
   661     val supexpr = Locale.Merge suplocales;
   662     val supparams = (map fst o Locale.parameters_of_expr thy) supexpr;
   663     val supconsts = AList.make (the o AList.lookup (op =) (these_params thy sups))
   664       (map fst supparams);
   665     val mergeexpr = Locale.Merge (suplocales @ includes);
   666     val constrain = Element.Constrains ((map o apsnd o map_atyps)
   667       (fn TFree (_, sort) => TFree (Name.aT, sort)) supparams);
   668   in
   669     ProofContext.init thy
   670     |> Locale.cert_expr supexpr [constrain]
   671     |> snd
   672     |> init_ctxt sups base_sort
   673     |> process_expr Locale.empty raw_elems
   674     |> fst
   675     |> (fn elems => ((((sups, supconsts), (supsort, base_sort, mergeexpr)),
   676           (*FIXME*) if null includes then constrain :: elems else elems)))
   677   end;
   678 
   679 val read_class_spec = gen_class_spec Sign.intern_class Locale.intern_expr Locale.read_expr;
   680 val check_class_spec = gen_class_spec (K I) (K I) Locale.cert_expr;
   681 
   682 fun define_class_params (name, raw_superclasses) raw_consts raw_dep_axioms other_consts thy =
   683   let
   684     val superclasses = map (Sign.certify_class thy) raw_superclasses;
   685     val consts = (map o apfst o apsnd) (Sign.certify_typ thy) raw_consts;
   686     fun add_const ((c, ty), syn) =
   687       Sign.declare_const [] (c, Type.strip_sorts ty, syn) #>> Term.dest_Const;
   688     fun mk_axioms cs thy =
   689       raw_dep_axioms thy cs
   690       |> (map o apsnd o map) (Sign.cert_prop thy)
   691       |> rpair thy;
   692     fun constrain_typs class = (map o apsnd o Term.map_type_tfree)
   693       (fn (v, _) => TFree (v, [class]))
   694   in
   695     thy
   696     |> Sign.add_path (Logic.const_of_class name)
   697     |> fold_map add_const consts
   698     ||> Sign.restore_naming thy
   699     |-> (fn cs => mk_axioms cs
   700     #-> (fn axioms_prop => AxClass.define_class (name, superclasses)
   701            (map fst cs @ other_consts) axioms_prop
   702     #-> (fn class => `(fn _ => constrain_typs class cs)
   703     #-> (fn cs' => `(fn thy => AxClass.get_info thy class)
   704     #-> (fn {axioms, ...} => fold (Sign.add_const_constraint o apsnd SOME) cs'
   705     #> pair (class, (cs', axioms)))))))
   706   end;
   707 
   708 fun gen_class prep_spec prep_param bname
   709     raw_supclasses raw_includes_elems raw_other_consts thy =
   710   let
   711     val class = Sign.full_name thy bname;
   712     val (((sups, supconsts), (supsort, base_sort, mergeexpr)), elems_syn) =
   713       prep_spec thy raw_supclasses raw_includes_elems;
   714     val other_consts = map (tap (Sign.the_const_type thy) o prep_param thy) raw_other_consts;
   715     fun mk_inst class cs =
   716       (map o apsnd o Term.map_type_tfree) (fn (v, _) => TFree (v, [class])) cs;
   717     fun fork_syntax (Element.Fixes xs) =
   718           fold_map (fn (c, ty, syn) => cons (c, syn) #> pair (c, ty, NoSyn)) xs
   719           #>> Element.Fixes
   720       | fork_syntax x = pair x;
   721     val (elems, global_syn) = fold_map fork_syntax elems_syn [];
   722     fun globalize (c, ty) =
   723       ((c, Term.map_type_tfree (K (TFree (Name.aT, base_sort))) ty),
   724         (the_default NoSyn o AList.lookup (op =) global_syn) c);
   725     fun extract_params thy =
   726       let
   727         val params = map fst (Locale.parameters_of thy class);
   728       in
   729         (params, (map globalize o snd o chop (length supconsts)) params)
   730       end;
   731     fun extract_assumes params thy cs =
   732       let
   733         val consts = supconsts @ (map (fst o fst) params ~~ cs);
   734         fun subst (Free (c, ty)) =
   735               Const ((fst o the o AList.lookup (op =) consts) c, ty)
   736           | subst t = t;
   737         fun prep_asm ((name, atts), ts) =
   738           ((Sign.base_name name, map (Attrib.attribute_i thy) atts),
   739             (map o map_aterms) subst ts);
   740       in
   741         Locale.global_asms_of thy class
   742         |> map prep_asm
   743       end;
   744   in
   745     thy
   746     |> Locale.add_locale_i (SOME "") bname mergeexpr elems
   747     |> snd
   748     |> ProofContext.theory_of
   749     |> `extract_params
   750     |-> (fn (all_params, params) =>
   751         define_class_params (bname, supsort) params
   752           (extract_assumes params) other_consts
   753       #-> (fn (_, (consts, axioms)) =>
   754         `(fn thy => class_intro thy class sups)
   755       #-> (fn class_intro =>
   756         PureThy.note_thmss_qualified "" (NameSpace.append class classN)
   757           [((introN, []), [([class_intro], [])])]
   758       #-> (fn [(_, [class_intro])] =>
   759         add_class_data ((class, sups),
   760           (map fst params ~~ consts, base_sort,
   761             mk_inst class (map snd supconsts @ consts),
   762               calculate_morphism class (supconsts @ (map (fst o fst) params ~~ consts)), class_intro))
   763       #> class_interpretation class axioms []
   764       ))))
   765     |> init class
   766     |> pair class
   767   end;
   768 
   769 fun read_const thy = #1 o Term.dest_Const o ProofContext.read_const (ProofContext.init thy);
   770 
   771 in
   772 
   773 val class_cmd = gen_class read_class_spec read_const;
   774 val class = gen_class check_class_spec (K I);
   775 
   776 end; (*local*)
   777 
   778 
   779 (* class target *)
   780 
   781 fun logical_const class pos ((c, mx), dict) thy =
   782   let
   783     val prfx = class_prefix class;
   784     val thy' = thy |> Sign.add_path prfx;
   785     val phi = morphism thy' class;
   786 
   787     val c' = Sign.full_name thy' c;
   788     val dict' = Morphism.term phi dict;
   789     val dict_def = map_types Logic.unvarifyT dict';
   790     val ty' = Term.fastype_of dict_def;
   791     val ty'' = Type.strip_sorts ty';
   792     val def_eq = Logic.mk_equals (Const (c', ty'), dict_def);
   793   in
   794     thy'
   795     |> Sign.declare_const pos (c, ty'', mx) |> snd
   796     |> Thm.add_def false false (c, def_eq)
   797     |>> Thm.symmetric
   798     |-> (fn def => class_interpretation class [def] [Thm.prop_of def]
   799           #> register_operation class (c', (dict', SOME (Thm.varifyT def))))
   800     |> Sign.restore_naming thy
   801     |> Sign.add_const_constraint (c', SOME ty')
   802   end;
   803 
   804 fun syntactic_const class prmode pos ((c, mx), rhs) thy =
   805   let
   806     val prfx = class_prefix class;
   807     val thy' = thy |> Sign.add_path prfx;
   808     val phi = morphism thy class;
   809 
   810     val c' = Sign.full_name thy' c;
   811     val rews = map (Logic.dest_equals o Thm.prop_of) (these_defs thy' [class])
   812     val rhs' = (Pattern.rewrite_term thy rews [] o Morphism.term phi) rhs;
   813     val ty' = Logic.unvarifyT (Term.fastype_of rhs');
   814   in
   815     thy'
   816     |> Sign.add_abbrev (#1 prmode) pos (c, map_types Type.strip_sorts rhs') |> snd
   817     |> Sign.add_const_constraint (c', SOME ty')
   818     |> Sign.notation true prmode [(Const (c', ty'), mx)]
   819     |> register_operation class (c', (rhs', NONE))
   820     |> Sign.restore_naming thy
   821   end;
   822 
   823 
   824 (** instantiation target **)
   825 
   826 (* bookkeeping *)
   827 
   828 datatype instantiation = Instantiation of {
   829   arities: arity list,
   830   params: ((string * string) * (string * typ)) list
   831 }
   832 
   833 structure Instantiation = ProofDataFun
   834 (
   835   type T = instantiation
   836   fun init _ = Instantiation { arities = [], params = [] };
   837 );
   838 
   839 fun mk_instantiation (arities, params) =
   840   Instantiation { arities = arities, params = params };
   841 fun get_instantiation lthy = case Instantiation.get (LocalTheory.target_of lthy)
   842  of Instantiation data => data;
   843 fun map_instantiation f = (LocalTheory.target o Instantiation.map)
   844   (fn Instantiation { arities, params } => mk_instantiation (f (arities, params)));
   845 
   846 fun the_instantiation lthy = case get_instantiation lthy
   847  of { arities = [], ... } => error "No instantiation target"
   848   | data => data;
   849 
   850 val instantiation_params = #params o get_instantiation;
   851 
   852 fun instantiation_param lthy v = instantiation_params lthy
   853   |> find_first (fn (_, (v', _)) => v = v')
   854   |> Option.map (fst o fst);
   855 
   856 fun confirm_declaration c = (map_instantiation o apsnd)
   857   (filter_out (fn (_, (c', _)) => c' = c));
   858 
   859 
   860 (* syntax *)
   861 
   862 fun inst_term_check ts lthy =
   863   let
   864     val params = instantiation_params lthy;
   865     val tsig = ProofContext.tsig_of lthy;
   866     val thy = ProofContext.theory_of lthy;
   867 
   868     fun check_improve (Const (c, ty)) = (case inst_tyco thy (c, ty)
   869          of SOME tyco => (case AList.lookup (op =) params (c, tyco)
   870              of SOME (_, ty') => perhaps (try (Type.typ_match tsig (ty, ty')))
   871               | NONE => I)
   872           | NONE => I)
   873       | check_improve _ = I;
   874     val improvement = (fold o fold_aterms) check_improve ts Vartab.empty;
   875     val ts' = (map o map_types) (Envir.typ_subst_TVars improvement) ts;
   876     val ts'' = (map o map_aterms) (fn t as Const (c, ty) => (case inst_tyco thy (c, ty)
   877          of SOME tyco => (case AList.lookup (op =) params (c, tyco)
   878              of SOME v_ty => Free v_ty
   879               | NONE => t)
   880           | NONE => t)
   881       | t => t) ts';
   882   in if eq_list (op aconv) (ts, ts'') then NONE else SOME (ts'', lthy) end;
   883 
   884 fun inst_term_uncheck ts lthy =
   885   let
   886     val params = instantiation_params lthy;
   887     val ts' = (map o map_aterms) (fn t as Free (v, ty) =>
   888        (case get_first (fn ((c, _), (v', _)) => if v = v' then SOME c else NONE) params
   889          of SOME c => Const (c, ty)
   890           | NONE => t)
   891       | t => t) ts;
   892   in if eq_list (op aconv) (ts, ts') then NONE else SOME (ts', lthy) end;
   893 
   894 
   895 (* target *)
   896 
   897 val sanatize_name = (*FIXME*)
   898   let
   899     fun is_valid s = Symbol.is_ascii_letter s orelse Symbol.is_ascii_digit s orelse s = "'";
   900     val is_junk = not o is_valid andf Symbol.is_regular;
   901     val junk = Scan.many is_junk;
   902     val scan_valids = Symbol.scanner "Malformed input"
   903       ((junk |--
   904         (Scan.optional (Scan.one Symbol.is_ascii_letter) "x" ^^ (Scan.many is_valid >> implode)
   905         --| junk))
   906       -- Scan.repeat ((Scan.many1 is_valid >> implode) --| junk) >> op ::);
   907   in
   908     explode #> scan_valids #> implode
   909   end;
   910 
   911 fun init_instantiation arities thy =
   912   let
   913     val _ = if null arities then error "At least one arity must be given" else ();
   914     val _ = case (duplicates (op =) o map #1) arities
   915      of [] => ()
   916       | dupl_tycos => error ("Type constructors occur more than once in arities: "
   917           ^ commas_quote dupl_tycos);
   918     val _ = map (map (the_class_data thy) o #3) arities;
   919     val ty_insts = map (fn (tyco, sorts, _) =>
   920         (tyco, Type (tyco, map TFree (Name.names Name.context Name.aT sorts))))
   921       arities;
   922     val ty_inst = the o AList.lookup (op =) ty_insts;
   923     fun type_name "*" = "prod"
   924       | type_name "+" = "sum"
   925       | type_name s = sanatize_name (NameSpace.base s); (*FIXME*)
   926     fun get_param tyco sorts (param, (c, ty)) = if can (inst thy) (c, tyco)
   927       then NONE else SOME ((unoverload_const thy (c, ty), tyco),
   928         (param ^ "_" ^ type_name tyco, map_atyps (K (ty_inst tyco)) ty));
   929     fun get_params (tyco, sorts, sort) =
   930       map_filter (get_param tyco sorts) (these_params thy sort)
   931     val params = maps get_params arities;
   932   in
   933     thy
   934     |> ProofContext.init
   935     |> Instantiation.put (mk_instantiation (arities, params))
   936     |> fold (Variable.declare_term o Logic.mk_type o snd) ty_insts
   937     |> fold ProofContext.add_arity arities
   938     |> Context.proof_map (
   939         Syntax.add_term_check 0 "instance" inst_term_check
   940         #> Syntax.add_term_uncheck 0 "instance" inst_term_uncheck)
   941   end;
   942 
   943 fun gen_instantiation_instance do_proof after_qed lthy =
   944   let
   945     val arities = (#arities o the_instantiation) lthy;
   946     val arities_proof = maps Logic.mk_arities arities;
   947     fun after_qed' results =
   948       LocalTheory.theory (fold (AxClass.add_arity o Thm.varifyT) results)
   949       #> after_qed;
   950   in
   951     lthy
   952     |> do_proof after_qed' arities_proof
   953   end;
   954 
   955 val instantiation_instance = gen_instantiation_instance (fn after_qed => fn ts =>
   956   Proof.theorem_i NONE (after_qed o map the_single) (map (fn t => [(t, [])]) ts));
   957 
   958 fun prove_instantiation_instance tac = gen_instantiation_instance (fn after_qed =>
   959   fn ts => fn lthy => after_qed (map (fn t => Goal.prove lthy [] [] t
   960     (fn {context, ...} => tac context)) ts) lthy) I;
   961 
   962 fun conclude_instantiation lthy =
   963   let
   964     val { arities, params } = the_instantiation lthy;
   965     val thy = ProofContext.theory_of lthy;
   966     (*val _ = map (fn (tyco, sorts, sort) =>
   967       if Sign.of_sort thy
   968         (Type (tyco, map TFree (Name.names Name.context Name.aT sorts)), sort)
   969       then () else error ("Missing instance proof for type " ^ quote (Sign.extern_type thy tyco)))
   970         arities; FIXME activate when old instance command is gone*)
   971     val params_of = maps (these o try (#params o AxClass.get_info thy))
   972       o Sign.complete_sort thy;
   973     val missing_params = arities
   974       |> maps (fn (tyco, _, sort) => params_of sort |> map (rpair tyco))
   975       |> filter_out (can (inst thy) o apfst fst);
   976     fun declare_missing ((c, ty0), tyco) thy =
   977     (*fun declare_missing ((c, tyco), (_, ty)) thy =*)
   978       let
   979         val SOME class = AxClass.class_of_param thy c;
   980         val name_inst = AxClass.instance_name (tyco, class) ^ "_inst";
   981         val c' = NameSpace.base c ^ "_" ^ NameSpace.base tyco;
   982         val vs = Name.names Name.context Name.aT (replicate (Sign.arity_number thy tyco) []);
   983         val ty = map_atyps (fn _ => Type (tyco, map TFree vs)) ty0;
   984       in
   985         thy
   986         |> Sign.sticky_prefix name_inst
   987         |> Sign.no_base_names
   988         |> Sign.declare_const [] (c', ty, NoSyn)
   989         |-> (fn const' as Const (c'', _) => Thm.add_def false true
   990               (Thm.def_name c', Logic.mk_equals (const', Const (c, ty)))
   991         #>> Thm.varifyT
   992         #-> (fn thm => add_inst (c, tyco) (c'', Thm.symmetric thm)
   993         #> primitive_note Thm.internalK (c', thm)
   994         #> snd
   995         #> Sign.restore_naming thy))
   996       end;
   997   in
   998     lthy
   999     |> LocalTheory.theory (fold declare_missing missing_params)
  1000   end;
  1001 
  1002 end;