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