src/Pure/axclass.ML
author wenzelm
Sat Apr 29 23:16:45 2006 +0200 (2006-04-29)
changeset 19503 10921826b160
parent 19482 9f11af8f7ef9
child 19511 b4bd790f9373
permissions -rw-r--r--
instances data: mutable cache;
added of_sort: interface for derived instances;
     1 (*  Title:      Pure/axclass.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 Axiomatic type classes: managing predicates and parameter collections.
     6 *)
     7 
     8 signature AX_CLASS =
     9 sig
    10   val print_axclasses: theory -> unit
    11   val get_info: theory -> class -> {def: thm, intro: thm, axioms: thm list}
    12   val class_intros: theory -> thm list
    13   val params_of: theory -> class -> string list
    14   val all_params_of: theory -> sort -> string list
    15   val cert_classrel: theory -> class * class -> class * class
    16   val read_classrel: theory -> xstring * xstring -> class * class
    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 of_sort: theory -> typ * sort -> thm list
    22   val add_axclass: bstring * xstring list -> string list ->
    23     ((bstring * Attrib.src list) * string list) list -> theory -> class * theory
    24   val add_axclass_i: bstring * class list -> string list ->
    25     ((bstring * attribute list) * term list) list -> theory -> class * theory
    26 end;
    27 
    28 structure AxClass: AX_CLASS =
    29 struct
    30 
    31 (** theory data **)
    32 
    33 (* class parameters (canonical order) *)
    34 
    35 type param = string * class;
    36 
    37 fun add_param pp ((x, c): param) params =
    38   (case AList.lookup (op =) params x of
    39     NONE => (x, c) :: params
    40   | SOME c' => error ("Duplicate class parameter " ^ quote x ^
    41       " for " ^ Pretty.string_of_sort pp [c] ^
    42       (if c = c' then "" else " and " ^ Pretty.string_of_sort pp [c'])));
    43 
    44 fun merge_params _ ([], qs) = qs
    45   | merge_params pp (ps, qs) =
    46       fold_rev (fn q => if member (op =) ps q then I else add_param pp q) qs ps;
    47 
    48 
    49 (* axclass *)
    50 
    51 val introN = "intro";
    52 val axiomsN = "axioms";
    53 
    54 datatype axclass = AxClass of
    55  {def: thm,
    56   intro: thm,
    57   axioms: thm list};
    58 
    59 type axclasses = axclass Symtab.table * param list;
    60 
    61 fun make_axclass (def, intro, axioms) =
    62   AxClass {def = def, intro = intro, axioms = axioms};
    63 
    64 fun merge_axclasses pp ((tab1, params1), (tab2, params2)) : axclasses =
    65   (Symtab.merge (K true) (tab1, tab2), merge_params pp (params1, params2));
    66 
    67 
    68 (* instances *)
    69 
    70 datatype instances = Instances of
    71  {classes: unit Graph.T,                 (*raw relation -- no closure!*)
    72   classrel: ((class * class) * thm) list,
    73   arities: ((class * sort list) * thm) list Symtab.table,
    74   types: (class * thm) list Typtab.table};
    75 
    76 fun make_instances (classes, classrel, arities, types) =
    77   Instances {classes = classes, classrel = classrel, arities = arities, types = types};
    78 
    79 fun map_instances f (Instances {classes, classrel, arities, types}) =
    80   make_instances (f (classes, classrel, arities, types));
    81 
    82 fun merge_instances
    83    (Instances {classes = classes1, classrel = classrel1, arities = arities1, types = types1},
    84     Instances {classes = classes2, classrel = classrel2, arities = arities2, types = types2}) =
    85   make_instances
    86    (Graph.merge (K true) (classes1, classes2),
    87     merge (eq_fst op =) (classrel1, classrel2),
    88     Symtab.join (K (merge (eq_fst op =))) (arities1, arities2),
    89     Typtab.join (K (merge (eq_fst op =))) (types1, types2));
    90 
    91 
    92 (* data *)
    93 
    94 structure AxClassData = TheoryDataFun
    95 (struct
    96   val name = "Pure/axclass";
    97   type T = axclasses * instances ref;
    98   val empty : T =
    99     ((Symtab.empty, []), ref (make_instances (Graph.empty, [], Symtab.empty, Typtab.empty)));
   100   fun copy (axclasses, ref instances) : T = (axclasses, ref instances);
   101   val extend = copy;
   102   fun merge pp ((axclasses1, ref instances1), (axclasses2, ref instances2)) =
   103     (merge_axclasses pp (axclasses1, axclasses2), ref (merge_instances (instances1, instances2)));
   104   fun print _ _ = ();
   105 end);
   106 
   107 val _ = Context.add_setup AxClassData.init;
   108 
   109 
   110 (* classes *)
   111 
   112 val lookup_info = Symtab.lookup o #1 o #1 o AxClassData.get;
   113 
   114 fun get_info thy c =
   115   (case lookup_info thy c of
   116     SOME (AxClass info) => info
   117   | NONE => error ("Unknown axclass " ^ quote c));
   118 
   119 fun class_intros thy =
   120   let
   121     fun add_intro c =
   122       (case lookup_info thy c of SOME (AxClass {intro, ...}) => cons intro | _ => I);
   123     val classes = Sign.classes thy;
   124   in map (Thm.class_triv thy) classes @ fold add_intro classes [] end;
   125 
   126 
   127 (* parameters *)
   128 
   129 fun get_params thy pred =
   130   let val params = #2 (#1 (AxClassData.get 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 
   137 (* instances *)
   138 
   139 val get_instances = AxClassData.get #> (fn (_, ref (Instances insts)) => insts);
   140 
   141 fun store_instance f thy (x, th) =
   142   let
   143     val th' = Drule.standard' th;
   144     val _ = change (#2 (AxClassData.get thy)) (map_instances (f (x, th')));
   145   in th' end;
   146 
   147 val store_classrel = store_instance (fn ((c1, c2), th) => fn (classes, classrel, arities, types) =>
   148   (classes
   149     |> Graph.default_node (c1, ())
   150     |> Graph.default_node (c2, ())
   151     |> Graph.add_edge (c1, c2),
   152     insert (eq_fst op =) ((c1, c2), th) classrel, arities, types));
   153 
   154 val store_arity = store_instance (fn ((t, Ss, c), th) => fn (classes, classrel, arities, types) =>
   155   (classes, classrel, arities |> Symtab.insert_list (eq_fst op =) (t, ((c, Ss), th)), types));
   156 
   157 val store_type = store_instance (fn ((T, c), th) => fn (classes, classrel, arities, types) =>
   158   (classes, classrel, arities, types |> Typtab.insert_list (eq_fst op =) (T, (c, th))));
   159 
   160 
   161 (* print_axclasses *)
   162 
   163 fun print_axclasses thy =
   164   let
   165     val axclasses = #1 (#1 (AxClassData.get thy));
   166     val ctxt = ProofContext.init thy;
   167 
   168     fun pretty_axclass (class, AxClass {def, intro, axioms}) =
   169       Pretty.block (Pretty.fbreaks
   170        [Pretty.block
   171           [Pretty.str "axclass ", ProofContext.pretty_sort ctxt [class], Pretty.str ":"],
   172         Pretty.strs ("parameters:" :: params_of thy class),
   173         ProofContext.pretty_fact ctxt ("def", [def]),
   174         ProofContext.pretty_fact ctxt (introN, [intro]),
   175         ProofContext.pretty_fact ctxt (axiomsN, axioms)]);
   176   in Pretty.writeln (Pretty.chunks (map pretty_axclass (Symtab.dest axclasses))) end;
   177 
   178 
   179 
   180 (** instance proofs **)
   181 
   182 (* class relations *)
   183 
   184 fun cert_classrel thy raw_rel =
   185   let
   186     val (c1, c2) = pairself (Sign.certify_class thy) raw_rel;
   187     val _ = Type.add_classrel (Sign.pp thy) [(c1, c2)] (Sign.tsig_of thy);
   188     val _ =
   189       (case subtract (op =) (all_params_of thy [c1]) (all_params_of thy [c2]) of
   190         [] => ()
   191       | xs => raise TYPE ("Class " ^ Sign.string_of_sort thy [c1] ^ " lacks parameter(s) " ^
   192           commas_quote xs ^ " of " ^ Sign.string_of_sort thy [c2], [], []));
   193   in (c1, c2) end;
   194 
   195 fun read_classrel thy raw_rel =
   196   cert_classrel thy (pairself (Sign.read_class thy) raw_rel)
   197     handle TYPE (msg, _, _) => error msg;
   198 
   199 
   200 (* primitive rules *)
   201 
   202 fun add_classrel th thy =
   203   let
   204     fun err () = raise THM ("add_classrel: malformed class relation", 0, [th]);
   205     val prop = Drule.plain_prop_of (Thm.transfer thy th);
   206     val rel = Logic.dest_classrel prop handle TERM _ => err ();
   207     val (c1, c2) = cert_classrel thy rel handle TYPE _ => err ();
   208     val thy' = thy |> Theory.add_classrel_i [(c1, c2)];
   209     val _ = store_classrel thy' ((c1, c2), Drule.unconstrainTs th);
   210   in thy' end;
   211 
   212 fun add_arity th thy =
   213   let
   214     val prop = Drule.plain_prop_of (Thm.transfer thy th);
   215     val (t, Ss, c) = Logic.dest_arity prop handle TERM _ =>
   216       raise THM ("add_arity: malformed type arity", 0, [th]);
   217     val thy' = thy |> Theory.add_arities_i [(t, Ss, [c])];
   218     val _ = store_arity thy' ((t, Ss, c), Drule.unconstrainTs th);
   219   in thy' end;
   220 
   221 
   222 (* tactical proofs *)
   223 
   224 fun prove_classrel raw_rel tac thy =
   225   let
   226     val (c1, c2) = cert_classrel thy raw_rel;
   227     val th = Goal.prove thy [] [] (Logic.mk_classrel (c1, c2)) (fn _ => tac) handle ERROR msg =>
   228       cat_error msg ("The error(s) above occurred while trying to prove class relation " ^
   229         quote (Sign.string_of_classrel thy [c1, c2]));
   230   in add_classrel th thy end;
   231 
   232 fun prove_arity raw_arity tac thy =
   233   let
   234     val arity = Sign.cert_arity thy raw_arity;
   235     val props = Logic.mk_arities arity;
   236     val ths = Goal.prove_multi thy [] [] props
   237       (fn _ => Tactic.precise_conjunction_tac (length props) 1 THEN tac) handle ERROR msg =>
   238         cat_error msg ("The error(s) above occurred while trying to prove type arity " ^
   239           quote (Sign.string_of_arity thy arity));
   240   in fold add_arity ths thy end;
   241 
   242 
   243 (* derived instances -- cached *)
   244 
   245 fun derive_classrel thy (c1, c2) =
   246   let
   247     val {classes, classrel, ...} = get_instances thy;
   248     val lookup = AList.lookup (op =) classrel;
   249     fun derive [c, c'] = the (lookup (c, c'))
   250       | derive (c :: c' :: cs) = derive [c, c'] RS derive (c' :: cs);
   251   in
   252     (case lookup (c1, c2) of
   253       SOME rule => rule
   254     | NONE =>
   255         (case Graph.find_paths classes (c1, c2) of
   256           [] => error ("Cannot derive class relation " ^ Sign.string_of_classrel thy [c1, c2])
   257         | path :: _ => store_classrel thy ((c1, c2), derive path)))
   258   end;
   259 
   260 fun weaken_subclass thy (c1, th) c2 =
   261   if c1 = c2 then th
   262   else th RS derive_classrel thy (c1, c2);
   263 
   264 fun weaken_subsort thy S1 S2 = S2 |> map (fn c2 =>
   265   (case S1 |> find_first (fn (c1, _) => Sign.subsort thy ([c1], [c2])) of
   266     SOME c1 => weaken_subclass thy c1 c2
   267   | NONE => error ("Cannot derive subsort relation " ^
   268       Sign.string_of_sort thy (map #1 S1) ^ " < " ^ Sign.string_of_sort thy S2)));
   269 
   270 fun apply_arity thy t dom c =
   271   let
   272     val {arities, ...} = get_instances thy;
   273     val subsort = Sign.subsort thy;
   274     val Ss = map (map #1) dom;
   275   in
   276     (case Symtab.lookup_list arities t |> find_first (fn ((c', Ss'), _) =>
   277         subsort ([c'], [c]) andalso ListPair.all subsort (Ss, Ss')) of
   278       SOME ((c', Ss'), rule) =>
   279         weaken_subclass thy (c', rule OF flat (map2 (weaken_subsort thy) dom Ss')) c
   280     | NONE => error ("Cannot derive type arity " ^ Sign.string_of_arity thy (t, Ss, [c])))
   281   end;
   282 
   283 fun derive_type thy hyps =
   284   let
   285     fun derive (Type (a, Ts)) S =
   286           let val Ss = Sign.arity_sorts thy a S
   287           in map (apply_arity thy a (map2 (fn T => fn S => S ~~ derive T S) Ts Ss)) S end
   288       | derive (TFree (a, [])) S =
   289           weaken_subsort thy (the_default [] (AList.lookup (op =) hyps a)) S
   290       | derive T _ = error ("Illegal occurrence of type variable " ^
   291           setmp show_sorts true (Sign.string_of_typ thy) T);
   292   in derive end;
   293 
   294 fun of_sort thy (typ, sort) =
   295   let
   296     fun lookup () = AList.lookup (op =) (Typtab.lookup_list (#types (get_instances thy)) typ);
   297     val sort' = filter (is_none o lookup ()) sort;
   298     val _ = conditional (not (null sort')) (fn () =>
   299       let
   300         val vars = Term.fold_atyps (insert (op =)) typ [];
   301         val renaming =
   302           map2 (fn T => fn a => (T, (a, case T of TFree (_, S) => S | TVar (_, S) => S)))
   303             vars (Term.invent_names [] "'a" (length vars));
   304         val typ' = typ |> Term.map_atyps
   305           (fn T => TFree (#1 (the (AList.lookup (op =) renaming T)), []));
   306 
   307         val hyps = renaming |> map (fn (_, (a, S)) => (a, S ~~ (S |> map (fn c =>
   308           Thm.assume (Thm.cterm_of thy (Logic.mk_inclass (TFree (a, []), c)))))));
   309         val inst = renaming |> map (fn (T, (a, S)) =>
   310           pairself (Thm.ctyp_of thy) (TVar ((a, 0), S), T));
   311 
   312         val ths =
   313           derive_type thy hyps typ' sort'
   314           |> map (Thm.instantiate (inst, []));
   315         val _ = map (store_type thy) (map (pair typ) sort' ~~ ths);
   316       in () end);
   317   in map (the o lookup ()) sort end;
   318 
   319 
   320 
   321 (** axclass definitions **)
   322 
   323 (* add_axclass(_i) *)
   324 
   325 fun gen_axclass prep_class prep_att prep_propp
   326     (bclass, raw_super) params raw_specs thy =
   327   let
   328     val ctxt = ProofContext.init thy;
   329     val pp = ProofContext.pp ctxt;
   330 
   331 
   332     (* prepare specification *)
   333 
   334     val bconst = Logic.const_of_class bclass;
   335     val class = Sign.full_name thy bclass;
   336     val super = map (prep_class thy) raw_super |> Sign.certify_sort thy;
   337 
   338     fun prep_axiom t =
   339       (case Term.add_tfrees t [] of
   340         [(a, S)] =>
   341           if Sign.subsort thy (super, S) then t
   342           else error ("Sort constraint of type variable " ^
   343             setmp show_sorts true (Pretty.string_of_typ pp) (TFree (a, S)) ^
   344             " needs to be weaker than " ^ Pretty.string_of_sort pp super)
   345       | [] => t
   346       | _ => error ("Multiple type variables in class axiom:\n" ^ Pretty.string_of_term pp t))
   347       |> map_term_types (Term.map_atyps (fn TFree _ => Term.aT [] | U => U))
   348       |> Logic.close_form;
   349 
   350     val axiomss = prep_propp (ctxt, map (map (rpair ([], [])) o snd) raw_specs)
   351       |> snd |> map (map (prep_axiom o fst));
   352     val name_atts = Attrib.map_specs (prep_att thy) raw_specs |> map fst;
   353 
   354 
   355     (* definition *)
   356 
   357     val conjs = map (curry Logic.mk_inclass (Term.aT [])) super @ flat axiomss;
   358     val class_eq =
   359       Logic.mk_equals (Logic.mk_inclass (Term.aT [], class), Logic.mk_conjunction_list conjs);
   360 
   361     val ([def], def_thy) =
   362       thy
   363       |> Theory.add_classes_i [(bclass, super)]
   364       |> PureThy.add_defs_i false [((Thm.def_name bconst, class_eq), [])];
   365     val (raw_intro, (raw_classrel, raw_axioms)) =
   366       (Conjunction.split_defined (length conjs) def) ||> chop (length super);
   367 
   368 
   369     (* facts *)
   370 
   371     val class_triv = Thm.class_triv def_thy class;
   372     val ([(_, [intro]), (_, axioms)], facts_thy) =
   373       def_thy
   374       |> PureThy.note_thmss_qualified "" bconst
   375         [((introN, []), [([Drule.standard raw_intro], [])]),
   376          ((axiomsN, []), [(map (fn th => Drule.standard (class_triv RS th)) raw_axioms, [])])];
   377     val _ = map (store_classrel facts_thy)
   378       (map (pair class) super ~~ map Drule.standard raw_classrel);
   379 
   380 
   381     (* result *)
   382 
   383     val result_thy =
   384       facts_thy
   385       |> Sign.add_path bconst
   386       |> PureThy.note_thmss_i "" (name_atts ~~ map Thm.simple_fact (unflat axiomss axioms)) |> snd
   387       |> Sign.restore_naming facts_thy
   388       |> AxClassData.map (apfst (fn (axclasses, parameters) =>
   389         (Symtab.update (class, make_axclass (def, intro, axioms)) axclasses,
   390           fold (fn x => add_param pp (x, class)) params parameters)));
   391 
   392   in (class, result_thy) end;
   393 
   394 val add_axclass = gen_axclass Sign.read_class Attrib.attribute ProofContext.read_propp;
   395 val add_axclass_i = gen_axclass Sign.certify_class (K I) ProofContext.cert_propp;
   396 
   397 end;