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