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