src/Pure/axclass.ML
author wenzelm
Tue Oct 09 17:10:41 2007 +0200 (2007-10-09 ago)
changeset 24929 408becab067e
parent 24920 2a45e400fdad
child 24964 526df61afe97
permissions -rw-r--r--
renamed AxClass.get_definition to AxClass.get_info (again);
AxClass.axiomatize: renamed XXX_i to XXX, and XXX to XXX_cmd;
     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_info: 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 * class list -> theory -> theory
    30   val axiomatize_class_cmd: bstring * xstring list -> theory -> theory
    31   val axiomatize_classrel: (class * class) list -> theory -> theory
    32   val axiomatize_classrel_cmd: (xstring * xstring) list -> theory -> theory
    33   val axiomatize_arity: arity -> theory -> theory
    34   val axiomatize_arity_cmd: xstring * string list * string -> theory -> theory
    35   type cache
    36   val of_sort: theory -> typ * sort -> cache -> thm list * cache  (*exception Sorts.CLASS_ERROR*)
    37   val cache: cache
    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_info 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_info 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 " ^
   152       Syntax.string_of_classrel (ProofContext.init thy) [c1, c2]));
   153 
   154 fun put_classrel arg = map_instances (fn (classrel, arities) =>
   155   (insert (eq_fst op =) arg classrel, arities));
   156 
   157 
   158 fun the_arity thy a (c, Ss) =
   159   (case AList.lookup (op =) (Symtab.lookup_list (#2 (get_instances thy)) a) (c, Ss) of
   160     SOME th => Thm.transfer thy th
   161   | NONE => error ("Unproven type arity " ^
   162       Syntax.string_of_arity (ProofContext.init thy) (a, Ss, [c])));
   163 
   164 fun put_arity ((t, Ss, c), th) = map_instances (fn (classrel, arities) =>
   165   (classrel, arities |> Symtab.insert_list (eq_fst op =) (t, ((c, Ss), th))));
   166 
   167 
   168 (* print data *)
   169 
   170 fun print_axclasses thy =
   171   let
   172     val axclasses = #1 (get_axclasses thy);
   173     val ctxt = ProofContext.init thy;
   174 
   175     fun pretty_axclass (class, AxClass {def, intro, axioms, params}) =
   176       Pretty.block (Pretty.fbreaks
   177        [Pretty.block
   178           [Pretty.str "class ", Syntax.pretty_sort ctxt [class], Pretty.str ":"],
   179         Pretty.strs ("parameters:" :: params_of thy class),
   180         ProofContext.pretty_fact ctxt ("def", [def]),
   181         ProofContext.pretty_fact ctxt (introN, [intro]),
   182         ProofContext.pretty_fact ctxt (axiomsN, axioms)]);
   183   in Pretty.writeln (Pretty.chunks (map pretty_axclass (Symtab.dest axclasses))) end;
   184 
   185 
   186 
   187 (** instances **)
   188 
   189 (* class relations *)
   190 
   191 fun cert_classrel thy raw_rel =
   192   let
   193     val (c1, c2) = pairself (Sign.certify_class thy) raw_rel;
   194     val _ = Sign.primitive_classrel (c1, c2) (Theory.copy thy);
   195     val _ =
   196       (case subtract (op =) (all_params_of thy [c1]) (all_params_of thy [c2]) of
   197         [] => ()
   198       | xs => raise TYPE ("Class " ^ Sign.string_of_sort thy [c1] ^ " lacks parameter(s) " ^
   199           commas_quote xs ^ " of " ^ Sign.string_of_sort thy [c2], [], []));
   200   in (c1, c2) end;
   201 
   202 fun read_classrel thy raw_rel =
   203   cert_classrel thy (pairself (Sign.read_class thy) raw_rel)
   204     handle TYPE (msg, _, _) => error msg;
   205 
   206 
   207 (* primitive rules *)
   208 
   209 fun add_classrel th thy =
   210   let
   211     fun err () = raise THM ("add_classrel: malformed class relation", 0, [th]);
   212     val prop = Thm.plain_prop_of (Thm.transfer thy th);
   213     val rel = Logic.dest_classrel prop handle TERM _ => err ();
   214     val (c1, c2) = cert_classrel thy rel handle TYPE _ => err ();
   215   in
   216     thy
   217     |> Sign.primitive_classrel (c1, c2)
   218     |> put_classrel ((c1, c2), Drule.unconstrainTs th)
   219   end;
   220 
   221 fun add_arity th thy =
   222   let
   223     fun err () = raise THM ("add_arity: malformed type arity", 0, [th]);
   224     val prop = Thm.plain_prop_of (Thm.transfer thy th);
   225     val (t, Ss, c) = Logic.dest_arity prop handle TERM _ => err ();
   226     val _ = map (Sign.certify_sort thy) Ss = Ss orelse err ();
   227   in
   228     thy
   229     |> Sign.primitive_arity (t, Ss, [c])
   230     |> put_arity ((t, Ss, c), Drule.unconstrainTs th)
   231   end;
   232 
   233 
   234 (* tactical proofs *)
   235 
   236 fun prove_classrel raw_rel tac thy =
   237   let
   238     val ctxt = ProofContext.init thy;
   239     val (c1, c2) = cert_classrel thy raw_rel;
   240     val th = Goal.prove ctxt [] []
   241         (Logic.mk_classrel (c1, c2)) (fn _ => tac) handle ERROR msg =>
   242       cat_error msg ("The error(s) above occurred while trying to prove class relation " ^
   243         quote (Syntax.string_of_classrel ctxt [c1, c2]));
   244   in
   245     thy
   246     |> PureThy.add_thms [((prefix classrel_prefix (Logic.name_classrel (c1, c2)), th), [])]
   247     |-> (fn [th'] => add_classrel th')
   248   end;
   249 
   250 fun prove_arity raw_arity tac thy =
   251   let
   252     val ctxt = ProofContext.init thy;
   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 ctxt [] [] 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 (Syntax.string_of_arity ctxt 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.minimize_sort thy (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 (Name.aT, [class])) ty;
   345       in (param, ty') end) params;
   346 
   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 
   364 
   365 (** axclasses with implicit parameter handling **)
   366 
   367 fun define_class_params (name, raw_superclasses) raw_consts raw_dep_axioms other_consts thy =
   368   let
   369     val superclasses = map (Sign.certify_class thy) raw_superclasses;
   370     val consts = (map o apfst o apsnd) (Sign.certify_typ thy) raw_consts;
   371     val prefix = Logic.const_of_class name;
   372     fun mk_const_name c = NameSpace.map_base (NameSpace.append prefix)
   373       (Sign.full_name thy c);
   374     fun add_const ((c, ty), syn) =
   375       Sign.add_consts_authentic [] [(c, ty, syn)]
   376       #> pair (mk_const_name c, ty);
   377     fun mk_axioms cs thy =
   378       raw_dep_axioms thy cs
   379       |> (map o apsnd o map) (Sign.cert_prop thy)
   380       |> rpair thy;
   381     fun add_constraint class (c, ty) =
   382       Sign.add_const_constraint (c, SOME
   383         (Term.map_type_tfree (fn (v, _) => TFree (v, [class])) ty));
   384   in
   385     thy
   386     |> Sign.add_path prefix
   387     |> fold_map add_const consts
   388     ||> Sign.restore_naming thy
   389     |-> (fn cs => mk_axioms cs
   390     #-> (fn axioms_prop => define_class (name, superclasses)
   391            (map fst cs @ other_consts) axioms_prop
   392     #-> (fn class => `(fn thy => get_info thy class)
   393     #-> (fn {axioms, ...} => fold (add_constraint class) cs
   394     #> pair (class, (cs, axioms))))))
   395   end;
   396 
   397 
   398 
   399 (** axiomatizations **)
   400 
   401 local
   402 
   403 fun axiomatize prep mk name add raw_args thy =
   404   let
   405     val args = prep thy raw_args;
   406     val specs = mk args;
   407     val names = name args;
   408   in thy |> PureThy.add_axioms_i (map (rpair []) (names ~~ specs)) |-> fold add end;
   409 
   410 fun ax_classrel prep =
   411   axiomatize (map o prep) (map Logic.mk_classrel)
   412     (map (prefix classrel_prefix o Logic.name_classrel)) add_classrel;
   413 
   414 fun ax_arity prep =
   415   axiomatize prep Logic.mk_arities
   416     (map (prefix arity_prefix) o Logic.name_arities) add_arity;
   417 
   418 fun class_const c =
   419   (Logic.const_of_class c, Term.itselfT (Term.aT []) --> propT);
   420 
   421 fun ax_class prep_class prep_classrel (bclass, raw_super) thy =
   422   let
   423     val class = Sign.full_name thy bclass;
   424     val super = map (prep_class thy) raw_super |> Sign.minimize_sort thy;
   425   in
   426     thy
   427     |> Sign.primitive_class (bclass, super)
   428     |> ax_classrel prep_classrel (map (fn c => (class, c)) super)
   429     |> Theory.add_deps "" (class_const class) (map class_const super)
   430   end;
   431 
   432 in
   433 
   434 val axiomatize_class = ax_class Sign.certify_class cert_classrel;
   435 val axiomatize_class_cmd = ax_class Sign.read_class read_classrel;
   436 val axiomatize_classrel = ax_classrel cert_classrel;
   437 val axiomatize_classrel_cmd = ax_classrel read_classrel;
   438 val axiomatize_arity = ax_arity Sign.cert_arity;
   439 val axiomatize_arity_cmd = ax_arity Sign.read_arity;
   440 
   441 end;
   442 
   443 
   444 
   445 (** explicit derivations -- cached **)
   446 
   447 datatype cache = Types of (class * thm) list Typtab.table;
   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 val cache = Types Typtab.empty;
   493 
   494 end;