src/Pure/axclass.ML
author haftmann
Fri Nov 10 07:44:47 2006 +0100 (2006-11-10)
changeset 21286 b5e7b80caa6a
parent 20628 b15b6f05d145
child 21463 42dd50268c8b
permissions -rw-r--r--
introduces canonical AList functions for loop_tacs
     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 classrel_prefix = "classrel_";
    82 val arity_prefix = "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 [((prefix classrel_prefix (Logic.name_classrel (c1, c2)), 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 names = map (prefix arity_prefix) (Logic.name_arities arity);
   250     val props = Logic.mk_arities arity;
   251     val ths = Goal.prove_multi (ProofContext.init thy) [] [] props
   252       (fn _ => Tactic.precise_conjunction_tac (length props) 1 THEN tac) handle ERROR msg =>
   253         cat_error msg ("The error(s) above occurred while trying to prove type arity " ^
   254           quote (Sign.string_of_arity thy arity));
   255   in
   256     thy
   257     |> PureThy.add_thms (map (rpair []) (names ~~ ths))
   258     |-> fold add_arity
   259   end;
   260 
   261 
   262 
   263 (** class definitions **)
   264 
   265 local
   266 
   267 fun def_class prep_class prep_att prep_propp
   268     (bclass, raw_super) params raw_specs thy =
   269   let
   270     val ctxt = ProofContext.init thy;
   271     val pp = ProofContext.pp ctxt;
   272 
   273 
   274     (* prepare specification *)
   275 
   276     val bconst = Logic.const_of_class bclass;
   277     val class = Sign.full_name thy bclass;
   278     val super = map (prep_class thy) raw_super |> Sign.certify_sort thy;
   279 
   280     fun prep_axiom t =
   281       (case Term.add_tfrees t [] of
   282         [(a, S)] =>
   283           if Sign.subsort thy (super, S) then t
   284           else error ("Sort constraint of type variable " ^
   285             setmp show_sorts true (Pretty.string_of_typ pp) (TFree (a, S)) ^
   286             " needs to be weaker than " ^ Pretty.string_of_sort pp super)
   287       | [] => t
   288       | _ => error ("Multiple type variables in class axiom:\n" ^ Pretty.string_of_term pp t))
   289       |> map_types (Term.map_atyps (fn TFree _ => Term.aT [] | U => U))
   290       |> Logic.close_form;
   291 
   292     val axiomss = prep_propp (ctxt, map (map (rpair []) o snd) raw_specs)
   293       |> snd |> map (map (prep_axiom o fst));
   294     val name_atts = Attrib.map_specs (prep_att thy) raw_specs |> map fst;
   295 
   296 
   297     (* definition *)
   298 
   299     val conjs = map (curry Logic.mk_inclass (Term.aT [])) super @ flat axiomss;
   300     val class_eq =
   301       Logic.mk_equals (Logic.mk_inclass (Term.aT [], class), Logic.mk_conjunction_list conjs);
   302 
   303     val ([def], def_thy) =
   304       thy
   305       |> Sign.primitive_class (bclass, super)
   306       |> PureThy.add_defs_i false [((Thm.def_name bconst, class_eq), [])];
   307     val (raw_intro, (raw_classrel, raw_axioms)) =
   308       (Conjunction.split_defined (length conjs) def) ||> chop (length super);
   309 
   310 
   311     (* facts *)
   312 
   313     val class_triv = Thm.class_triv def_thy class;
   314     val ([(_, [intro]), (_, classrel), (_, axioms)], facts_thy) =
   315       def_thy
   316       |> PureThy.note_thmss_qualified "" bconst
   317         [((introN, []), [([Drule.standard raw_intro], [])]),
   318          ((superN, []), [(map Drule.standard raw_classrel, [])]),
   319          ((axiomsN, []), [(map (fn th => Drule.standard (class_triv RS th)) raw_axioms, [])])];
   320 
   321 
   322     (* result *)
   323 
   324     val result_thy =
   325       facts_thy
   326       |> fold put_classrel (map (pair class) super ~~ classrel)
   327       |> Sign.add_path bconst
   328       |> PureThy.note_thmss_i "" (name_atts ~~ map Thm.simple_fact (unflat axiomss axioms)) |> snd
   329       |> Sign.restore_naming facts_thy
   330       |> map_axclasses (fn (axclasses, parameters) =>
   331         (Symtab.update (class, make_axclass (def, intro, axioms)) axclasses,
   332           fold (fn x => add_param pp (x, class)) params parameters));
   333 
   334   in (class, result_thy) end;
   335 
   336 in
   337 
   338 val define_class = def_class Sign.read_class Attrib.attribute ProofContext.read_propp;
   339 val define_class_i = def_class Sign.certify_class (K I) ProofContext.cert_propp;
   340 
   341 end;
   342 
   343 
   344 
   345 (** axiomatizations **)
   346 
   347 local
   348 
   349 fun axiomatize prep mk name add raw_args thy =
   350   let
   351     val args = prep thy raw_args;
   352     val specs = mk args;
   353     val names = name args;
   354   in thy |> PureThy.add_axioms_i (map (rpair []) (names ~~ specs)) |-> fold add end;
   355 
   356 fun ax_classrel prep =
   357   axiomatize (map o prep) (map Logic.mk_classrel)
   358     (map (prefix classrel_prefix o Logic.name_classrel)) add_classrel;
   359 
   360 fun ax_arity prep =
   361   axiomatize prep Logic.mk_arities
   362     (map (prefix arity_prefix) o Logic.name_arities) add_arity;
   363 
   364 fun class_const c =
   365   (Logic.const_of_class c, Term.itselfT (Term.aT []) --> propT);
   366 
   367 fun ax_class prep_class prep_classrel (bclass, raw_super) thy =
   368   let
   369     val class = Sign.full_name thy bclass;
   370     val super = map (prep_class thy) raw_super |> Sign.certify_sort thy;
   371   in
   372     thy
   373     |> Sign.primitive_class (bclass, super)
   374     |> ax_classrel prep_classrel (map (fn c => (class, c)) super)
   375     |> Theory.add_deps "" (class_const class) (map class_const super)
   376   end;
   377 
   378 in
   379 
   380 val axiomatize_class = ax_class Sign.read_class read_classrel;
   381 val axiomatize_class_i = ax_class Sign.certify_class cert_classrel;
   382 val axiomatize_classrel = ax_classrel read_classrel;
   383 val axiomatize_classrel_i = ax_classrel cert_classrel;
   384 val axiomatize_arity = ax_arity Sign.read_arity;
   385 val axiomatize_arity_i = ax_arity Sign.cert_arity;
   386 
   387 end;
   388 
   389 
   390 
   391 (** explicit derivations -- cached **)
   392 
   393 datatype cache = Types of (class * thm) list Typtab.table;
   394 val cache = Types Typtab.empty;
   395 
   396 local
   397 
   398 fun lookup_type (Types cache) = AList.lookup (op =) o Typtab.lookup_list cache;
   399 fun insert_type T der (Types cache) = Types (Typtab.insert_list (eq_fst op =) (T, der) cache);
   400 
   401 fun derive_type _ (_, []) = []
   402   | derive_type thy (typ, sort) =
   403       let
   404         val vars = Term.fold_atyps
   405             (fn T as TFree (_, S) => insert (eq_fst op =) (T, S)
   406               | T as TVar (_, S) => insert (eq_fst op =) (T, S)
   407               | _ => I) typ [];
   408         val hyps = vars
   409           |> map (fn (T, S) => (T, Drule.sort_triv thy (T, S) ~~ S));
   410         val ths = (typ, sort) |> Sorts.of_sort_derivation (Sign.pp thy) (Sign.classes_of thy)
   411            {classrel =
   412               fn (th, c1) => fn c2 => th RS the_classrel thy (c1, c2),
   413             constructor =
   414               fn a => fn dom => fn c =>
   415                 let val Ss = map (map snd) dom and ths = maps (map fst) dom
   416                 in ths MRS the_arity thy a (c, Ss) end,
   417             variable =
   418               the_default [] o AList.lookup (op =) hyps};
   419       in ths end;
   420 
   421 in
   422 
   423 fun of_sort thy (typ, sort) cache =
   424   let
   425     val sort' = filter (is_none o lookup_type cache typ) sort;
   426     val ths' = derive_type thy (typ, sort')
   427       handle ERROR msg => cat_error msg ("The error(s) above occurred for sort derivation: " ^
   428         Sign.string_of_typ thy typ ^ " :: " ^ Sign.string_of_sort thy sort');
   429     val cache' = cache |> fold (insert_type typ) (sort' ~~ ths');
   430     val ths =
   431       sort |> map (fn c =>
   432         Goal.finish (the (lookup_type cache' typ c) RS
   433           Goal.init (Thm.cterm_of thy (Logic.mk_inclass (typ, c))))
   434         |> Thm.adjust_maxidx_thm ~1);
   435   in (ths, cache') end;
   436 
   437 end;
   438 
   439 end;