src/Pure/Isar/class.ML
author wenzelm
Sun Oct 14 00:18:05 2007 +0200 (2007-10-14)
changeset 25024 0615bb9955dd
parent 25020 f1344290e420
child 25038 522abf8a5f87
permissions -rw-r--r--
added is_class;
tuned signature of add_const/abbrev_in_class;
removed obsolete class_of_locale/locale_of_class;
tuned name prefixing: Sign.full_name does the job;
     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   val fork_mixfix: bool -> bool -> mixfix -> mixfix * mixfix
    11 
    12   val axclass_cmd: bstring * xstring list
    13     -> ((bstring * Attrib.src list) * string list) list
    14     -> theory -> class * theory
    15   val classrel_cmd: xstring * xstring -> theory -> Proof.state
    16 
    17   val class: bstring -> class list -> Element.context_i Locale.element list
    18     -> string list -> theory -> string * Proof.context
    19   val class_cmd: bstring -> xstring list -> Element.context Locale.element list
    20     -> xstring list -> theory -> string * Proof.context
    21   val init: class -> Proof.context -> Proof.context;
    22   val add_const_in_class: string -> (string * mixfix) * term -> theory -> string * theory
    23   val add_abbrev_in_class: string -> Syntax.mode -> (string * mixfix) * term -> theory ->
    24     string * theory
    25   val remove_constraint: class -> string -> Proof.context -> Proof.context
    26   val is_class: theory -> string -> bool
    27   val these_params: theory -> sort -> (string * (string * typ)) list
    28   val intro_classes_tac: thm list -> tactic
    29   val default_intro_classes_tac: thm list -> tactic
    30   val print_classes: theory -> unit
    31   val uncheck: bool ref
    32 
    33   val instance_arity: (theory -> theory) -> arity list -> theory -> Proof.state
    34   val instance: arity list -> ((bstring * Attrib.src list) * term) list
    35     -> (thm list -> theory -> theory)
    36     -> theory -> Proof.state
    37   val instance_cmd: (bstring * xstring list * xstring) list
    38     -> ((bstring * Attrib.src list) * xstring) list
    39     -> (thm list -> theory -> theory)
    40     -> theory -> Proof.state
    41   val prove_instance: tactic -> arity list
    42     -> ((bstring * Attrib.src list) * term) list
    43     -> theory -> thm list * theory
    44   val unoverload: theory -> conv
    45   val overload: theory -> conv
    46   val unoverload_const: theory -> string * typ -> string
    47   val inst_const: theory -> string * string -> string
    48   val param_const: theory -> string -> (string * string) option
    49 end;
    50 
    51 structure Class : CLASS =
    52 struct
    53 
    54 (** auxiliary **)
    55 
    56 fun fork_mixfix is_locale is_class mx =
    57   let
    58     val mx' = Syntax.unlocalize_mixfix mx;
    59     val mx_global = if not is_locale orelse (is_class andalso not (mx = mx'))
    60       then mx' else NoSyn;
    61     val mx_local = if is_locale then mx else NoSyn;
    62   in (mx_global, mx_local) end;
    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 OF_LAST thm1 thm2 = thm1 RSN (Thm.nprems_of thm2, thm2);
    71 
    72 fun strip_all_ofclass thy sort =
    73   let
    74     val typ = TVar ((Name.aT, 0), sort);
    75     fun prem_inclass t =
    76       case Logic.strip_imp_prems t
    77        of ofcls :: _ => try Logic.dest_inclass ofcls
    78         | [] => NONE;
    79     fun strip_ofclass class thm =
    80       thm OF (fst o AxClass.of_sort thy (typ, [class])) AxClass.cache;
    81     fun strip thm = case (prem_inclass o Thm.prop_of) thm
    82      of SOME (_, class) => thm |> strip_ofclass class |> strip
    83       | NONE => thm;
    84   in strip end;
    85 
    86 
    87 (** axclass command **)
    88 
    89 fun axclass_cmd (class, raw_superclasses) raw_specs thy =
    90   let
    91     val ctxt = ProofContext.init thy;
    92     val superclasses = map (Sign.read_class thy) raw_superclasses;
    93     val name_atts = map ((apsnd o map) (Attrib.attribute thy) o fst)
    94       raw_specs;
    95     val axiomss = ProofContext.read_propp (ctxt, map (map (rpair []) o snd)
    96           raw_specs)
    97       |> snd
    98       |> (map o map) fst;
    99   in
   100     AxClass.define_class (class, superclasses) []
   101       (name_atts ~~ axiomss) thy
   102   end;
   103 
   104 local
   105 
   106 fun gen_instance mk_prop add_thm after_qed insts thy =
   107   let
   108     fun after_qed' results =
   109       ProofContext.theory ((fold o fold) add_thm results #> after_qed);
   110   in
   111     thy
   112     |> ProofContext.init
   113     |> Proof.theorem_i NONE after_qed' ((map (fn t => [(t, [])])
   114         o maps (mk_prop thy)) insts)
   115   end;
   116 
   117 in
   118 
   119 val instance_arity =
   120   gen_instance (Logic.mk_arities oo Sign.cert_arity) AxClass.add_arity;
   121 val classrel =
   122   gen_instance (single oo (Logic.mk_classrel oo AxClass.cert_classrel))
   123     AxClass.add_classrel I o single;
   124 val classrel_cmd =
   125   gen_instance (single oo (Logic.mk_classrel oo AxClass.read_classrel))
   126     AxClass.add_classrel I o single;
   127 
   128 end; (*local*)
   129 
   130 
   131 (** explicit constants for overloaded definitions **)
   132 
   133 structure InstData = TheoryDataFun
   134 (
   135   type T = (string * thm) Symtab.table Symtab.table * (string * string) Symtab.table;
   136     (*constant name ~> type constructor ~> (constant name, equation),
   137         constant name ~> (constant name, type constructor)*)
   138   val empty = (Symtab.empty, Symtab.empty);
   139   val copy = I;
   140   val extend = I;
   141   fun merge _ ((taba1, tabb1), (taba2, tabb2)) =
   142     (Symtab.join (K (Symtab.merge (K true))) (taba1, taba2),
   143       Symtab.merge (K true) (tabb1, tabb2));
   144 );
   145 
   146 fun inst_thms thy = (Symtab.fold (Symtab.fold (cons o snd o snd) o snd) o fst)
   147     (InstData.get thy) [];
   148 fun add_inst (c, tyco) inst = (InstData.map o apfst
   149       o Symtab.map_default (c, Symtab.empty)) (Symtab.update_new (tyco, inst))
   150   #> (InstData.map o apsnd) (Symtab.update_new (fst inst, (c, tyco)));
   151 
   152 fun unoverload thy = MetaSimplifier.rewrite true (inst_thms thy);
   153 fun overload thy = MetaSimplifier.rewrite true (map Thm.symmetric (inst_thms thy));
   154 
   155 fun inst_const thy (c, tyco) =
   156   (fst o the o Symtab.lookup ((the o Symtab.lookup (fst (InstData.get thy))) c)) tyco;
   157 fun unoverload_const thy (c_ty as (c, _)) =
   158   case AxClass.class_of_param thy c
   159    of SOME class => (case Sign.const_typargs thy c_ty
   160        of [Type (tyco, _)] => (case Symtab.lookup
   161            ((the o Symtab.lookup (fst (InstData.get thy))) c) tyco
   162              of SOME (c, _) => c
   163               | NONE => c)
   164         | [_] => c)
   165     | NONE => c;
   166 
   167 val param_const = Symtab.lookup o snd o InstData.get;
   168 
   169 fun add_inst_def (class, tyco) (c, ty) thy =
   170   let
   171     val tyco_base = Sign.base_name tyco;
   172     val name_inst = Sign.base_name class ^ "_" ^ tyco_base ^ "_inst";
   173     val c_inst_base = Sign.base_name c ^ "_" ^ tyco_base;
   174   in
   175     thy
   176     |> Sign.sticky_prefix name_inst
   177     |> Sign.declare_const [] (c_inst_base, ty, NoSyn)
   178     |-> (fn const as Const (c_inst, _) =>
   179       PureThy.add_defs_i false
   180         [((Thm.def_name c_inst_base, Logic.mk_equals (const, Const (c, ty))), [])]
   181       #-> (fn [thm] => add_inst (c, tyco) (c_inst, Thm.symmetric thm)))
   182     |> Sign.restore_naming thy
   183   end;
   184 
   185 fun add_inst_def' (class, tyco) (c, ty) thy =
   186   if case Symtab.lookup (fst (InstData.get thy)) c
   187    of NONE => true
   188     | SOME tab => is_none (Symtab.lookup tab tyco)
   189   then add_inst_def (class, tyco) (c, Logic.unvarifyT ty) thy
   190   else thy;
   191 
   192 fun add_def ((class, tyco), ((name, prop), atts)) thy =
   193   let
   194     val ((lhs as Const (c, ty), args), rhs) =
   195       (apfst Term.strip_comb o Logic.dest_equals) prop;
   196     fun (*add_inst' def ([], (Const (c_inst, ty))) =
   197           if forall (fn TFree _ => true | _ => false) (Sign.const_typargs thy (c_inst, ty))
   198           then add_inst (c, tyco) (c_inst, def)
   199           else add_inst_def (class, tyco) (c, ty)
   200       |*) add_inst' _ t = add_inst_def (class, tyco) (c, ty);
   201   in
   202     thy
   203     |> PureThy.add_defs_i true [((name, prop), map (Attrib.attribute_i thy) atts)]
   204     |-> (fn [def] => add_inst' def (args, rhs) #> pair def)
   205   end;
   206 
   207 
   208 (** instances with implicit parameter handling **)
   209 
   210 local
   211 
   212 fun gen_read_def thy prep_att parse_prop ((raw_name, raw_atts), raw_t) =
   213   let
   214     val ctxt = ProofContext.init thy;
   215     val t = parse_prop ctxt raw_t |> Syntax.check_prop ctxt;
   216     val ((c, ty), _) = Sign.cert_def ctxt t;
   217     val atts = map (prep_att thy) raw_atts;
   218     val insts = Consts.typargs (Sign.consts_of thy) (c, ty);
   219     val name = case raw_name
   220      of "" => NONE
   221       | _ => SOME raw_name;
   222   in (c, (insts, ((name, t), atts))) end;
   223 
   224 fun read_def_cmd thy = gen_read_def thy Attrib.intern_src Syntax.parse_prop;
   225 fun read_def thy = gen_read_def thy (K I) (K I);
   226 
   227 fun gen_instance prep_arity read_def do_proof raw_arities raw_defs after_qed theory =
   228   let
   229     val arities = map (prep_arity theory) raw_arities;
   230     val _ = if null arities then error "At least one arity must be given" else ();
   231     val _ = case (duplicates (op =) o map #1) arities
   232      of [] => ()
   233       | dupl_tycos => error ("Type constructors occur more than once in arities: "
   234           ^ commas_quote dupl_tycos);
   235     fun get_remove_constraint c thy =
   236       let
   237         val ty = Sign.the_const_constraint thy c;
   238       in
   239         thy
   240         |> Sign.add_const_constraint (c, NONE)
   241         |> pair (c, Logic.unvarifyT ty)
   242       end;
   243     fun get_consts_class tyco ty class =
   244       let
   245         val cs = (these o try (#params o AxClass.get_info theory)) class;
   246         val subst_ty = map_type_tfree (K ty);
   247       in
   248         map (fn (c, ty) => (c, ((class, tyco), subst_ty ty))) cs
   249       end;
   250     fun get_consts_sort (tyco, asorts, sort) =
   251       let
   252         val ty = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort))
   253           (Name.names Name.context Name.aT asorts))
   254       in maps (get_consts_class tyco ty) (Sign.complete_sort theory sort) end;
   255     val cs = maps get_consts_sort arities;
   256     fun mk_typnorm thy (ty, ty_sc) =
   257       case try (Sign.typ_match thy (Logic.varifyT ty_sc, ty)) Vartab.empty
   258        of SOME env => SOME (Logic.varifyT #> Envir.typ_subst_TVars env #> Logic.unvarifyT)
   259         | NONE => NONE;
   260     fun read_defs defs cs thy_read =
   261       let
   262         fun read raw_def cs =
   263           let
   264             val (c, (inst, ((name_opt, t), atts))) = read_def thy_read raw_def;
   265             val ty = Consts.instance (Sign.consts_of thy_read) (c, inst);
   266             val ((class, tyco), ty') = case AList.lookup (op =) cs c
   267              of NONE => error ("Illegal definition for constant " ^ quote c)
   268               | SOME class_ty => class_ty;
   269             val name = case name_opt
   270              of NONE => Thm.def_name (Logic.name_arity (tyco, [], c))
   271               | SOME name => name;
   272             val t' = case mk_typnorm thy_read (ty', ty)
   273              of NONE => error ("Illegal definition for constant " ^
   274                   quote (c ^ "::" ^ setmp show_sorts true
   275                     (Sign.string_of_typ thy_read) ty))
   276               | SOME norm => map_types norm t
   277           in (((class, tyco), ((name, t'), atts)), AList.delete (op =) c cs) end;
   278       in fold_map read defs cs end;
   279     val (defs, other_cs) = read_defs raw_defs cs
   280       (fold Sign.primitive_arity arities (Theory.copy theory));
   281     fun after_qed' cs defs =
   282       fold Sign.add_const_constraint (map (apsnd SOME) cs)
   283       #> after_qed defs;
   284   in
   285     theory
   286     |> fold_map get_remove_constraint (map fst cs |> distinct (op =))
   287     ||>> fold_map add_def defs
   288     ||> fold (fn (c, ((class, tyco), ty)) => add_inst_def' (class, tyco) (c, ty)) other_cs
   289     |-> (fn (cs, defs) => do_proof (after_qed' cs defs) arities defs)
   290   end;
   291 
   292 fun tactic_proof tac f arities defs =
   293   fold (fn arity => AxClass.prove_arity arity tac) arities
   294   #> f
   295   #> pair defs;
   296 
   297 in
   298 
   299 val instance = gen_instance Sign.cert_arity read_def
   300   (fn f => fn arities => fn defs => instance_arity f arities);
   301 val instance_cmd = gen_instance Sign.read_arity read_def_cmd
   302   (fn f => fn arities => fn defs => instance_arity f arities);
   303 fun prove_instance tac arities defs =
   304   gen_instance Sign.cert_arity read_def
   305     (tactic_proof tac) arities defs (K I);
   306 
   307 end; (*local*)
   308 
   309 
   310 
   311 (** class data **)
   312 
   313 datatype class_data = ClassData of {
   314   locale: string,
   315   consts: (string * string) list
   316     (*locale parameter ~> constant name*),
   317   local_sort: sort,
   318   inst: typ Symtab.table * term Symtab.table
   319     (*canonical interpretation*),
   320   intro: thm,
   321   defs: thm list,
   322   operations: (string * (term * (typ * int))) list
   323     (*constant name ~> (locale term, (constant constraint, instantiaton index of class typ))*),
   324   operations_rev: (string * string) list
   325     (*locale operation ~> constant name*)
   326 };
   327 
   328 fun rep_class_data (ClassData d) = d;
   329 fun mk_class_data ((locale, consts, local_sort, inst, intro),
   330     (defs, operations, operations_rev)) =
   331   ClassData { locale = locale, consts = consts, local_sort = local_sort, inst = inst,
   332     intro = intro, defs = defs, operations = operations,
   333     operations_rev = operations_rev };
   334 fun map_class_data f (ClassData { locale, consts, local_sort, inst, intro,
   335     defs, operations, operations_rev }) =
   336   mk_class_data (f ((locale, consts, local_sort, inst, intro),
   337     (defs, operations, operations_rev)));
   338 fun merge_class_data _ (ClassData { locale = locale, consts = consts,
   339     local_sort = local_sort, inst = inst, intro = intro,
   340     defs = defs1, operations = operations1, operations_rev = operations_rev1 },
   341   ClassData { locale = _, consts = _, local_sort = _, inst = _, intro = _,
   342     defs = defs2, operations = operations2, operations_rev = operations_rev2 }) =
   343   mk_class_data ((locale, consts, local_sort, inst, intro),
   344     (Thm.merge_thms (defs1, defs2),
   345       AList.merge (op =) (K true) (operations1, operations2),
   346       AList.merge (op =) (K true) (operations_rev1, operations_rev2)));
   347 
   348 fun merge_pair f1 f2 ((x1, y1), (x2, y2)) = (f1 (x1, x2), f2 (y1, y2));
   349 
   350 structure ClassData = TheoryDataFun
   351 (
   352   type T = class_data Graph.T * class Symtab.table
   353     (*locale name ~> class name*);
   354   val empty = (Graph.empty, Symtab.empty);
   355   val copy = I;
   356   val extend = I;
   357   fun merge _ = merge_pair (Graph.join merge_class_data) (Symtab.merge (K true));
   358 );
   359 
   360 
   361 (* queries *)
   362 
   363 val is_class = Symtab.defined o snd o ClassData.get;
   364 
   365 val lookup_class_data = Option.map rep_class_data oo try o Graph.get_node
   366   o fst o ClassData.get;
   367 
   368 fun the_class_data thy class = case lookup_class_data thy class
   369  of NONE => error ("Undeclared class " ^ quote class)
   370   | SOME data => data;
   371 
   372 val ancestry = Graph.all_succs o fst o ClassData.get;
   373 
   374 fun these_params thy =
   375   let
   376     fun params class =
   377       let
   378         val const_typs = (#params o AxClass.get_info thy) class;
   379         val const_names = (#consts o the_class_data thy) class;
   380       in
   381         (map o apsnd) (fn c => (c, (the o AList.lookup (op =) const_typs) c)) const_names
   382       end;
   383   in maps params o ancestry thy end;
   384 
   385 fun these_defs thy = maps (these o Option.map #defs o lookup_class_data thy) o ancestry thy;
   386 
   387 fun these_intros thy =
   388   Graph.fold (fn (_, (data, _)) => insert Thm.eq_thm ((#intro o rep_class_data) data))
   389     ((fst o ClassData.get) thy) [];
   390 
   391 fun these_operations thy =
   392   maps (#operations o the_class_data thy) o ancestry thy;
   393 
   394 fun these_operations_rev thy =
   395   maps (#operations_rev o the_class_data thy) o ancestry thy;
   396 
   397 fun local_operation thy = AList.lookup (op =) o these_operations thy;
   398 
   399 fun global_operation thy = AList.lookup (op =) o these_operations_rev thy;
   400 
   401 fun sups_local_sort thy sort =
   402   let
   403     val sups = filter (is_some o lookup_class_data thy) sort
   404       |> Sign.minimize_sort thy;
   405     val local_sort = case sups
   406      of sup :: _ => #local_sort (the_class_data thy sup)
   407       | [] => sort;
   408   in (sups, local_sort) end;
   409 
   410 fun print_classes thy =
   411   let
   412     val ctxt = ProofContext.init thy;
   413 
   414     val algebra = Sign.classes_of thy;
   415     val arities =
   416       Symtab.empty
   417       |> Symtab.fold (fn (tyco, arities) => fold (fn (class, _) =>
   418            Symtab.map_default (class, []) (insert (op =) tyco)) arities)
   419              ((#arities o Sorts.rep_algebra) algebra);
   420     val the_arities = these o Symtab.lookup arities;
   421     fun mk_arity class tyco =
   422       let
   423         val Ss = Sorts.mg_domain algebra tyco [class];
   424       in Syntax.pretty_arity ctxt (tyco, Ss, [class]) end;
   425     fun mk_param (c, ty) = Pretty.str (Sign.extern_const thy c ^ " :: "
   426       ^ setmp show_sorts false (Syntax.string_of_typ ctxt o Type.strip_sorts) ty);
   427     fun mk_entry class = (Pretty.block o Pretty.fbreaks o map_filter I) [
   428       (SOME o Pretty.str) ("class " ^ class ^ ":"),
   429       (SOME o Pretty.block) [Pretty.str "supersort: ",
   430         (Syntax.pretty_sort ctxt o Sign.minimize_sort thy o Sign.super_classes thy) class],
   431       Option.map (Pretty.str o prefix "locale: " o #locale) (lookup_class_data thy class),
   432       ((fn [] => NONE | ps => (SOME o Pretty.block o Pretty.fbreaks) (Pretty.str "parameters:" :: ps)) o map mk_param
   433         o these o Option.map #params o try (AxClass.get_info thy)) class,
   434       (SOME o Pretty.block o Pretty.breaks) [
   435         Pretty.str "instances:",
   436         Pretty.list "" "" (map (mk_arity class) (the_arities class))
   437       ]
   438     ]
   439   in
   440     (Pretty.writeln o Pretty.chunks o separate (Pretty.str "")
   441       o map mk_entry o Sorts.all_classes) algebra
   442   end;
   443 
   444 
   445 (* updaters *)
   446 
   447 fun add_class_data ((class, superclasses), (locale, cs, local_sort, inst, intro)) =
   448   let
   449     val operations = map (fn (v_ty, (c, ty)) => (c, (Free v_ty, (ty, 0)))) cs;
   450     val cs = (map o pairself) fst cs;
   451     val add_class = Graph.new_node (class, mk_class_data ((locale,
   452           cs, local_sort, inst, intro),
   453             ([], operations, [])))
   454       #> fold (curry Graph.add_edge class) superclasses;
   455     val add_locale = Symtab.update (locale, class);
   456   in
   457     ClassData.map (fn (gr, tab) => (add_class gr, add_locale tab))
   458   end;
   459 
   460 fun register_operation class (entry, some_def) =
   461   (ClassData.map o apfst o Graph.map_node class o map_class_data o apsnd)
   462     (fn (defs, operations, operations_rev) =>
   463       (case some_def of NONE => defs | SOME def => def :: defs,
   464         entry :: operations, (*FIXME*)operations_rev));
   465 
   466 
   467 (** rule calculation, tactics and methods **)
   468 
   469 val class_prefix = Logic.const_of_class o Sign.base_name;
   470 
   471 fun class_intro thy locale class sups =
   472   let
   473     fun class_elim class =
   474       case (#axioms o AxClass.get_info thy) class
   475        of [thm] => SOME (Drule.unconstrainTs thm)
   476         | [] => NONE;
   477     val pred_intro = case Locale.intros thy locale
   478      of ([ax_intro], [intro]) => intro |> OF_LAST ax_intro |> SOME
   479       | ([intro], []) => SOME intro
   480       | ([], [intro]) => SOME intro
   481       | _ => NONE;
   482     val pred_intro' = pred_intro
   483       |> Option.map (fn intro => intro OF map_filter class_elim sups);
   484     val class_intro = (#intro o AxClass.get_info thy) class;
   485     val raw_intro = case pred_intro'
   486      of SOME pred_intro => class_intro |> OF_LAST pred_intro
   487       | NONE => class_intro;
   488     val sort = Sign.super_classes thy class;
   489     val typ = TVar ((Name.aT, 0), sort);
   490     val defs = these_defs thy sups;
   491   in
   492     raw_intro
   493     |> Drule.instantiate' [SOME (Thm.ctyp_of thy typ)] []
   494     |> strip_all_ofclass thy sort
   495     |> Thm.strip_shyps
   496     |> MetaSimplifier.rewrite_rule defs
   497     |> Drule.unconstrainTs
   498   end;
   499 
   500 fun class_interpretation class facts defs thy =
   501   let
   502     val inst = #inst (the_class_data thy class);
   503     val tac = ALLGOALS (ProofContext.fact_tac facts);
   504   in
   505     prove_interpretation tac ((false, class_prefix class), []) (Locale.Locale class)
   506       (inst, defs) thy
   507   end;
   508 
   509 fun interpretation_in_rule thy (class1, class2) =
   510   let
   511     val ctxt = ProofContext.init thy;
   512     fun mk_axioms class =
   513       let
   514         val { locale, inst = (_, insttab), ... } = the_class_data thy class;
   515       in
   516         Locale.global_asms_of thy locale
   517         |> maps snd
   518         |> (map o map_aterms) (fn Free (s, _) => (the o Symtab.lookup insttab) s | t => t)
   519         |> (map o map_types o map_atyps) (fn TFree _ => TFree (Name.aT, [class1]) | T => T)
   520         |> map (ObjectLogic.ensure_propT thy)
   521       end;
   522     val (prems, concls) = pairself mk_axioms (class1, class2);
   523   in
   524     Goal.prove_global thy [] prems (Logic.mk_conjunction_list concls)
   525       (Locale.intro_locales_tac true ctxt)
   526   end;
   527 
   528 fun intro_classes_tac facts st =
   529   let
   530     val thy = Thm.theory_of_thm st;
   531     val classes = Sign.all_classes thy;
   532     val class_trivs = map (Thm.class_triv thy) classes;
   533     val class_intros = these_intros thy;
   534     val axclass_intros = map_filter (try (#intro o AxClass.get_info thy)) classes;
   535   in
   536     (ALLGOALS (Method.insert_tac facts THEN'
   537       REPEAT_ALL_NEW (resolve_tac (class_trivs @ class_intros @ axclass_intros)))
   538     THEN Tactic.distinct_subgoals_tac) st
   539   end;
   540 
   541 fun default_intro_classes_tac [] = intro_classes_tac []
   542   | default_intro_classes_tac _ = no_tac;
   543 
   544 fun default_tac rules ctxt facts =
   545   HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
   546     default_intro_classes_tac facts;
   547 
   548 val _ = Context.add_setup (Method.add_methods
   549  [("intro_classes", Method.no_args (Method.METHOD intro_classes_tac),
   550     "back-chain introduction rules of classes"),
   551   ("default", Method.thms_ctxt_args (Method.METHOD oo default_tac),
   552     "apply some intro/elim rule")]);
   553 
   554 
   555 (** classes and class target **)
   556 
   557 (* class context syntax *)
   558 
   559 fun internal_remove_constraint local_sort (c, (_, (ty, typidx))) ctxt =
   560   let
   561     val consts = ProofContext.consts_of ctxt;
   562     val typargs = Consts.typargs consts (c, ty);
   563     val typargs' = nth_map typidx (K (TVar ((Name.aT, 0), local_sort))) typargs;
   564     val ty' = Consts.instance consts (c, typargs');
   565   in ProofContext.add_const_constraint (c, SOME ty') ctxt end;
   566 
   567 fun remove_constraint class c ctxt =
   568   let
   569     val thy = ProofContext.theory_of ctxt;
   570     val SOME entry = local_operation thy [class] c;
   571   in
   572     internal_remove_constraint
   573       ((#local_sort o the_class_data thy) class) (c, entry) ctxt
   574   end;
   575 
   576 fun sort_term_check sups local_sort ts ctxt =
   577   let
   578     val thy = ProofContext.theory_of ctxt;
   579     val local_operation = local_operation thy sups;
   580     val constraints = these_operations thy sups |> (map o apsnd) (fst o snd);
   581     val consts = ProofContext.consts_of ctxt;
   582     fun check_typ (c, ty) (t', idx) = case nth (Consts.typargs consts (c, ty)) idx
   583      of TFree (v, _) => if v = Name.aT
   584           then apfst (AList.update (op =) ((c, ty), t')) else I
   585       | TVar (vi, _) => if TypeInfer.is_param vi
   586           then apfst (AList.update (op =) ((c, ty), t'))
   587             #> apsnd (insert (op =) vi) else I
   588       | _ => I;
   589     fun add_const (Const (c, ty)) = (case local_operation c
   590          of SOME (t', (_, idx)) => check_typ (c, ty) (t', idx)
   591           | NONE => I)
   592       | add_const _ = I;
   593     val (cs, typarams) = (fold o fold_aterms) add_const ts ([], []);
   594     val ts' = map (map_aterms
   595         (fn t as Const (c, ty) => the_default t (AList.lookup (op =) cs (c, ty)) | t => t)
   596       #> (map_types o map_type_tvar) (fn var as (vi, _) => if member (op =) typarams vi
   597            then TFree (Name.aT, local_sort) else TVar var)) ts;
   598     val ctxt' = fold (ProofContext.add_const_constraint o apsnd SOME) constraints ctxt;
   599   in (ts', ctxt') end;
   600 
   601 val uncheck = ref false;
   602 
   603 fun sort_term_uncheck sups ts ctxt =
   604   let
   605     val thy = ProofContext.theory_of ctxt;
   606     val global_param = AList.lookup (op =) (these_params thy sups) #> Option.map fst;
   607     val global_operation = global_operation thy sups;
   608     fun globalize (t as Free (v, ty)) = (case global_param v
   609          of SOME c => Const (c, ty)
   610           | NONE => t)
   611       | globalize (t as Const (c, ty)) = (case global_operation c
   612          of SOME c => Const (c, ty)
   613           | NONE => t)
   614       | globalize t = t;
   615     val ts' = if ! uncheck then (map o map_aterms) globalize ts else ts;
   616   in (ts', ctxt) end;
   617 
   618 fun init_class_ctxt sups local_sort ctxt =
   619   let
   620     val operations = these_operations (ProofContext.theory_of ctxt) sups;
   621   in
   622     ctxt
   623     |> Variable.declare_term
   624         (Logic.mk_type (TFree (Name.aT, local_sort)))
   625     |> fold (internal_remove_constraint local_sort) operations
   626     |> Context.proof_map (Syntax.add_term_check 50 "class"
   627         (sort_term_check sups local_sort)
   628         #> Syntax.add_term_uncheck 50 "class"
   629           (sort_term_uncheck sups))
   630   end;
   631 
   632 fun init class ctxt =
   633   init_class_ctxt [class]
   634     ((#local_sort o the_class_data (ProofContext.theory_of ctxt)) class) ctxt;
   635 
   636 
   637 (* class definition *)
   638 
   639 local
   640 
   641 fun gen_class_spec prep_class prep_expr process_expr thy raw_supclasses raw_includes_elems =
   642   let
   643     val supclasses = map (prep_class thy) raw_supclasses;
   644     val (sups, local_sort) = sups_local_sort thy supclasses;
   645     val supsort = Sign.minimize_sort thy supclasses;
   646     val suplocales = map (Locale.Locale o #locale o the_class_data thy) sups;
   647     val (raw_elems, includes) = fold_rev (fn Locale.Elem e => apfst (cons e)
   648       | Locale.Expr i => apsnd (cons (prep_expr thy i))) raw_includes_elems ([], []);
   649     val supexpr = Locale.Merge suplocales;
   650     val supparams = (map fst o Locale.parameters_of_expr thy) supexpr;
   651     val supconsts = AList.make (the o AList.lookup (op =) (these_params thy sups))
   652       (map fst supparams);
   653     val mergeexpr = Locale.Merge (suplocales @ includes);
   654     val constrain = Element.Constrains ((map o apsnd o map_atyps)
   655       (fn TFree (_, sort) => TFree (Name.aT, sort)) supparams);
   656   in
   657     ProofContext.init thy
   658     |> Locale.cert_expr supexpr [constrain]
   659     |> snd
   660     |> init_class_ctxt sups local_sort
   661     |> process_expr Locale.empty raw_elems
   662     |> fst
   663     |> (fn elems => ((((sups, supconsts), (supsort, local_sort, mergeexpr)),
   664           (*FIXME*) if null includes then constrain :: elems else elems)))
   665   end;
   666 
   667 val read_class_spec = gen_class_spec Sign.intern_class Locale.intern_expr Locale.read_expr;
   668 val check_class_spec = gen_class_spec (K I) (K I) Locale.cert_expr;
   669 
   670 fun define_class_params (name, raw_superclasses) raw_consts raw_dep_axioms other_consts thy =
   671   let
   672     val superclasses = map (Sign.certify_class thy) raw_superclasses;
   673     val consts = (map o apfst o apsnd) (Sign.certify_typ thy) raw_consts;
   674     fun add_const ((c, ty), syn) = Sign.declare_const [] (c, ty, syn) #>> Term.dest_Const;
   675     fun mk_axioms cs thy =
   676       raw_dep_axioms thy cs
   677       |> (map o apsnd o map) (Sign.cert_prop thy)
   678       |> rpair thy;
   679     fun constrain_typs class = (map o apsnd o Term.map_type_tfree)
   680       (fn (v, _) => TFree (v, [class]))
   681   in
   682     thy
   683     |> Sign.add_path (Logic.const_of_class name)
   684     |> fold_map add_const consts
   685     ||> Sign.restore_naming thy
   686     |-> (fn cs => mk_axioms cs
   687     #-> (fn axioms_prop => AxClass.define_class (name, superclasses)
   688            (map fst cs @ other_consts) axioms_prop
   689     #-> (fn class => `(fn _ => constrain_typs class cs)
   690     #-> (fn cs' => `(fn thy => AxClass.get_info thy class)
   691     #-> (fn {axioms, ...} => fold (Sign.add_const_constraint o apsnd SOME) cs'
   692     #> pair (class, (cs', axioms)))))))
   693   end;
   694 
   695 fun gen_class prep_spec prep_param bname
   696     raw_supclasses raw_includes_elems raw_other_consts thy =
   697   let
   698     val (((sups, supconsts), (supsort, local_sort, mergeexpr)), elems) =
   699       prep_spec thy raw_supclasses raw_includes_elems;
   700     val other_consts = map (tap (Sign.the_const_type thy) o prep_param thy) raw_other_consts;
   701     fun mk_instT class = Symtab.empty
   702       |> Symtab.update (Name.aT, TFree (Name.aT, [class]));
   703     fun mk_inst class param_names cs =
   704       Symtab.empty
   705       |> fold2 (fn v => fn (c, ty) => Symtab.update (v, Const
   706            (c, Term.map_type_tfree (fn (v, _) => TFree (v, [class])) ty))) param_names cs;
   707     fun extract_params thy name_locale =
   708       let
   709         val params = Locale.parameters_of thy name_locale;
   710         val _ = if Sign.subsort thy (supsort, local_sort) then () else error
   711           ("Sort " ^ Sign.string_of_sort thy local_sort
   712             ^ " is less general than permitted least general sort "
   713             ^ Sign.string_of_sort thy supsort);
   714       in
   715         (map fst params, params
   716         |> (map o apfst o apsnd o Term.map_type_tfree) (K (TFree (Name.aT, local_sort)))
   717         |> (map o apsnd) (fork_mixfix true true #> fst)
   718         |> chop (length supconsts)
   719         |> snd)
   720       end;
   721     fun extract_assumes name_locale params thy cs =
   722       let
   723         val consts = supconsts @ (map (fst o fst) params ~~ cs);
   724         fun subst (Free (c, ty)) =
   725               Const ((fst o the o AList.lookup (op =) consts) c, ty)
   726           | subst t = t;
   727         fun prep_asm ((name, atts), ts) =
   728           ((Sign.base_name name, map (Attrib.attribute_i thy) atts),
   729             (map o map_aterms) subst ts);
   730       in
   731         Locale.global_asms_of thy name_locale
   732         |> map prep_asm
   733       end;
   734     fun note_intro name_axclass class_intro =
   735       PureThy.note_thmss_qualified "" (class_prefix name_axclass)
   736         [(("intro", []), [([class_intro], [])])]
   737       #> snd
   738   in
   739     thy
   740     |> Locale.add_locale_i (SOME "") bname mergeexpr elems
   741     |-> (fn name_locale => ProofContext.theory_result (
   742       `(fn thy => extract_params thy name_locale)
   743       #-> (fn (globals, params) =>
   744         define_class_params (bname, supsort) params
   745           (extract_assumes name_locale params) other_consts
   746       #-> (fn (name_axclass, (consts, axioms)) =>
   747         `(fn thy => class_intro thy name_locale name_axclass sups)
   748       #-> (fn class_intro =>
   749         add_class_data ((name_axclass, sups),
   750           (name_locale, map fst params ~~ consts, local_sort,
   751             (mk_instT name_axclass, mk_inst name_axclass (map fst globals)
   752               (map snd supconsts @ consts)), class_intro))
   753       #> note_intro name_axclass class_intro
   754       #> class_interpretation name_axclass axioms []
   755       #> pair name_axclass
   756       )))))
   757   end;
   758 
   759 in
   760 
   761 val class_cmd = gen_class read_class_spec ((#1 o Term.dest_Const) oo Sign.read_const);
   762 val class = gen_class check_class_spec (K I);
   763 
   764 end; (*local*)
   765 
   766 
   767 (* definition in class target *)
   768 
   769 fun export_fixes thy class =
   770   let
   771     val cs = these_params thy [class];
   772     fun subst_aterm (t as Free (v, ty)) = (case AList.lookup (op =) cs v
   773          of SOME (c, _) => Const (c, ty)
   774           | NONE => t)
   775       | subst_aterm t = t;
   776   in Term.map_aterms subst_aterm end;
   777 
   778 fun mk_operation_entry thy (c, rhs) =
   779   let
   780     val ty = Logic.unvarifyT (Sign.the_const_constraint thy c);
   781     val typargs = Sign.const_typargs thy (c, ty);
   782     val typidx = find_index (fn TFree (w, _) => Name.aT = w | _ => false) typargs;
   783   in (c, (rhs, (ty, typidx))) end;
   784 
   785 fun add_const_in_class class ((c, mx), rhs) thy =
   786   let
   787     val prfx = class_prefix class;
   788     val thy' = thy |> Sign.add_path prfx;
   789 
   790     val rhs' = export_fixes thy' class rhs;
   791     val subst_typ = Term.map_type_tfree (fn var as (w, sort) =>
   792       if w = Name.aT then TFree (w, [class]) else TFree var);
   793     val ty' = Term.fastype_of rhs';
   794     val ty'' = subst_typ ty';
   795     val c' = Sign.full_name thy' c;
   796     val def = (c, Logic.mk_equals (Const (c', ty'), rhs'));
   797     val (mx', _) = fork_mixfix true true mx;
   798     fun interpret def thy =
   799       let
   800         val def' = symmetric def;
   801         val def_eq = (map_types Logic.unvarifyT o Thm.prop_of) def';
   802       in
   803         thy
   804         |> class_interpretation class [def'] [def_eq]
   805         |> Sign.add_const_constraint (c', SOME ty'')
   806         |> `(fn thy => mk_operation_entry thy (c', rhs))
   807         |-> (fn entry => register_operation class (entry, SOME def'))
   808       end;
   809   in
   810     thy'
   811     |> Sign.declare_const [] (c, ty', mx') |> snd
   812     |> Sign.parent_path
   813     |> Sign.sticky_prefix prfx
   814     |> PureThy.add_defs_i false [(def, [])]
   815     |-> (fn [def] => interpret def)
   816     |> Sign.restore_naming thy
   817     |> pair c'
   818   end;
   819 
   820 
   821 (* abbreviation in class target *)
   822 
   823 fun add_abbrev_in_class class prmode ((c, mx), rhs) thy =
   824   let
   825     val prfx = class_prefix class;
   826     val naming = Sign.naming_of thy |> NameSpace.add_path prfx |> NameSpace.add_path prfx; (* FIXME !? *)
   827     val c' = NameSpace.full naming c;
   828     val rhs' = export_fixes thy class rhs;
   829     val ty' = Term.fastype_of rhs';
   830     val entry = mk_operation_entry thy (c', rhs);
   831   in
   832     thy
   833     |> Sign.notation true prmode [(Const (c', ty'), mx)]
   834     |> register_operation class (entry, NONE)
   835     |> pair c'
   836   end;
   837 
   838 end;