src/Pure/axclass.ML
author wenzelm
Tue Aug 14 23:22:51 2007 +0200 (2007-08-14)
changeset 24271 499608101177
parent 23421 c9007fc4a646
child 24589 d3fca349736c
permissions -rw-r--r--
avoid low-level tsig;
     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 _ = Sign.primitive_classrel (c1, c2) (Theory.copy 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 split_defined n eq =
   267   let
   268     val intro =
   269       (eq RS Drule.equal_elim_rule2)
   270       |> Conjunction.curry_balanced n
   271       |> n = 0 ? Thm.eq_assumption 1;
   272     val dests =
   273       if n = 0 then []
   274       else
   275         (eq RS Drule.equal_elim_rule1)
   276         |> BalancedTree.dest (fn th =>
   277           (th RS Conjunction.conjunctionD1, th RS Conjunction.conjunctionD2)) n;
   278   in (intro, dests) end;
   279 
   280 fun define_class (bclass, raw_super) params raw_specs thy =
   281   let
   282     val ctxt = ProofContext.init thy;
   283     val pp = ProofContext.pp ctxt;
   284 
   285 
   286     (* prepare specification *)
   287 
   288     val bconst = Logic.const_of_class bclass;
   289     val class = Sign.full_name thy bclass;
   290     val super = Sign.certify_sort thy raw_super;
   291 
   292     fun prep_axiom t =
   293       (case Term.add_tfrees t [] of
   294         [(a, S)] =>
   295           if Sign.subsort thy (super, S) then t
   296           else error ("Sort constraint of type variable " ^
   297             setmp show_sorts true (Pretty.string_of_typ pp) (TFree (a, S)) ^
   298             " needs to be weaker than " ^ Pretty.string_of_sort pp super)
   299       | [] => t
   300       | _ => error ("Multiple type variables in class axiom:\n" ^ Pretty.string_of_term pp t))
   301       |> map_types (Term.map_atyps (fn TFree _ => Term.aT [] | U => U))
   302       |> Logic.close_form;
   303 
   304     (*FIXME is ProofContext.cert_propp really neccessary?*)
   305     val axiomss = ProofContext.cert_propp (ctxt, map (map (rpair []) o snd) raw_specs)
   306       |> snd |> map (map (prep_axiom o fst));
   307     val name_atts = map fst raw_specs;
   308 
   309 
   310     (* definition *)
   311 
   312     val conjs = map (curry Logic.mk_inclass (Term.aT [])) super @ flat axiomss;
   313     val class_eq =
   314       Logic.mk_equals (Logic.mk_inclass (Term.aT [], class), Logic.mk_conjunction_balanced conjs);
   315 
   316     val ([def], def_thy) =
   317       thy
   318       |> Sign.primitive_class (bclass, super)
   319       |> PureThy.add_defs_i false [((Thm.def_name bconst, class_eq), [])];
   320     val (raw_intro, (raw_classrel, raw_axioms)) =
   321       split_defined (length conjs) def ||> chop (length super);
   322 
   323 
   324     (* facts *)
   325 
   326     val class_triv = Thm.class_triv def_thy class;
   327     val ([(_, [intro]), (_, classrel), (_, axioms)], facts_thy) =
   328       def_thy
   329       |> PureThy.note_thmss_qualified "" bconst
   330         [((introN, []), [([Drule.standard raw_intro], [])]),
   331          ((superN, []), [(map Drule.standard raw_classrel, [])]),
   332          ((axiomsN, []), [(map (fn th => Drule.standard (class_triv RS th)) raw_axioms, [])])];
   333 
   334     (* params *)
   335 
   336     val params_typs = map (fn param =>
   337       let
   338         val ty = Sign.the_const_type thy param;
   339         val _ = case Term.typ_tvars ty
   340          of [_] => ()
   341           | _ => error ("Exactly one type variable required in parameter " ^ quote param);
   342         val ty' = Term.map_type_tvar (fn _ => TFree (param_tyvarname, [class])) ty;
   343       in (param, ty') end) params;
   344 
   345     (* result *)
   346 
   347     val axclass = make_axclass ((def, intro, axioms), params_typs);
   348     val result_thy =
   349       facts_thy
   350       |> fold put_classrel (map (pair class) super ~~ classrel)
   351       |> Sign.add_path bconst
   352       |> PureThy.note_thmss_i "" (name_atts ~~ map Thm.simple_fact (unflat axiomss axioms)) |> snd
   353       |> Sign.restore_naming facts_thy
   354       |> map_axclasses (fn (axclasses, parameters) =>
   355         (Symtab.update (class, axclass) axclasses,
   356           fold (fn x => add_param pp (x, class)) params parameters));
   357 
   358   in (class, result_thy) end;
   359 
   360 
   361 
   362 (** axiomatizations **)
   363 
   364 local
   365 
   366 fun axiomatize prep mk name add raw_args thy =
   367   let
   368     val args = prep thy raw_args;
   369     val specs = mk args;
   370     val names = name args;
   371   in thy |> PureThy.add_axioms_i (map (rpair []) (names ~~ specs)) |-> fold add end;
   372 
   373 fun ax_classrel prep =
   374   axiomatize (map o prep) (map Logic.mk_classrel)
   375     (map (prefix classrel_prefix o Logic.name_classrel)) add_classrel;
   376 
   377 fun ax_arity prep =
   378   axiomatize prep Logic.mk_arities
   379     (map (prefix arity_prefix) o Logic.name_arities) add_arity;
   380 
   381 fun class_const c =
   382   (Logic.const_of_class c, Term.itselfT (Term.aT []) --> propT);
   383 
   384 fun ax_class prep_class prep_classrel (bclass, raw_super) thy =
   385   let
   386     val class = Sign.full_name thy bclass;
   387     val super = map (prep_class thy) raw_super |> Sign.certify_sort thy;
   388   in
   389     thy
   390     |> Sign.primitive_class (bclass, super)
   391     |> ax_classrel prep_classrel (map (fn c => (class, c)) super)
   392     |> Theory.add_deps "" (class_const class) (map class_const super)
   393   end;
   394 
   395 in
   396 
   397 val axiomatize_class = ax_class Sign.read_class read_classrel;
   398 val axiomatize_class_i = ax_class Sign.certify_class cert_classrel;
   399 val axiomatize_classrel = ax_classrel read_classrel;
   400 val axiomatize_classrel_i = ax_classrel cert_classrel;
   401 val axiomatize_arity = ax_arity Sign.read_arity;
   402 val axiomatize_arity_i = ax_arity Sign.cert_arity;
   403 
   404 end;
   405 
   406 
   407 
   408 (** explicit derivations -- cached **)
   409 
   410 datatype cache = Types of (class * thm) list Typtab.table;
   411 val cache = Types Typtab.empty;
   412 
   413 local
   414 
   415 fun lookup_type (Types cache) = AList.lookup (op =) o Typtab.lookup_list cache;
   416 fun insert_type T der (Types cache) = Types (Typtab.insert_list (eq_fst op =) (T, der) cache);
   417 
   418 fun derive_type _ (_, []) = []
   419   | derive_type thy (typ, sort) =
   420       let
   421         val vars = Term.fold_atyps
   422             (fn T as TFree (_, S) => insert (eq_fst op =) (T, S)
   423               | T as TVar (_, S) => insert (eq_fst op =) (T, S)
   424               | _ => I) typ [];
   425         val hyps = vars
   426           |> map (fn (T, S) => (T, Drule.sort_triv thy (T, S) ~~ S));
   427         val ths = (typ, sort) |> Sorts.of_sort_derivation (Sign.pp thy) (Sign.classes_of thy)
   428            {class_relation =
   429               fn (th, c1) => fn c2 => th RS the_classrel thy (c1, c2),
   430             type_constructor =
   431               fn a => fn dom => fn c =>
   432                 let val Ss = map (map snd) dom and ths = maps (map fst) dom
   433                 in ths MRS the_arity thy a (c, Ss) end,
   434             type_variable =
   435               the_default [] o AList.lookup (op =) hyps};
   436       in ths end;
   437 
   438 in
   439 
   440 fun of_sort thy (typ, sort) cache =
   441   let
   442     val sort' = filter (is_none o lookup_type cache typ) sort;
   443     val ths' = derive_type thy (typ, sort')
   444       handle ERROR msg => cat_error msg ("The error(s) above occurred for sort derivation: " ^
   445         Sign.string_of_typ thy typ ^ " :: " ^ Sign.string_of_sort thy sort');
   446     val cache' = cache |> fold (insert_type typ) (sort' ~~ ths');
   447     val ths =
   448       sort |> map (fn c =>
   449         Goal.finish (the (lookup_type cache' typ c) RS
   450           Goal.init (Thm.cterm_of thy (Logic.mk_inclass (typ, c))))
   451         |> Thm.adjust_maxidx_thm ~1);
   452   in (ths, cache') end;
   453 
   454 end;
   455 
   456 end;