src/Pure/axclass.ML
author wenzelm
Thu Oct 04 20:29:13 2007 +0200 (2007-10-04 ago)
changeset 24847 bc15dcaed517
parent 24770 695a8e087b9f
child 24920 2a45e400fdad
permissions -rw-r--r--
replaced AxClass.param_tyvarname by Name.aT;
     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 print_axclasses: theory -> unit
    27   val cert_classrel: theory -> class * class -> class * class
    28   val read_classrel: theory -> xstring * xstring -> class * class
    29   val axiomatize_class: bstring * xstring list -> theory -> theory
    30   val axiomatize_class_i: bstring * class list -> theory -> theory
    31   val axiomatize_classrel: (xstring * xstring) list -> theory -> theory
    32   val axiomatize_classrel_i: (class * class) list -> theory -> theory
    33   val axiomatize_arity: xstring * string list * string -> theory -> theory
    34   val axiomatize_arity_i: arity -> theory -> theory
    35   type cache
    36   val cache: cache
    37   val of_sort: theory -> typ * sort -> cache -> thm list * cache  (*exception Sorts.CLASS_ERROR*)
    38 end;
    39 
    40 structure AxClass: AX_CLASS =
    41 struct
    42 
    43 (** theory data **)
    44 
    45 (* class parameters (canonical order) *)
    46 
    47 type param = string * class;
    48 
    49 fun add_param pp ((x, c): param) params =
    50   (case AList.lookup (op =) params x of
    51     NONE => (x, c) :: params
    52   | SOME c' => error ("Duplicate class parameter " ^ quote x ^
    53       " for " ^ Pretty.string_of_sort pp [c] ^
    54       (if c = c' then "" else " and " ^ Pretty.string_of_sort pp [c'])));
    55 
    56 fun merge_params _ ([], qs) = qs
    57   | merge_params pp (ps, qs) =
    58       fold_rev (fn q => if member (op =) ps q then I else add_param pp q) qs ps;
    59 
    60 
    61 (* axclasses *)
    62 
    63 val introN = "intro";
    64 val superN = "super";
    65 val axiomsN = "axioms";
    66 
    67 datatype axclass = AxClass of
    68  {def: thm,
    69   intro: thm,
    70   axioms: thm list,
    71   params: (string * typ) list};
    72 
    73 type axclasses = axclass Symtab.table * param list;
    74 
    75 fun make_axclass ((def, intro, axioms), params) =
    76   AxClass {def = def, intro = intro, axioms = axioms, params = params};
    77 
    78 fun merge_axclasses pp ((tab1, params1), (tab2, params2)) : axclasses =
    79   (Symtab.merge (K true) (tab1, tab2), merge_params pp (params1, params2));
    80 
    81 
    82 (* instances *)
    83 
    84 val classrel_prefix = "classrel_";
    85 val arity_prefix = "arity_";
    86 
    87 type instances =
    88   ((class * class) * thm) list *
    89   ((class * sort list) * thm) list Symtab.table;
    90 
    91 fun merge_instances ((classrel1, arities1): instances, (classrel2, arities2)) =
    92  (merge (eq_fst op =) (classrel1, classrel2),
    93   Symtab.join (K (merge (eq_fst op =))) (arities1, arities2));
    94 
    95 
    96 (* setup data *)
    97 
    98 structure AxClassData = TheoryDataFun
    99 (
   100   type T = axclasses * instances;
   101   val empty = ((Symtab.empty, []), ([], Symtab.empty));
   102   val copy = I;
   103   val extend = I;
   104   fun merge pp ((axclasses1, instances1), (axclasses2, instances2)) =
   105     (merge_axclasses pp (axclasses1, axclasses2), (merge_instances (instances1, instances2)));
   106 );
   107 
   108 
   109 (* maintain axclasses *)
   110 
   111 val get_axclasses = #1 o AxClassData.get;
   112 fun map_axclasses f = AxClassData.map (apfst f);
   113 
   114 val lookup_def = Symtab.lookup o #1 o get_axclasses;
   115 
   116 fun get_definition thy c =
   117   (case lookup_def thy c of
   118     SOME (AxClass info) => info
   119   | NONE => error ("No such axclass: " ^ quote c));
   120 
   121 fun class_intros thy =
   122   let
   123     fun add_intro c =
   124       (case lookup_def thy c of SOME (AxClass {intro, ...}) => cons intro | _ => I);
   125     val classes = Sign.all_classes thy;
   126   in map (Thm.class_triv thy) classes @ fold add_intro classes [] end;
   127 
   128 
   129 fun get_params thy pred =
   130   let val params = #2 (get_axclasses thy);
   131   in fold (fn (x, c) => if pred c then cons x else I) params [] end;
   132 
   133 fun params_of thy c = get_params thy (fn c' => c' = c);
   134 fun all_params_of thy S = get_params thy (fn c => Sign.subsort thy (S, [c]));
   135 
   136 fun class_of_param thy =
   137   AList.lookup (op =) (#2 (get_axclasses thy));
   138 
   139 fun params_of_class thy class = (Name.aT, #params (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 _ = map (Sign.certify_sort thy) Ss = Ss orelse 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.minimize_sort thy (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     val axiomss = map (map (prep_axiom o Sign.cert_prop thy) o snd) raw_specs;
   305     val name_atts = map fst raw_specs;
   306 
   307 
   308     (* definition *)
   309 
   310     val conjs = map (curry Logic.mk_inclass (Term.aT [])) super @ flat axiomss;
   311     val class_eq =
   312       Logic.mk_equals (Logic.mk_inclass (Term.aT [], class), Logic.mk_conjunction_balanced conjs);
   313 
   314     val ([def], def_thy) =
   315       thy
   316       |> Sign.primitive_class (bclass, super)
   317       |> PureThy.add_defs_i false [((Thm.def_name bconst, class_eq), [])];
   318     val (raw_intro, (raw_classrel, raw_axioms)) =
   319       split_defined (length conjs) def ||> chop (length super);
   320 
   321 
   322     (* facts *)
   323 
   324     val class_triv = Thm.class_triv def_thy class;
   325     val ([(_, [intro]), (_, classrel), (_, axioms)], facts_thy) =
   326       def_thy
   327       |> PureThy.note_thmss_qualified "" bconst
   328         [((introN, []), [([Drule.standard raw_intro], [])]),
   329          ((superN, []), [(map Drule.standard raw_classrel, [])]),
   330          ((axiomsN, []), [(map (fn th => Drule.standard (class_triv RS th)) raw_axioms, [])])];
   331 
   332     (* params *)
   333 
   334     val params_typs = map (fn param =>
   335       let
   336         val ty = Sign.the_const_type thy param;
   337         val _ = case Term.typ_tvars ty
   338          of [_] => ()
   339           | _ => error ("Exactly one type variable required in parameter " ^ quote param);
   340         val ty' = Term.map_type_tvar (fn _ => TFree (Name.aT, [class])) ty;
   341       in (param, ty') end) params;
   342 
   343 
   344     (* result *)
   345 
   346     val axclass = make_axclass ((def, intro, axioms), params_typs);
   347     val result_thy =
   348       facts_thy
   349       |> fold put_classrel (map (pair class) super ~~ classrel)
   350       |> Sign.add_path bconst
   351       |> PureThy.note_thmss_i "" (name_atts ~~ map Thm.simple_fact (unflat axiomss axioms)) |> snd
   352       |> Sign.restore_naming facts_thy
   353       |> map_axclasses (fn (axclasses, parameters) =>
   354         (Symtab.update (class, axclass) axclasses,
   355           fold (fn x => add_param pp (x, class)) params parameters));
   356 
   357   in (class, result_thy) end;
   358 
   359 
   360 
   361 (** axclasses with implicit parameter handling **)
   362 
   363 fun define_class_params (name, raw_superclasses) raw_consts raw_dep_axioms other_consts thy =
   364   let
   365     val superclasses = map (Sign.certify_class thy) raw_superclasses;
   366     val consts = (map o apfst o apsnd) (Sign.certify_typ thy) raw_consts;
   367     val prefix = Logic.const_of_class name;
   368     fun mk_const_name c = NameSpace.map_base (NameSpace.append prefix)
   369       (Sign.full_name thy c);
   370     fun add_const ((c, ty), syn) =
   371       Sign.add_consts_authentic [] [(c, ty, syn)]
   372       #> pair (mk_const_name c, ty);
   373     fun mk_axioms cs thy =
   374       raw_dep_axioms thy cs
   375       |> (map o apsnd o map) (Sign.cert_prop thy)
   376       |> rpair thy;
   377     fun add_constraint class (c, ty) =
   378       Sign.add_const_constraint (c, SOME
   379         (Term.map_type_tfree (fn (v, _) => TFree (v, [class])) ty));
   380   in
   381     thy
   382     |> Sign.add_path prefix
   383     |> fold_map add_const consts
   384     ||> Sign.restore_naming thy
   385     |-> (fn cs => mk_axioms cs
   386     #-> (fn axioms_prop => define_class (name, superclasses)
   387            (map fst cs @ other_consts) axioms_prop
   388     #-> (fn class => `(fn thy => get_definition thy class)
   389     #-> (fn {axioms, ...} => fold (add_constraint class) cs
   390     #> pair (class, (cs, axioms))))))
   391   end;
   392 
   393 
   394 
   395 (** axiomatizations **)
   396 
   397 local
   398 
   399 fun axiomatize prep mk name add raw_args thy =
   400   let
   401     val args = prep thy raw_args;
   402     val specs = mk args;
   403     val names = name args;
   404   in thy |> PureThy.add_axioms_i (map (rpair []) (names ~~ specs)) |-> fold add end;
   405 
   406 fun ax_classrel prep =
   407   axiomatize (map o prep) (map Logic.mk_classrel)
   408     (map (prefix classrel_prefix o Logic.name_classrel)) add_classrel;
   409 
   410 fun ax_arity prep =
   411   axiomatize prep Logic.mk_arities
   412     (map (prefix arity_prefix) o Logic.name_arities) add_arity;
   413 
   414 fun class_const c =
   415   (Logic.const_of_class c, Term.itselfT (Term.aT []) --> propT);
   416 
   417 fun ax_class prep_class prep_classrel (bclass, raw_super) thy =
   418   let
   419     val class = Sign.full_name thy bclass;
   420     val super = map (prep_class thy) raw_super |> Sign.minimize_sort thy;
   421   in
   422     thy
   423     |> Sign.primitive_class (bclass, super)
   424     |> ax_classrel prep_classrel (map (fn c => (class, c)) super)
   425     |> Theory.add_deps "" (class_const class) (map class_const super)
   426   end;
   427 
   428 in
   429 
   430 val axiomatize_class = ax_class Sign.read_class read_classrel;
   431 val axiomatize_class_i = ax_class Sign.certify_class cert_classrel;
   432 val axiomatize_classrel = ax_classrel read_classrel;
   433 val axiomatize_classrel_i = ax_classrel cert_classrel;
   434 val axiomatize_arity = ax_arity Sign.read_arity;
   435 val axiomatize_arity_i = ax_arity Sign.cert_arity;
   436 
   437 end;
   438 
   439 
   440 
   441 (** explicit derivations -- cached **)
   442 
   443 datatype cache = Types of (class * thm) list Typtab.table;
   444 val cache = Types Typtab.empty;
   445 
   446 local
   447 
   448 fun lookup_type (Types cache) = AList.lookup (op =) o Typtab.lookup_list cache;
   449 fun insert_type T der (Types cache) = Types (Typtab.insert_list (eq_fst op =) (T, der) cache);
   450 
   451 fun derive_type _ (_, []) = []
   452   | derive_type thy (typ, sort) =
   453       let
   454         val vars = Term.fold_atyps
   455             (fn T as TFree (_, S) => insert (eq_fst op =) (T, S)
   456               | T as TVar (_, S) => insert (eq_fst op =) (T, S)
   457               | _ => I) typ [];
   458         val hyps = vars
   459           |> map (fn (T, S) => (T, Drule.sort_triv thy (T, S) ~~ S));
   460         val ths = (typ, sort) |> Sorts.of_sort_derivation (Sign.pp thy) (Sign.classes_of thy)
   461            {class_relation =
   462               fn (th, c1) => fn c2 => th RS the_classrel thy (c1, c2),
   463             type_constructor =
   464               fn a => fn dom => fn c =>
   465                 let val Ss = map (map snd) dom and ths = maps (map fst) dom
   466                 in ths MRS the_arity thy a (c, Ss) end,
   467             type_variable =
   468               the_default [] o AList.lookup (op =) hyps};
   469       in ths end;
   470 
   471 in
   472 
   473 fun of_sort thy (typ, sort) cache =
   474   let
   475     val sort' = filter (is_none o lookup_type cache typ) sort;
   476     val ths' = derive_type thy (typ, sort')
   477       handle ERROR msg => cat_error msg ("The error(s) above occurred for sort derivation: " ^
   478         Sign.string_of_typ thy typ ^ " :: " ^ Sign.string_of_sort thy sort');
   479     val cache' = cache |> fold (insert_type typ) (sort' ~~ ths');
   480     val ths =
   481       sort |> map (fn c =>
   482         Goal.finish (the (lookup_type cache' typ c) RS
   483           Goal.init (Thm.cterm_of thy (Logic.mk_inclass (typ, c))))
   484         |> Thm.adjust_maxidx_thm ~1);
   485   in (ths, cache') end;
   486 
   487 end;
   488 
   489 end;