src/Pure/Isar/class.ML
author haftmann
Mon Aug 27 11:34:17 2007 +0200 (2007-08-27)
changeset 24435 cabf8cd38258
parent 24423 ae9cd0e92423
child 24589 d3fca349736c
permissions -rw-r--r--
introduces params_of_sort
     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 -> string option -> mixfix -> mixfix * mixfix
    11 
    12   val axclass_cmd: bstring * xstring list
    13     -> ((bstring * Attrib.src list) * string list) list -> theory -> class * theory
    14   val class: bstring -> class list -> Element.context_i Locale.element list
    15     -> string list -> theory -> string * Proof.context
    16   val class_cmd: bstring -> string list -> Element.context Locale.element list
    17     -> string list -> theory -> string * Proof.context
    18   val class_of_locale: theory -> string -> class option
    19   val add_const_in_class: string -> (string * term) * Syntax.mixfix
    20     -> theory -> theory
    21 
    22   val instance_arity: arity list -> ((bstring * Attrib.src list) * term) list
    23     -> (thm list -> theory -> theory)
    24     -> theory -> Proof.state
    25   val instance_arity_cmd: (bstring * string list * string) list
    26     -> ((bstring * Attrib.src list) * string) list
    27     -> (thm list -> theory -> theory)
    28     -> theory -> Proof.state
    29   val prove_instance_arity: tactic -> arity list
    30     -> ((bstring * Attrib.src list) * term) list
    31     -> theory -> thm list * theory
    32   val unoverload: theory -> conv
    33   val overload: theory -> conv
    34   val unoverload_const: theory -> string * typ -> string
    35   val inst_const: theory -> string * string -> string
    36   val param_const: theory -> string -> (string * string) option
    37   val params_of_sort: theory -> sort -> (string * (string * typ)) list
    38   val intro_classes_tac: thm list -> tactic
    39   val default_intro_classes_tac: thm list -> tactic
    40 
    41   val instance_class: class * class -> theory -> Proof.state
    42   val instance_class_cmd: string * string -> theory -> Proof.state
    43   val instance_sort: class * sort -> theory -> Proof.state
    44   val instance_sort_cmd: string * string -> theory -> Proof.state
    45   val prove_instance_sort: tactic -> class * sort -> theory -> theory
    46 
    47   val print_classes: theory -> unit
    48 end;
    49 
    50 structure Class : CLASS =
    51 struct
    52 
    53 (** auxiliary **)
    54 
    55 fun fork_mixfix is_loc some_class mx =
    56   let
    57     val mx' = Syntax.unlocalize_mixfix mx;
    58     val mx_global = if is_some some_class orelse (is_loc andalso mx = mx')
    59       then NoSyn else mx';
    60     val mx_local = if is_loc then mx else NoSyn;
    61   in (mx_global, mx_local) end;
    62 
    63 fun axclass_cmd (class, raw_superclasses) raw_specs thy =
    64   let
    65     val ctxt = ProofContext.init thy;
    66     val superclasses = map (Sign.read_class thy) raw_superclasses;
    67     val name_atts = map ((apsnd o map) (Attrib.attribute thy) o fst) raw_specs;
    68     val axiomss = ProofContext.read_propp (ctxt, map (map (rpair []) o snd) raw_specs)
    69       |> snd
    70       |> (map o map) fst;
    71   in AxClass.define_class (class, superclasses) [] (name_atts ~~ axiomss) thy end;
    72 
    73 
    74 (** axclasses with implicit parameter handling **)
    75 
    76 (* axclass instances *)
    77 
    78 local
    79 
    80 fun gen_instance mk_prop add_thm after_qed insts thy =
    81   let
    82     fun after_qed' results =
    83       ProofContext.theory ((fold o fold) add_thm results #> after_qed);
    84   in
    85     thy
    86     |> ProofContext.init
    87     |> Proof.theorem_i NONE after_qed' ((map (fn t => [(t, [])]) o maps (mk_prop thy)) insts)
    88   end;
    89 
    90 in
    91 
    92 val axclass_instance_arity =
    93   gen_instance (Logic.mk_arities oo Sign.cert_arity) AxClass.add_arity;
    94 val axclass_instance_sort =
    95   gen_instance (single oo (Logic.mk_classrel oo AxClass.cert_classrel))
    96     AxClass.add_classrel I o single;
    97 
    98 end; (*local*)
    99 
   100 
   101 (* introducing axclasses with implicit parameter handling *)
   102 
   103 fun axclass_params (name, raw_superclasses) raw_consts raw_dep_axioms other_consts thy =
   104   let
   105     val superclasses = map (Sign.certify_class thy) raw_superclasses;
   106     val consts = (map o apfst o apsnd) (Sign.certify_typ thy) raw_consts;
   107     val prefix = Logic.const_of_class name;
   108     fun mk_const_name c = NameSpace.map_base (NameSpace.append prefix)
   109       (Sign.full_name thy c);
   110     fun add_const ((c, ty), syn) =
   111       Sign.add_consts_authentic [(c, ty, syn)]
   112       #> pair (mk_const_name c, ty);
   113     fun mk_axioms cs thy =
   114       raw_dep_axioms thy cs
   115       |> (map o apsnd o map) (Sign.cert_prop thy)
   116       |> rpair thy;
   117     fun add_constraint class (c, ty) =
   118       Sign.add_const_constraint_i (c, SOME
   119         (Term.map_type_tfree (fn (v, _) => TFree (v, [class])) ty));
   120   in
   121     thy
   122     |> Theory.add_path prefix
   123     |> fold_map add_const consts
   124     ||> Theory.restore_naming thy
   125     |-> (fn cs => mk_axioms cs
   126     #-> (fn axioms_prop => AxClass.define_class (name, superclasses)
   127            (map fst cs @ other_consts) axioms_prop
   128     #-> (fn class => `(fn thy => AxClass.get_definition thy class)
   129     #-> (fn {intro, axioms, ...} => fold (add_constraint class) cs
   130     #> pair (class, ((intro, (map Thm.prop_of axioms, axioms)), cs))))))
   131   end;
   132 
   133 
   134 (* explicit constants for overloaded definitions *)
   135 
   136 structure InstData = TheoryDataFun
   137 (
   138   type T = (string * thm) Symtab.table Symtab.table * (string * string) Symtab.table;
   139     (*constant name ~> type constructor ~> (constant name, equation),
   140         constant name ~> (constant name, type constructor)*)
   141   val empty = (Symtab.empty, Symtab.empty);
   142   val copy = I;
   143   val extend = I;
   144   fun merge _ ((taba1, tabb1), (taba2, tabb2)) =
   145     (Symtab.join (K (Symtab.merge (K true))) (taba1, taba2),
   146       Symtab.merge (K true) (tabb1, tabb2));
   147 );
   148 
   149 fun inst_thms f thy =
   150   (Symtab.fold (Symtab.fold (cons o f o snd o snd) o snd) o fst) (InstData.get thy) [];
   151 fun add_inst (c, tyco) inst = (InstData.map o apfst o Symtab.map_default (c, Symtab.empty))
   152   (Symtab.update_new (tyco, inst))
   153   #> (InstData.map o apsnd) (Symtab.update_new (fst inst, (c, tyco)));
   154 
   155 fun unoverload thy thm = MetaSimplifier.rewrite false (inst_thms I thy) thm;
   156 fun overload thy thm = MetaSimplifier.rewrite false (inst_thms symmetric thy) thm;
   157 
   158 fun inst_const thy (c, tyco) =
   159   (fst o the o Symtab.lookup ((the o Symtab.lookup (fst (InstData.get thy))) c)) tyco;
   160 fun unoverload_const thy (c_ty as (c, _)) =
   161   case AxClass.class_of_param thy c
   162    of SOME class => (case Sign.const_typargs thy c_ty
   163        of [Type (tyco, _)] =>
   164             (case Symtab.lookup ((the o Symtab.lookup (fst (InstData.get thy))) c) tyco
   165              of SOME (c, _) => c
   166               | NONE => c)
   167         | [_] => c)
   168     | NONE => c;
   169 
   170 val param_const = Symtab.lookup o snd o InstData.get;
   171 
   172 fun add_inst_def (class, tyco) (c, ty) thy =
   173   let
   174     val tyco_base = NameSpace.base tyco;
   175     val name_inst = NameSpace.base class ^ "_" ^ tyco_base ^ "_inst";
   176     val c_inst_base = NameSpace.base c ^ "_" ^ tyco_base;
   177   in
   178     thy
   179     |> Sign.sticky_prefix name_inst
   180     |> PureThy.simple_def ("", [])
   181          (((c_inst_base, ty, Syntax.NoSyn), []), Const (c, ty))
   182     |-> (fn (c_inst, thm) => add_inst (c, tyco) (c_inst, symmetric thm))
   183     |> Sign.restore_naming thy
   184   end;
   185 
   186 fun add_inst_def' (class, tyco) (c, ty) thy =
   187   if case Symtab.lookup (fst (InstData.get thy)) c
   188    of NONE => true
   189     | SOME tab => is_none (Symtab.lookup tab tyco)
   190   then add_inst_def (class, tyco) (c, Logic.unvarifyT ty) thy
   191   else thy;
   192 
   193 fun add_def ((class, tyco), ((name, prop), atts)) thy =
   194   let
   195     val ((lhs as Const (c, ty), args), rhs) = (apfst Term.strip_comb o Logic.dest_equals) prop;
   196     fun add_inst' def ([], (Const (c_inst, ty))) =
   197           if forall (fn TFree _ => true | _ => false) (Sign.const_typargs thy (c_inst, ty))
   198           then add_inst (c, tyco) (c_inst, def)
   199           else add_inst_def (class, tyco) (c, ty)
   200       | add_inst' _ t = add_inst_def (class, tyco) (c, ty);
   201   in
   202     thy
   203     |> PureThy.add_defs_i true [((name, prop), map (Attrib.attribute thy) atts)]
   204     |-> (fn [def] => add_inst' def (args, rhs) #> pair def)
   205   end;
   206 
   207 
   208 (* instances with implicit parameter handling *)
   209 
   210 local
   211 
   212 fun gen_read_def thy prep_att read_def ((raw_name, raw_atts), raw_t) =
   213   let
   214     val (_, t) = read_def thy (raw_name, raw_t);
   215     val ((c, ty), _) = Sign.cert_def (Sign.pp thy) t;
   216     val atts = map (prep_att thy) raw_atts;
   217     val insts = Consts.typargs (Sign.consts_of thy) (c, ty);
   218     val name = case raw_name
   219      of "" => NONE
   220       | _ => SOME raw_name;
   221   in (c, (insts, ((name, t), atts))) end;
   222 
   223 fun read_def_cmd thy = gen_read_def thy Attrib.intern_src Theory.read_axm;
   224 fun read_def thy = gen_read_def thy (K I) (K I);
   225 
   226 fun gen_instance_arity prep_arity read_def do_proof raw_arities raw_defs after_qed theory =
   227   let
   228     val arities = map (prep_arity theory) raw_arities;
   229     val _ = if null arities then error "at least one arity must be given" else ();
   230     val _ = case (duplicates (op =) o map #1) arities
   231      of [] => ()
   232       | dupl_tycos => error ("type constructors occur more than once in arities: "
   233           ^ (commas o map quote) dupl_tycos);
   234     val super_sort = (Graph.all_succs o #classes o Sorts.rep_algebra o Sign.classes_of) theory
   235     fun get_consts_class tyco ty class =
   236       let
   237         val cs = (these o Option.map snd o try (AxClass.params_of_class theory)) class;
   238         val subst_ty = map_type_tfree (K ty);
   239       in
   240         map (fn (c, ty) => (c, ((class, tyco), subst_ty ty))) cs
   241       end;
   242     fun get_consts_sort (tyco, asorts, sort) =
   243       let
   244         val ty = Type (tyco, map (fn (v, sort) => TVar ((v, 0), sort)) (Name.names Name.context "'a" asorts))
   245       in maps (get_consts_class tyco ty) (super_sort sort) end;
   246     val cs = maps get_consts_sort arities;
   247     fun mk_typnorm thy (ty, ty_sc) =
   248       case try (Sign.typ_match thy (Logic.varifyT ty_sc, ty)) Vartab.empty
   249        of SOME env => SOME (Logic.varifyT #> Envir.typ_subst_TVars env #> Logic.unvarifyT)
   250         | NONE => NONE;
   251     fun read_defs defs cs thy_read =
   252       let
   253         fun read raw_def cs =
   254           let
   255             val (c, (inst, ((name_opt, t), atts))) = read_def thy_read raw_def;
   256             val ty = Consts.instance (Sign.consts_of thy_read) (c, inst);
   257             val ((class, tyco), ty') = case AList.lookup (op =) cs c
   258              of NONE => error ("illegal definition for constant " ^ quote c)
   259               | SOME class_ty => class_ty;
   260             val name = case name_opt
   261              of NONE => Thm.def_name (Logic.name_arity (tyco, [], c))
   262               | SOME name => name;
   263             val t' = case mk_typnorm thy_read (ty', ty)
   264              of NONE => error ("illegal definition for constant " ^
   265                   quote (c ^ "::" ^ setmp show_sorts true
   266                     (Sign.string_of_typ thy_read) ty))
   267               | SOME norm => map_types norm t
   268           in (((class, tyco), ((name, t'), atts)), AList.delete (op =) c cs) end;
   269       in fold_map read defs cs end;
   270     val (defs, other_cs) = read_defs raw_defs cs
   271       (fold Sign.primitive_arity arities (Theory.copy theory));
   272     fun get_remove_contraint c thy =
   273       let
   274         val ty = Sign.the_const_constraint thy c;
   275       in
   276         thy
   277         |> Sign.add_const_constraint_i (c, NONE)
   278         |> pair (c, Logic.unvarifyT ty)
   279       end;
   280     fun after_qed' cs defs =
   281       fold Sign.add_const_constraint_i (map (apsnd SOME) cs)
   282       #> after_qed defs;
   283   in
   284     theory
   285     |> fold_map get_remove_contraint (map fst cs |> distinct (op =))
   286     ||>> fold_map add_def defs
   287     ||> fold (fn (c, ((class, tyco), ty)) => add_inst_def' (class, tyco) (c, ty)) other_cs
   288     |-> (fn (cs, defs) => do_proof (after_qed' cs defs) arities defs)
   289   end;
   290 
   291 fun instance_arity_cmd' do_proof = gen_instance_arity Sign.read_arity read_def_cmd do_proof;
   292 fun instance_arity' do_proof = gen_instance_arity Sign.cert_arity read_def do_proof;
   293 fun tactic_proof tac f arities defs =
   294   fold (fn arity => AxClass.prove_arity arity tac) arities
   295   #> f
   296   #> pair defs;
   297 
   298 in
   299 
   300 val instance_arity_cmd = instance_arity_cmd'
   301   (fn f => fn arities => fn defs => axclass_instance_arity f arities);
   302 val instance_arity = instance_arity'
   303   (fn f => fn arities => fn defs => axclass_instance_arity f arities);
   304 fun prove_instance_arity tac arities defs =
   305   instance_arity' (tactic_proof tac) arities defs (K I);
   306 
   307 end; (*local*)
   308 
   309 
   310 
   311 (** combining locales and axclasses **)
   312 
   313 (* theory data *)
   314 
   315 datatype class_data = ClassData of {
   316   locale: string,
   317   consts: (string * string) list
   318     (*locale parameter ~> toplevel theory constant*),
   319   v: string option,
   320   intro: thm
   321 } * thm list (*derived defs*);
   322 
   323 fun rep_classdata (ClassData c) = c;
   324 
   325 fun merge_pair f1 f2 ((x1, y1), (x2, y2)) = (f1 (x1, x2), f2 (y1, y2));
   326 
   327 structure ClassData = TheoryDataFun
   328 (
   329   type T = class_data Graph.T * class Symtab.table (*locale name ~> class name*);
   330   val empty = (Graph.empty, Symtab.empty);
   331   val copy = I;
   332   val extend = I;
   333   fun merge _ = merge_pair (Graph.merge (K true)) (Symtab.merge (K true));
   334 );
   335 
   336 
   337 (* queries *)
   338 
   339 val lookup_class_data = Option.map rep_classdata oo try o Graph.get_node o fst o ClassData.get;
   340 fun class_of_locale thy = Symtab.lookup ((snd o ClassData.get) thy);
   341 
   342 fun the_class_data thy class =
   343   case lookup_class_data thy class
   344     of NONE => error ("undeclared class " ^ quote class)
   345      | SOME data => data;
   346 
   347 val ancestry = Graph.all_succs o fst o ClassData.get;
   348 
   349 fun params_of_sort thy =
   350   let
   351     fun params class =
   352       let
   353         val const_typs = (#params o AxClass.get_definition thy) class;
   354         val const_names = (#consts o fst o the_class_data thy) class;
   355       in
   356         (map o apsnd) (fn c => (c, (the o AList.lookup (op =) const_typs) c)) const_names
   357       end;
   358   in maps params o ancestry thy end;
   359 
   360 fun these_defs thy = maps (these o Option.map snd o lookup_class_data thy) o ancestry thy;
   361 
   362 fun these_intros thy =
   363   Graph.fold (fn (_, (data, _)) => insert Thm.eq_thm ((#intro o fst o rep_classdata) data))
   364     ((fst o ClassData.get) thy) [];
   365 
   366 fun print_classes thy =
   367   let
   368     val algebra = Sign.classes_of thy;
   369     val arities =
   370       Symtab.empty
   371       |> Symtab.fold (fn (tyco, arities) => fold (fn (class, _) =>
   372            Symtab.map_default (class, []) (insert (op =) tyco)) arities)
   373              ((#arities o Sorts.rep_algebra) algebra);
   374     val the_arities = these o Symtab.lookup arities;
   375     fun mk_arity class tyco =
   376       let
   377         val Ss = Sorts.mg_domain algebra tyco [class];
   378       in Sign.pretty_arity thy (tyco, Ss, [class]) end;
   379     fun mk_param (c, ty) = Pretty.str (Sign.extern_const thy c ^ " :: "
   380       ^ setmp show_sorts false (Sign.string_of_typ thy o Type.strip_sorts) ty);
   381     fun mk_entry class = (Pretty.block o Pretty.fbreaks o map_filter I) [
   382       (SOME o Pretty.str) ("class " ^ class ^ ":"),
   383       (SOME o Pretty.block) [Pretty.str "supersort: ",
   384         (Sign.pretty_sort thy o Sign.certify_sort thy o Sign.super_classes thy) class],
   385       Option.map (Pretty.str o prefix "locale: " o #locale o fst) (lookup_class_data thy class),
   386       ((fn [] => NONE | ps => (SOME o Pretty.block o Pretty.fbreaks) (Pretty.str "parameters:" :: ps)) o map mk_param
   387         o these o Option.map #params o try (AxClass.get_definition thy)) class,
   388       (SOME o Pretty.block o Pretty.breaks) [
   389         Pretty.str "instances:",
   390         Pretty.list "" "" (map (mk_arity class) (the_arities class))
   391       ]
   392     ]
   393   in
   394     (Pretty.writeln o Pretty.chunks o separate (Pretty.str "") o map mk_entry o Sorts.all_classes)
   395       algebra
   396   end;
   397 
   398 
   399 (* updaters *)
   400 
   401 fun add_class_data ((class, superclasses), (locale, consts, v, intro)) =
   402   ClassData.map (fn (gr, tab) => (
   403     gr
   404     |> Graph.new_node (class, ClassData ({ locale = locale, consts = consts,
   405          v = v, intro = intro }, []))
   406     |> fold (curry Graph.add_edge class) superclasses,
   407     tab
   408     |> Symtab.update (locale, class)
   409   ));
   410 
   411 fun add_class_const_thm (class, thm) = (ClassData.map o apfst o Graph.map_node class)
   412   (fn ClassData (data, thms) => ClassData (data, thm :: thms));
   413 
   414 (* tactics and methods *)
   415 
   416 fun intro_classes_tac facts st =
   417   let
   418     val thy = Thm.theory_of_thm st;
   419     val classes = Sign.all_classes thy;
   420     val class_trivs = map (Thm.class_triv thy) classes;
   421     val class_intros = these_intros thy;
   422     fun add_axclass_intro class =
   423       case try (AxClass.get_definition thy) class of SOME {intro, ...} => cons intro | _ => I;
   424     val axclass_intros = fold add_axclass_intro classes [];
   425   in
   426     st
   427     |> ((ALLGOALS (Method.insert_tac facts THEN'
   428           REPEAT_ALL_NEW (resolve_tac (class_trivs @ class_intros @ axclass_intros))))
   429             THEN Tactic.distinct_subgoals_tac)
   430   end;
   431 
   432 fun default_intro_classes_tac [] = intro_classes_tac []
   433   | default_intro_classes_tac _ = Tactical.no_tac;    (*no error message!*)
   434 
   435 fun default_tac rules ctxt facts =
   436   HEADGOAL (Method.some_rule_tac rules ctxt facts) ORELSE
   437     default_intro_classes_tac facts;
   438 
   439 val _ = Context.add_setup (Method.add_methods
   440  [("intro_classes", Method.no_args (Method.METHOD intro_classes_tac),
   441     "back-chain introduction rules of classes"),
   442   ("default", Method.thms_ctxt_args (Method.METHOD oo default_tac),
   443     "apply some intro/elim rule")]);
   444 
   445 
   446 (* tactical interfaces to locale commands *)
   447 
   448 fun prove_interpretation tac prfx_atts expr insts thy =
   449   thy
   450   |> Locale.interpretation_i I prfx_atts expr insts
   451   |> Proof.global_terminal_proof (Method.Basic (K (Method.SIMPLE_METHOD tac), Position.none), NONE)
   452   |> ProofContext.theory_of;
   453 
   454 fun prove_interpretation_in tac after_qed (name, expr) thy =
   455   thy
   456   |> Locale.interpretation_in_locale (ProofContext.theory after_qed) (name, expr)
   457   |> Proof.global_terminal_proof (Method.Basic (K (Method.SIMPLE_METHOD tac), Position.none), NONE)
   458   |> ProofContext.theory_of;
   459 
   460 
   461 (* constructing class introduction and other rules from axclass and locale rules *)
   462 
   463 fun mk_instT class = Symtab.empty
   464   |> Symtab.update (AxClass.param_tyvarname, TFree (AxClass.param_tyvarname, [class]));
   465 
   466 fun mk_inst class param_names cs =
   467   Symtab.empty
   468   |> fold2 (fn v => fn (c, ty) => Symtab.update (v, Const
   469        (c, Term.map_type_tfree (fn (v, _) => TFree (v, [class])) ty))) param_names cs;
   470 
   471 fun OF_LAST thm1 thm2 =
   472   let
   473     val n = (length o Logic.strip_imp_prems o prop_of) thm2;
   474   in (thm1 RSN (n, thm2)) end;
   475 
   476 fun strip_all_ofclass thy sort =
   477   let
   478     val typ = TVar ((AxClass.param_tyvarname, 0), sort);
   479     fun prem_inclass t =
   480       case Logic.strip_imp_prems t
   481        of ofcls :: _ => try Logic.dest_inclass ofcls
   482         | [] => NONE;
   483     fun strip_ofclass class thm =
   484       thm OF (fst o AxClass.of_sort thy (typ, [class])) AxClass.cache;
   485     fun strip thm = case (prem_inclass o Thm.prop_of) thm
   486      of SOME (_, class) => thm |> strip_ofclass class |> strip
   487       | NONE => thm;
   488   in strip end;
   489 
   490 fun class_intro thy locale class sups =
   491   let
   492     fun class_elim class =
   493       case (map Drule.unconstrainTs o #axioms o AxClass.get_definition thy) class
   494        of [thm] => SOME thm
   495         | [] => NONE;
   496     val pred_intro = case Locale.intros thy locale
   497      of ([ax_intro], [intro]) => intro |> OF_LAST ax_intro |> SOME
   498       | ([intro], []) => SOME intro
   499       | ([], [intro]) => SOME intro
   500       | _ => NONE;
   501     val pred_intro' = pred_intro
   502       |> Option.map (fn intro => intro OF map_filter class_elim sups);
   503     val class_intro = (#intro o AxClass.get_definition thy) class;
   504     val raw_intro = case pred_intro'
   505      of SOME pred_intro => class_intro |> OF_LAST pred_intro
   506       | NONE => class_intro;
   507     val sort = Sign.super_classes thy class;
   508     val typ = TVar ((AxClass.param_tyvarname, 0), sort);
   509     val defs = these_defs thy sups;
   510   in
   511     raw_intro
   512     |> Drule.instantiate' [SOME (Thm.ctyp_of thy typ)] []
   513     |> strip_all_ofclass thy sort
   514     |> Thm.strip_shyps
   515     |> MetaSimplifier.rewrite_rule defs
   516     |> Drule.unconstrainTs
   517   end;
   518 
   519 fun interpretation_in_rule thy (class1, class2) =
   520   let
   521     val (params, consts) = split_list (params_of_sort thy [class1]);
   522     (*FIXME also remember this at add_class*)
   523     fun mk_axioms class =
   524       let
   525         val name_locale = (#locale o fst o the_class_data thy) class;
   526         val inst = mk_inst class params consts;
   527       in
   528         Locale.global_asms_of thy name_locale
   529         |> maps snd
   530         |> (map o map_aterms) (fn Free (s, _) => (the o Symtab.lookup inst) s | t => t)
   531         |> (map o map_types o map_atyps) (fn TFree _ => TFree ("'a", [class1]) | T => T)
   532         |> map (ObjectLogic.ensure_propT thy)
   533       end;
   534     val (prems, concls) = pairself mk_axioms (class1, class2);
   535   in
   536     Goal.prove_global thy [] prems (Logic.mk_conjunction_list concls)
   537       (Locale.intro_locales_tac true (ProofContext.init thy))
   538   end;
   539 
   540 
   541 (* classes *)
   542 
   543 local
   544 
   545 fun read_param thy raw_t =
   546   let
   547     val t = Sign.read_term thy raw_t
   548   in case try dest_Const t
   549    of SOME (c, _) => c
   550     | NONE => error ("Not a constant: " ^ Sign.string_of_term thy t)
   551   end;
   552 
   553 fun gen_class add_locale prep_class prep_param bname
   554     raw_supclasses raw_elems raw_other_consts thy =
   555   let
   556     (*FIXME need proper concept for reading locale statements*)
   557     fun subst_classtyvar (_, _) =
   558           TFree (AxClass.param_tyvarname, [])
   559       | subst_classtyvar (v, sort) =
   560           error ("Sort constraint illegal in type class, for type variable " ^ v ^ "::" ^ Sign.string_of_sort thy sort);
   561     (*val subst_classtyvars = Element.map_ctxt {name = I, var = I, term = I,
   562       typ = Term.map_type_tfree subst_classtyvar, fact = I, attrib = I};*)
   563     val other_consts = map (prep_param thy) raw_other_consts;
   564     val (elems, includes) = fold_rev (fn Locale.Elem e => apfst (cons e)
   565       | Locale.Expr i => apsnd (cons i)) raw_elems ([], []);
   566     val supclasses = map (prep_class thy) raw_supclasses;
   567     val sups = filter (is_some o lookup_class_data thy) supclasses
   568       |> Sign.certify_sort thy;
   569     val supsort = Sign.certify_sort thy supclasses;
   570     val suplocales = map (Locale.Locale o #locale o fst o the_class_data thy) sups;
   571     val supexpr = Locale.Merge (suplocales @ includes);
   572     val supparams = (map fst o Locale.parameters_of_expr thy)
   573       (Locale.Merge suplocales);
   574     val supconsts = AList.make (the o AList.lookup (op =) (params_of_sort thy sups))
   575       (map fst supparams);
   576     (*val elems_constrains = map
   577       (Element.Constrains o apsnd (Term.map_type_tfree subst_classtyvar)) supparams;*)
   578     fun mk_tyvar (_, sort) = TFree (AxClass.param_tyvarname,
   579       if Sign.subsort thy (supsort, sort) then sort else error
   580         ("Sort " ^ Sign.string_of_sort thy sort
   581           ^ " is less general than permitted least general sort "
   582           ^ Sign.string_of_sort thy supsort));
   583     fun extract_params thy name_locale =
   584       let
   585         val params = Locale.parameters_of thy name_locale;
   586         val v = case (maps typ_tfrees o map (snd o fst)) params
   587          of (v, _) :: _ => SOME v
   588           | _ => NONE;
   589       in
   590         (v, (map (fst o fst) params, params
   591         |> (map o apfst o apsnd o Term.map_type_tfree) mk_tyvar
   592         |> (map o apsnd) (fork_mixfix true NONE #> fst)
   593         |> chop (length supconsts)
   594         |> snd))
   595       end;
   596     fun extract_assumes name_locale params thy cs =
   597       let
   598         val consts = supconsts @ (map (fst o fst) params ~~ cs);
   599         fun subst (Free (c, ty)) =
   600               Const ((fst o the o AList.lookup (op =) consts) c, ty)
   601           | subst t = t;
   602         val super_defs = these_defs thy sups;
   603         fun prep_asm ((name, atts), ts) =
   604           ((NameSpace.base name, map (Attrib.attribute thy) atts),
   605             (map o map_aterms) ((*MetaSimplifier.rewrite_term thy super_defs [] o *)subst) ts);
   606       in
   607         Locale.global_asms_of thy name_locale
   608         |> map prep_asm
   609       end;
   610     fun note_intro name_axclass class_intro =
   611       PureThy.note_thmss_qualified "" ((Logic.const_of_class o NameSpace.base) name_axclass)
   612         [(("intro", []), [([class_intro], [])])]
   613       #> snd
   614   in
   615     thy
   616     |> add_locale (SOME "") bname supexpr ((*elems_constrains @*) elems)
   617     |-> (fn name_locale => ProofContext.theory_result (
   618       `(fn thy => extract_params thy name_locale)
   619       #-> (fn (v, (param_names, params)) =>
   620         axclass_params (bname, supsort) params (extract_assumes name_locale params) other_consts
   621       #-> (fn (name_axclass, ((_, (ax_terms, ax_axioms)), consts)) =>
   622         `(fn thy => class_intro thy name_locale name_axclass sups)
   623       #-> (fn class_intro =>
   624         add_class_data ((name_axclass, sups),
   625           (name_locale, map (fst o fst) params ~~ map fst consts, v,
   626             class_intro))
   627         (*FIXME: class_data should already contain data relevant
   628           for interpretation; use this later for class target*)
   629         (*FIXME: general export_fixes which may be parametrized
   630           with pieces of an emerging class*)
   631       #> note_intro name_axclass class_intro
   632       #> prove_interpretation ((ALLGOALS o ProofContext.fact_tac) ax_axioms)
   633           ((false, Logic.const_of_class bname), []) (Locale.Locale name_locale)
   634           ((mk_instT name_axclass, mk_inst name_axclass param_names (map snd supconsts @ consts)), [])
   635       #> pair name_axclass
   636       )))))
   637   end;
   638 
   639 in
   640 
   641 val class_cmd = gen_class Locale.add_locale Sign.intern_class read_param;
   642 val class = gen_class Locale.add_locale_i Sign.certify_class (K I);
   643 
   644 end; (*local*)
   645 
   646 local
   647 
   648 fun instance_subclass (class1, class2) thy  =
   649   let
   650     val interp = interpretation_in_rule thy (class1, class2);
   651     val ax = #axioms (AxClass.get_definition thy class1);
   652     val intro = #intro (AxClass.get_definition thy class2)
   653       |> Drule.instantiate' [SOME (Thm.ctyp_of thy
   654           (TVar ((AxClass.param_tyvarname, 0), [class1])))] [];
   655     val thm = 
   656       intro
   657       |> OF_LAST (interp OF ax)
   658       |> strip_all_ofclass thy (Sign.super_classes thy class2);
   659   in
   660     thy |> AxClass.add_classrel thm
   661   end;
   662 
   663 fun instance_subsort (class, sort) thy =
   664   let
   665     val super_sort = (Graph.all_succs o #classes o Sorts.rep_algebra
   666       o Sign.classes_of) thy sort;
   667     val classes = filter_out (fn class' => Sign.subsort thy ([class], [class']))
   668       (rev super_sort);
   669   in
   670     thy |> fold (curry instance_subclass class) classes
   671   end;
   672 
   673 fun instance_sort' do_proof (class, sort) theory =
   674   let
   675     val loc_name = (#locale o fst o the_class_data theory) class;
   676     val loc_expr =
   677       (Locale.Merge o map (Locale.Locale o #locale o fst o the_class_data theory)) sort;
   678   in
   679     theory
   680     |> do_proof (instance_subsort (class, sort)) (loc_name, loc_expr)
   681   end;
   682 
   683 fun gen_instance_sort prep_class prep_sort (raw_class, raw_sort) theory =
   684   let
   685     val class = prep_class theory raw_class;
   686     val sort = prep_sort theory raw_sort;
   687   in
   688     theory
   689     |> instance_sort' (Locale.interpretation_in_locale o ProofContext.theory) (class, sort)
   690   end;
   691 
   692 fun gen_instance_class prep_class (raw_class, raw_superclass) theory =
   693   let
   694     val class = prep_class theory raw_class;
   695     val superclass = prep_class theory raw_superclass;
   696   in
   697     theory
   698     |> axclass_instance_sort (class, superclass)
   699   end;
   700 
   701 in
   702 
   703 val instance_sort_cmd = gen_instance_sort Sign.read_class Syntax.global_read_sort;
   704 val instance_sort = gen_instance_sort Sign.certify_class Sign.certify_sort;
   705 val prove_instance_sort = instance_sort' o prove_interpretation_in;
   706 val instance_class_cmd = gen_instance_class Sign.read_class;
   707 val instance_class = gen_instance_class Sign.certify_class;
   708 
   709 end; (*local*)
   710 
   711 
   712 (** class target **)
   713 
   714 fun export_fixes thy class =
   715   let
   716     val v = (#v o fst o the_class_data thy) class;
   717     val constrain_sort = curry (Sorts.inter_sort (Sign.classes_of thy)) [class];
   718     val subst_typ = Term.map_type_tfree (fn var as (w, sort) =>
   719       if SOME w = v then TFree (w, constrain_sort sort) else TFree var);
   720     val consts = params_of_sort thy [class];
   721     fun subst_aterm (t as Free (v, ty)) = (case AList.lookup (op =) consts v
   722          of SOME (c, _) => Const (c, ty)
   723           | NONE => t)
   724       | subst_aterm t = t;
   725   in map_types subst_typ #> Term.map_aterms subst_aterm end;
   726 
   727 fun add_const_in_class class ((c, rhs), syn) thy =
   728   let
   729     val prfx = (Logic.const_of_class o NameSpace.base) class;
   730     fun mk_name inject c =
   731       let
   732         val n1 = Sign.full_name thy c;
   733         val n2 = NameSpace.qualifier n1;
   734         val n3 = NameSpace.base n1;
   735       in NameSpace.implode (n2 :: inject @ [n3]) end;
   736     val abbr' = mk_name [prfx, prfx] c;
   737     val rhs' = export_fixes thy class rhs;
   738     val ty' = Term.fastype_of rhs';
   739     val def = (c, Logic.mk_equals (Const (mk_name [prfx] c, ty'), rhs'));
   740     val (syn', _) = fork_mixfix true NONE syn;
   741     fun interpret def =
   742       let
   743         val def' = symmetric def
   744         val tac = (ALLGOALS o ProofContext.fact_tac) [def'];
   745         val name_locale = (#locale o fst o the_class_data thy) class;
   746         val def_eq = Thm.prop_of def';
   747         val (params, consts) = split_list (params_of_sort thy [class]);
   748       in
   749         prove_interpretation tac ((false, prfx), []) (Locale.Locale name_locale)
   750           ((mk_instT class, mk_inst class params consts), [def_eq])
   751         #> add_class_const_thm (class, def')
   752       end;
   753   in
   754     thy
   755     |> Sign.hide_consts_i true [abbr']
   756     |> Sign.add_path prfx
   757     |> Sign.add_consts_authentic [(c, ty', syn')]
   758     |> Sign.parent_path
   759     |> Sign.sticky_prefix prfx
   760     |> PureThy.add_defs_i false [(def, [])]
   761     |-> (fn [def] => interpret def)
   762     |> Sign.restore_naming thy
   763   end;
   764 
   765 end;