src/Pure/axclass.ML
author haftmann
Sat Sep 15 19:27:44 2007 +0200 (2007-09-15)
changeset 24589 d3fca349736c
parent 24271 499608101177
child 24681 9d4982db0742
permissions -rw-r--r--
clarified class interfaces and internals
     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     (*FIXME is ProofContext.cert_propp really neccessary?*)
   309     val axiomss = ProofContext.cert_propp (ctxt, map (map (rpair []) o snd) raw_specs)
   310       |> snd |> map (map (prep_axiom o fst));
   311     val name_atts = map fst raw_specs;
   312 
   313 
   314     (* definition *)
   315 
   316     val conjs = map (curry Logic.mk_inclass (Term.aT [])) super @ flat axiomss;
   317     val class_eq =
   318       Logic.mk_equals (Logic.mk_inclass (Term.aT [], class), Logic.mk_conjunction_balanced conjs);
   319 
   320     val ([def], def_thy) =
   321       thy
   322       |> Sign.primitive_class (bclass, super)
   323       |> PureThy.add_defs_i false [((Thm.def_name bconst, class_eq), [])];
   324     val (raw_intro, (raw_classrel, raw_axioms)) =
   325       split_defined (length conjs) def ||> chop (length super);
   326 
   327 
   328     (* facts *)
   329 
   330     val class_triv = Thm.class_triv def_thy class;
   331     val ([(_, [intro]), (_, classrel), (_, axioms)], facts_thy) =
   332       def_thy
   333       |> PureThy.note_thmss_qualified "" bconst
   334         [((introN, []), [([Drule.standard raw_intro], [])]),
   335          ((superN, []), [(map Drule.standard raw_classrel, [])]),
   336          ((axiomsN, []), [(map (fn th => Drule.standard (class_triv RS th)) raw_axioms, [])])];
   337 
   338     (* params *)
   339 
   340     val params_typs = map (fn param =>
   341       let
   342         val ty = Sign.the_const_type thy param;
   343         val _ = case Term.typ_tvars ty
   344          of [_] => ()
   345           | _ => error ("Exactly one type variable required in parameter " ^ quote param);
   346         val ty' = Term.map_type_tvar (fn _ => TFree (param_tyvarname, [class])) ty;
   347       in (param, ty') end) params;
   348 
   349     (* result *)
   350 
   351     val axclass = make_axclass ((def, intro, axioms), params_typs);
   352     val result_thy =
   353       facts_thy
   354       |> fold put_classrel (map (pair class) super ~~ classrel)
   355       |> Sign.add_path bconst
   356       |> PureThy.note_thmss_i "" (name_atts ~~ map Thm.simple_fact (unflat axiomss axioms)) |> snd
   357       |> Sign.restore_naming facts_thy
   358       |> map_axclasses (fn (axclasses, parameters) =>
   359         (Symtab.update (class, axclass) axclasses,
   360           fold (fn x => add_param pp (x, class)) params parameters));
   361 
   362   in (class, result_thy) end;
   363 
   364 
   365 
   366 (** axclasses with implicit parameter handling **)
   367 
   368 fun define_class_params (name, raw_superclasses) raw_consts raw_dep_axioms other_consts thy =
   369   let
   370     val superclasses = map (Sign.certify_class thy) raw_superclasses;
   371     val consts = (map o apfst o apsnd) (Sign.certify_typ thy) raw_consts;
   372     val prefix = Logic.const_of_class name;
   373     fun mk_const_name c = NameSpace.map_base (NameSpace.append prefix)
   374       (Sign.full_name thy c);
   375     fun add_const ((c, ty), syn) =
   376       Sign.add_consts_authentic [(c, ty, syn)]
   377       #> pair (mk_const_name c, ty);
   378     fun mk_axioms cs thy =
   379       raw_dep_axioms thy cs
   380       |> (map o apsnd o map) (Sign.cert_prop thy)
   381       |> rpair thy;
   382     fun add_constraint class (c, ty) =
   383       Sign.add_const_constraint_i (c, SOME
   384         (Term.map_type_tfree (fn (v, _) => TFree (v, [class])) ty));
   385   in
   386     thy
   387     |> Theory.add_path prefix
   388     |> fold_map add_const consts
   389     ||> Theory.restore_naming thy
   390     |-> (fn cs => mk_axioms cs
   391     #-> (fn axioms_prop => define_class (name, superclasses)
   392            (map fst cs @ other_consts) axioms_prop
   393     #-> (fn class => `(fn thy => get_definition thy class)
   394     #-> (fn {axioms, ...} => fold (add_constraint class) cs
   395     #> pair (class, (cs, axioms))))))
   396   end;
   397 
   398 
   399 
   400 (** axiomatizations **)
   401 
   402 local
   403 
   404 fun axiomatize prep mk name add raw_args thy =
   405   let
   406     val args = prep thy raw_args;
   407     val specs = mk args;
   408     val names = name args;
   409   in thy |> PureThy.add_axioms_i (map (rpair []) (names ~~ specs)) |-> fold add end;
   410 
   411 fun ax_classrel prep =
   412   axiomatize (map o prep) (map Logic.mk_classrel)
   413     (map (prefix classrel_prefix o Logic.name_classrel)) add_classrel;
   414 
   415 fun ax_arity prep =
   416   axiomatize prep Logic.mk_arities
   417     (map (prefix arity_prefix) o Logic.name_arities) add_arity;
   418 
   419 fun class_const c =
   420   (Logic.const_of_class c, Term.itselfT (Term.aT []) --> propT);
   421 
   422 fun ax_class prep_class prep_classrel (bclass, raw_super) thy =
   423   let
   424     val class = Sign.full_name thy bclass;
   425     val super = map (prep_class thy) raw_super |> Sign.certify_sort thy;
   426   in
   427     thy
   428     |> Sign.primitive_class (bclass, super)
   429     |> ax_classrel prep_classrel (map (fn c => (class, c)) super)
   430     |> Theory.add_deps "" (class_const class) (map class_const super)
   431   end;
   432 
   433 in
   434 
   435 val axiomatize_class = ax_class Sign.read_class read_classrel;
   436 val axiomatize_class_i = ax_class Sign.certify_class cert_classrel;
   437 val axiomatize_classrel = ax_classrel read_classrel;
   438 val axiomatize_classrel_i = ax_classrel cert_classrel;
   439 val axiomatize_arity = ax_arity Sign.read_arity;
   440 val axiomatize_arity_i = ax_arity Sign.cert_arity;
   441 
   442 end;
   443 
   444 
   445 
   446 (** explicit derivations -- cached **)
   447 
   448 datatype cache = Types of (class * thm) list Typtab.table;
   449 val cache = Types Typtab.empty;
   450 
   451 local
   452 
   453 fun lookup_type (Types cache) = AList.lookup (op =) o Typtab.lookup_list cache;
   454 fun insert_type T der (Types cache) = Types (Typtab.insert_list (eq_fst op =) (T, der) cache);
   455 
   456 fun derive_type _ (_, []) = []
   457   | derive_type thy (typ, sort) =
   458       let
   459         val vars = Term.fold_atyps
   460             (fn T as TFree (_, S) => insert (eq_fst op =) (T, S)
   461               | T as TVar (_, S) => insert (eq_fst op =) (T, S)
   462               | _ => I) typ [];
   463         val hyps = vars
   464           |> map (fn (T, S) => (T, Drule.sort_triv thy (T, S) ~~ S));
   465         val ths = (typ, sort) |> Sorts.of_sort_derivation (Sign.pp thy) (Sign.classes_of thy)
   466            {class_relation =
   467               fn (th, c1) => fn c2 => th RS the_classrel thy (c1, c2),
   468             type_constructor =
   469               fn a => fn dom => fn c =>
   470                 let val Ss = map (map snd) dom and ths = maps (map fst) dom
   471                 in ths MRS the_arity thy a (c, Ss) end,
   472             type_variable =
   473               the_default [] o AList.lookup (op =) hyps};
   474       in ths end;
   475 
   476 in
   477 
   478 fun of_sort thy (typ, sort) cache =
   479   let
   480     val sort' = filter (is_none o lookup_type cache typ) sort;
   481     val ths' = derive_type thy (typ, sort')
   482       handle ERROR msg => cat_error msg ("The error(s) above occurred for sort derivation: " ^
   483         Sign.string_of_typ thy typ ^ " :: " ^ Sign.string_of_sort thy sort');
   484     val cache' = cache |> fold (insert_type typ) (sort' ~~ ths');
   485     val ths =
   486       sort |> map (fn c =>
   487         Goal.finish (the (lookup_type cache' typ c) RS
   488           Goal.init (Thm.cterm_of thy (Logic.mk_inclass (typ, c))))
   489         |> Thm.adjust_maxidx_thm ~1);
   490   in (ths, cache') end;
   491 
   492 end;
   493 
   494 end;