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