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