src/Pure/axclass.ML
author wenzelm
Sun Jul 30 21:28:52 2006 +0200 (2006-07-30)
changeset 20260 990dbc007ca6
parent 20107 239a0efd38b2
child 20548 8ef25fe585a8
permissions -rw-r--r--
Thm.adjust_maxidx;
     1 (*  Title:      Pure/axclass.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 Type classes as parameter records and predicates, with explicit
     6 definitions and proofs.
     7 *)
     8 
     9 signature AX_CLASS =
    10 sig
    11   val get_definition: theory -> class -> {def: thm, intro: thm, axioms: thm list}
    12   val class_intros: theory -> thm list
    13   val params_of: theory -> class -> string list
    14   val all_params_of: theory -> sort -> string list
    15   val class_of_param: theory -> string -> class option
    16   val print_axclasses: theory -> unit
    17   val cert_classrel: theory -> class * class -> class * class
    18   val read_classrel: theory -> xstring * xstring -> class * class
    19   val add_classrel: thm -> theory -> theory
    20   val add_arity: thm -> theory -> theory
    21   val prove_classrel: class * class -> tactic -> theory -> theory
    22   val prove_arity: string * sort list * sort -> tactic -> theory -> theory
    23   val define_class: bstring * xstring list -> string list ->
    24     ((bstring * Attrib.src list) * string list) list -> theory -> class * theory
    25   val define_class_i: bstring * class list -> string list ->
    26     ((bstring * attribute list) * term list) list -> theory -> class * theory
    27   val axiomatize_class: bstring * xstring list -> theory -> theory
    28   val axiomatize_class_i: bstring * class list -> theory -> theory
    29   val axiomatize_classrel: (xstring * xstring) list -> theory -> theory
    30   val axiomatize_classrel_i: (class * class) list -> theory -> theory
    31   val axiomatize_arity: xstring * string list * string -> theory -> theory
    32   val axiomatize_arity_i: arity -> theory -> theory
    33   type cache
    34   val cache: cache
    35   val of_sort: theory -> typ * sort -> cache -> thm list * cache  (*exception Sorts.CLASS_ERROR*)
    36 end;
    37 
    38 structure AxClass: AX_CLASS =
    39 struct
    40 
    41 (** theory data **)
    42 
    43 (* class parameters (canonical order) *)
    44 
    45 type param = string * class;
    46 
    47 fun add_param pp ((x, c): param) params =
    48   (case AList.lookup (op =) params x of
    49     NONE => (x, c) :: params
    50   | SOME c' => error ("Duplicate class parameter " ^ quote x ^
    51       " for " ^ Pretty.string_of_sort pp [c] ^
    52       (if c = c' then "" else " and " ^ Pretty.string_of_sort pp [c'])));
    53 
    54 fun merge_params _ ([], qs) = qs
    55   | merge_params pp (ps, qs) =
    56       fold_rev (fn q => if member (op =) ps q then I else add_param pp q) qs ps;
    57 
    58 
    59 (* axclasses *)
    60 
    61 val introN = "intro";
    62 val superN = "super";
    63 val axiomsN = "axioms";
    64 
    65 datatype axclass = AxClass of
    66  {def: thm,
    67   intro: thm,
    68   axioms: thm list};
    69 
    70 type axclasses = axclass Symtab.table * param list;
    71 
    72 fun make_axclass (def, intro, axioms) =
    73   AxClass {def = def, intro = intro, axioms = axioms};
    74 
    75 fun merge_axclasses pp ((tab1, params1), (tab2, params2)) : axclasses =
    76   (Symtab.merge (K true) (tab1, tab2), merge_params pp (params1, params2));
    77 
    78 
    79 (* instances *)
    80 
    81 val classrelN = "classrel";
    82 val arityN = "arity";
    83 
    84 type instances =
    85   ((class * class) * thm) list *
    86   ((class * sort list) * thm) list Symtab.table;
    87 
    88 fun merge_instances ((classrel1, arities1): instances, (classrel2, arities2)) =
    89  (merge (eq_fst op =) (classrel1, classrel2),
    90   Symtab.join (K (merge (eq_fst op =))) (arities1, arities2));
    91 
    92 
    93 (* setup data *)
    94 
    95 structure AxClassData = TheoryDataFun
    96 (struct
    97   val name = "Pure/axclass";
    98   type T = axclasses * instances;
    99   val empty : T = ((Symtab.empty, []), ([], Symtab.empty));
   100   val copy = I;
   101   val extend = I;
   102   fun merge pp ((axclasses1, instances1), (axclasses2, instances2)) =
   103     (merge_axclasses pp (axclasses1, axclasses2), (merge_instances (instances1, instances2)));
   104   fun print _ _ = ();
   105 end);
   106 
   107 val _ = Context.add_setup AxClassData.init;
   108 
   109 
   110 (* maintain axclasses *)
   111 
   112 val get_axclasses = #1 o AxClassData.get;
   113 fun map_axclasses f = AxClassData.map (apfst f);
   114 
   115 val lookup_def = Symtab.lookup o #1 o get_axclasses;
   116 
   117 fun get_definition thy c =
   118   (case lookup_def thy c of
   119     SOME (AxClass info) => info
   120   | NONE => error ("Undefined type class " ^ quote c));
   121 
   122 fun class_intros thy =
   123   let
   124     fun add_intro c =
   125       (case lookup_def thy c of SOME (AxClass {intro, ...}) => cons intro | _ => I);
   126     val classes = Sign.classes thy;
   127   in map (Thm.class_triv thy) classes @ fold add_intro classes [] end;
   128 
   129 
   130 fun get_params thy pred =
   131   let val params = #2 (get_axclasses thy);
   132   in fold (fn (x, c) => if pred c then cons x else I) params [] end;
   133 
   134 fun params_of thy c = get_params thy (fn c' => c' = c);
   135 fun all_params_of thy S = get_params thy (fn c => Sign.subsort thy (S, [c]));
   136 
   137 fun class_of_param thy =
   138   AList.lookup (op =) (#2 (get_axclasses thy));
   139 
   140 
   141 (* maintain instances *)
   142 
   143 val get_instances = #2 o AxClassData.get;
   144 fun map_instances f = AxClassData.map (apsnd f);
   145 
   146 
   147 fun the_classrel thy (c1, c2) =
   148   (case AList.lookup (op =) (#1 (get_instances thy)) (c1, c2) of
   149     SOME th => Thm.transfer thy th
   150   | NONE => error ("Unproven class relation " ^ Sign.string_of_classrel thy [c1, c2]));
   151 
   152 fun put_classrel arg = map_instances (fn (classrel, arities) =>
   153   (insert (eq_fst op =) arg classrel, arities));
   154 
   155 
   156 fun the_arity thy a (c, Ss) =
   157   (case AList.lookup (op =) (Symtab.lookup_list (#2 (get_instances thy)) a) (c, Ss)  of
   158     SOME th => Thm.transfer thy th
   159   | NONE => error ("Unproven type arity " ^ Sign.string_of_arity thy (a, Ss, [c])));
   160 
   161 fun put_arity ((t, Ss, c), th) = map_instances (fn (classrel, arities) =>
   162   (classrel, arities |> Symtab.insert_list (eq_fst op =) (t, ((c, Ss), th))));
   163 
   164 
   165 (* print data *)
   166 
   167 fun print_axclasses thy =
   168   let
   169     val axclasses = #1 (get_axclasses thy);
   170     val ctxt = ProofContext.init thy;
   171 
   172     fun pretty_axclass (class, AxClass {def, intro, axioms}) =
   173       Pretty.block (Pretty.fbreaks
   174        [Pretty.block
   175           [Pretty.str "class ", ProofContext.pretty_sort ctxt [class], Pretty.str ":"],
   176         Pretty.strs ("parameters:" :: params_of thy class),
   177         ProofContext.pretty_fact ctxt ("def", [def]),
   178         ProofContext.pretty_fact ctxt (introN, [intro]),
   179         ProofContext.pretty_fact ctxt (axiomsN, axioms)]);
   180   in Pretty.writeln (Pretty.chunks (map pretty_axclass (Symtab.dest axclasses))) end;
   181 
   182 
   183 
   184 (** instances **)
   185 
   186 (* class relations *)
   187 
   188 fun cert_classrel thy raw_rel =
   189   let
   190     val (c1, c2) = pairself (Sign.certify_class thy) raw_rel;
   191     val _ = Type.add_classrel (Sign.pp thy) (c1, c2) (Sign.tsig_of thy);
   192     val _ =
   193       (case subtract (op =) (all_params_of thy [c1]) (all_params_of thy [c2]) of
   194         [] => ()
   195       | xs => raise TYPE ("Class " ^ Sign.string_of_sort thy [c1] ^ " lacks parameter(s) " ^
   196           commas_quote xs ^ " of " ^ Sign.string_of_sort thy [c2], [], []));
   197   in (c1, c2) end;
   198 
   199 fun read_classrel thy raw_rel =
   200   cert_classrel thy (pairself (Sign.read_class thy) raw_rel)
   201     handle TYPE (msg, _, _) => error msg;
   202 
   203 
   204 (* primitive rules *)
   205 
   206 fun add_classrel th thy =
   207   let
   208     fun err () = raise THM ("add_classrel: malformed class relation", 0, [th]);
   209     val prop = Drule.plain_prop_of (Thm.transfer thy th);
   210     val rel = Logic.dest_classrel prop handle TERM _ => err ();
   211     val (c1, c2) = cert_classrel thy rel handle TYPE _ => err ();
   212   in
   213     thy
   214     |> Sign.primitive_classrel (c1, c2)
   215     |> put_classrel ((c1, c2), Drule.unconstrainTs th)
   216   end;
   217 
   218 fun add_arity th thy =
   219   let
   220     fun err () = raise THM ("add_arity: malformed type arity", 0, [th]);
   221     val prop = Drule.plain_prop_of (Thm.transfer thy th);
   222     val (t, Ss, c) = Logic.dest_arity prop handle TERM _ => err ();
   223     val _ = if map (Sign.certify_sort thy) Ss = Ss then () else err ();
   224   in
   225     thy
   226     |> Sign.primitive_arity (t, Ss, [c])
   227     |> put_arity ((t, Ss, c), Drule.unconstrainTs th)
   228   end;
   229 
   230 
   231 (* tactical proofs *)
   232 
   233 fun prove_classrel raw_rel tac thy =
   234   let
   235     val (c1, c2) = cert_classrel thy raw_rel;
   236     val th = Goal.prove (ProofContext.init thy) [] []
   237         (Logic.mk_classrel (c1, c2)) (fn _ => tac) handle ERROR msg =>
   238       cat_error msg ("The error(s) above occurred while trying to prove class relation " ^
   239         quote (Sign.string_of_classrel thy [c1, c2]));
   240   in
   241     thy
   242     |> PureThy.add_thms [((classrelN ^ "_" ^ serial_string (), th), [])]
   243     |-> (fn [th'] => add_classrel th')
   244   end;
   245 
   246 fun prove_arity raw_arity tac thy =
   247   let
   248     val arity = Sign.cert_arity thy raw_arity;
   249     val props = Logic.mk_arities arity;
   250     val ths = Goal.prove_multi (ProofContext.init thy) [] [] props
   251       (fn _ => Tactic.precise_conjunction_tac (length props) 1 THEN tac) handle ERROR msg =>
   252         cat_error msg ("The error(s) above occurred while trying to prove type arity " ^
   253           quote (Sign.string_of_arity thy arity));
   254   in
   255     thy
   256     |> PureThy.add_thms (ths |> map (fn th => ((arityN ^ "_" ^ serial_string (), th), [])))
   257     |-> fold add_arity
   258   end;
   259 
   260 
   261 
   262 (** class definitions **)
   263 
   264 local
   265 
   266 fun def_class prep_class prep_att prep_propp
   267     (bclass, raw_super) params raw_specs thy =
   268   let
   269     val ctxt = ProofContext.init thy;
   270     val pp = ProofContext.pp ctxt;
   271 
   272 
   273     (* prepare specification *)
   274 
   275     val bconst = Logic.const_of_class bclass;
   276     val class = Sign.full_name thy bclass;
   277     val super = map (prep_class thy) raw_super |> Sign.certify_sort thy;
   278 
   279     fun prep_axiom t =
   280       (case Term.add_tfrees t [] of
   281         [(a, S)] =>
   282           if Sign.subsort thy (super, S) then t
   283           else error ("Sort constraint of type variable " ^
   284             setmp show_sorts true (Pretty.string_of_typ pp) (TFree (a, S)) ^
   285             " needs to be weaker than " ^ Pretty.string_of_sort pp super)
   286       | [] => t
   287       | _ => error ("Multiple type variables in class axiom:\n" ^ Pretty.string_of_term pp t))
   288       |> map_term_types (Term.map_atyps (fn TFree _ => Term.aT [] | U => U))
   289       |> Logic.close_form;
   290 
   291     val axiomss = prep_propp (ctxt, map (map (rpair []) o snd) raw_specs)
   292       |> snd |> map (map (prep_axiom o fst));
   293     val name_atts = Attrib.map_specs (prep_att thy) raw_specs |> map fst;
   294 
   295 
   296     (* definition *)
   297 
   298     val conjs = map (curry Logic.mk_inclass (Term.aT [])) super @ flat axiomss;
   299     val class_eq =
   300       Logic.mk_equals (Logic.mk_inclass (Term.aT [], class), Logic.mk_conjunction_list conjs);
   301 
   302     val ([def], def_thy) =
   303       thy
   304       |> Sign.primitive_class (bclass, super)
   305       |> PureThy.add_defs_i false [((Thm.def_name bconst, class_eq), [])];
   306     val (raw_intro, (raw_classrel, raw_axioms)) =
   307       (Conjunction.split_defined (length conjs) def) ||> chop (length super);
   308 
   309 
   310     (* facts *)
   311 
   312     val class_triv = Thm.class_triv def_thy class;
   313     val ([(_, [intro]), (_, classrel), (_, axioms)], facts_thy) =
   314       def_thy
   315       |> PureThy.note_thmss_qualified "" bconst
   316         [((introN, []), [([Drule.standard raw_intro], [])]),
   317          ((superN, []), [(map Drule.standard raw_classrel, [])]),
   318          ((axiomsN, []), [(map (fn th => Drule.standard (class_triv RS th)) raw_axioms, [])])];
   319 
   320 
   321     (* result *)
   322 
   323     val result_thy =
   324       facts_thy
   325       |> fold put_classrel (map (pair class) super ~~ classrel)
   326       |> Sign.add_path bconst
   327       |> PureThy.note_thmss_i "" (name_atts ~~ map Thm.simple_fact (unflat axiomss axioms)) |> snd
   328       |> Sign.restore_naming facts_thy
   329       |> map_axclasses (fn (axclasses, parameters) =>
   330         (Symtab.update (class, make_axclass (def, intro, axioms)) axclasses,
   331           fold (fn x => add_param pp (x, class)) params parameters));
   332 
   333   in (class, result_thy) end;
   334 
   335 in
   336 
   337 val define_class = def_class Sign.read_class Attrib.attribute ProofContext.read_propp;
   338 val define_class_i = def_class Sign.certify_class (K I) ProofContext.cert_propp;
   339 
   340 end;
   341 
   342 
   343 
   344 (** axiomatizations **)
   345 
   346 local
   347 
   348 fun axiomatize kind add prep arg thy =
   349   let val specs = arg |> prep thy |> map (fn prop => ((kind ^ "_" ^ serial_string (), prop), []))
   350   in thy |> PureThy.add_axioms_i specs |-> fold add end;
   351 
   352 fun ax_classrel prep =
   353   axiomatize classrelN add_classrel (fn thy => map (prep thy #> Logic.mk_classrel));
   354 
   355 fun ax_arity prep =
   356   axiomatize arityN add_arity (fn thy => prep thy #> Logic.mk_arities);
   357 
   358 fun class_const c =
   359   (Logic.const_of_class c, Term.itselfT (Term.aT []) --> propT);
   360 
   361 fun ax_class prep_class prep_classrel (bclass, raw_super) thy =
   362   let
   363     val class = Sign.full_name thy bclass;
   364     val super = map (prep_class thy) raw_super |> Sign.certify_sort thy;
   365   in
   366     thy
   367     |> Sign.primitive_class (bclass, super)
   368     |> ax_classrel prep_classrel (map (fn c => (class, c)) super)
   369     |> Theory.add_deps "" (class_const class) (map class_const super)
   370   end;
   371 
   372 in
   373 
   374 val axiomatize_class = ax_class Sign.read_class read_classrel;
   375 val axiomatize_class_i = ax_class Sign.certify_class cert_classrel;
   376 val axiomatize_classrel = ax_classrel read_classrel;
   377 val axiomatize_classrel_i = ax_classrel cert_classrel;
   378 val axiomatize_arity = ax_arity Sign.read_arity;
   379 val axiomatize_arity_i = ax_arity Sign.cert_arity;
   380 
   381 end;
   382 
   383 
   384 
   385 (** explicit derivations -- cached **)
   386 
   387 datatype cache = Types of (class * thm) list Typtab.table;
   388 val cache = Types Typtab.empty;
   389 
   390 local
   391 
   392 fun lookup_type (Types cache) = AList.lookup (op =) o Typtab.lookup_list cache;
   393 fun insert_type T der (Types cache) = Types (Typtab.insert_list (eq_fst op =) (T, der) cache);
   394 
   395 fun derive_type _ (_, []) = []
   396   | derive_type thy (typ, sort) =
   397       let
   398         val vars = Term.fold_atyps
   399             (fn T as TFree (_, S) => insert (eq_fst op =) (T, S)
   400               | T as TVar (_, S) => insert (eq_fst op =) (T, S)
   401               | _ => I) typ [];
   402         val hyps = vars
   403           |> map (fn (T, S) => (T, Drule.sort_triv thy (T, S) ~~ S));
   404         val ths = (typ, sort) |> Sorts.of_sort_derivation (Sign.pp thy) (Sign.classes_of thy)
   405            {classrel =
   406               fn (th, c1) => fn c2 => th RS the_classrel thy (c1, c2),
   407             constructor =
   408               fn a => fn dom => fn c =>
   409                 let val Ss = map (map snd) dom and ths = maps (map fst) dom
   410                 in ths MRS the_arity thy a (c, Ss) end,
   411             variable =
   412               the_default [] o AList.lookup (op =) hyps};
   413       in ths end;
   414 
   415 in
   416 
   417 fun of_sort thy (typ, sort) cache =
   418   let
   419     val sort' = filter (is_none o lookup_type cache typ) sort;
   420     val ths' = derive_type thy (typ, sort')
   421       handle ERROR msg => cat_error msg ("The error(s) above occurred for sort derivation: " ^
   422         Sign.string_of_typ thy typ ^ " :: " ^ Sign.string_of_sort thy sort');
   423     val cache' = cache |> fold (insert_type typ) (sort' ~~ ths');
   424     val ths =
   425       sort |> map (fn c =>
   426         Goal.finish (the (lookup_type cache' typ c) RS
   427           Goal.init (Thm.cterm_of thy (Logic.mk_inclass (typ, c))))
   428         |> Thm.adjust_maxidx_thm ~1);
   429   in (ths, cache') end;
   430 
   431 end;
   432 
   433 end;