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