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