src/HOL/Tools/typedef_package.ML
author wenzelm
Thu Sep 15 17:16:56 2005 +0200 (2005-09-15)
changeset 17412 e26cb20ef0cc
parent 17339 ab97ccef124a
child 17922 0cba8edb269e
permissions -rw-r--r--
TableFun/Symtab: curried lookup and update;
     1 (*  Title:      HOL/Tools/typedef_package.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel and Stefan Berghofer, TU Muenchen
     4 
     5 Gordon/HOL-style type definitions.
     6 *)
     7 
     8 signature TYPEDEF_PACKAGE =
     9 sig
    10   val quiet_mode: bool ref
    11   val add_typedecls: (bstring * string list * mixfix) list -> theory -> theory
    12   val add_typedef_x: string -> bstring * string list * mixfix ->
    13     string -> string list -> thm list -> tactic option -> theory -> theory
    14   val add_typedef: bool -> string option -> bstring * string list * mixfix ->
    15     string -> (bstring * bstring) option -> tactic -> theory -> theory *
    16     {type_definition: thm, set_def: thm option, Rep: thm, Rep_inverse: thm,
    17       Abs_inverse: thm, Rep_inject: thm, Abs_inject: thm, Rep_cases: thm, Abs_cases: thm,
    18       Rep_induct: thm, Abs_induct: thm}
    19   val add_typedef_i: bool -> string option -> bstring * string list * mixfix ->
    20     term -> (bstring * bstring) option -> tactic -> theory -> theory *
    21     {type_definition: thm, set_def: thm option, Rep: thm, Rep_inverse: thm,
    22       Abs_inverse: thm, Rep_inject: thm, Abs_inject: thm, Rep_cases: thm, Abs_cases: thm,
    23       Rep_induct: thm, Abs_induct: thm}
    24   val typedef: (bool * string) * (bstring * string list * mixfix) * string
    25     * (string * string) option -> theory -> Proof.state
    26   val typedef_i: (bool * string) * (bstring * string list * mixfix) * term
    27     * (string * string) option -> theory -> Proof.state
    28   val setup: (theory -> theory) list
    29 end;
    30 
    31 structure TypedefPackage: TYPEDEF_PACKAGE =
    32 struct
    33 
    34 
    35 (** theory context references **)
    36 
    37 val type_definitionN = "Typedef.type_definition";
    38 
    39 val Rep = thm "type_definition.Rep";
    40 val Rep_inverse = thm "type_definition.Rep_inverse";
    41 val Abs_inverse = thm "type_definition.Abs_inverse";
    42 val Rep_inject = thm "type_definition.Rep_inject";
    43 val Abs_inject = thm "type_definition.Abs_inject";
    44 val Rep_cases = thm "type_definition.Rep_cases";
    45 val Abs_cases = thm "type_definition.Abs_cases";
    46 val Rep_induct = thm "type_definition.Rep_induct";
    47 val Abs_induct = thm "type_definition.Abs_induct";
    48 
    49 
    50 
    51 (** theory data **)
    52 
    53 structure TypedefData = TheoryDataFun
    54 (struct
    55   val name = "HOL/typedef";
    56   type T = (typ * typ * string * string) Symtab.table;
    57   val empty = Symtab.empty;
    58   val copy = I;
    59   val extend = I;
    60   fun merge _ (tabs: T * T) = Symtab.merge (op =) tabs;
    61   fun print _ _ = ();
    62 end);
    63 
    64 fun put_typedef newT oldT Abs_name Rep_name =
    65   TypedefData.map (Symtab.update_new (fst (dest_Type newT), (newT, oldT, Abs_name, Rep_name)));
    66 
    67 
    68 
    69 (** type declarations **)
    70 
    71 fun add_typedecls decls thy =
    72   let
    73     fun arity_of (raw_name, args, mx) =
    74       (Sign.full_name thy (Syntax.type_name raw_name mx),
    75         replicate (length args) HOLogic.typeS, HOLogic.typeS);
    76   in
    77     if can (Theory.assert_super HOL.thy) thy then
    78       thy |> Theory.add_typedecls decls
    79       |> Theory.add_arities_i (map arity_of decls)
    80     else thy |> Theory.add_typedecls decls
    81   end;
    82 
    83 
    84 
    85 (** type definitions **)
    86 
    87 (* messages *)
    88 
    89 val quiet_mode = ref false;
    90 fun message s = if ! quiet_mode then () else writeln s;
    91 
    92 
    93 (* prove_nonempty -- tactical version *)        (*exception ERROR*)
    94 
    95 fun prove_nonempty thy cset goal (witn1_tac, witn_names, witn_thms, witn2_tac) =
    96   let
    97     val is_def = Logic.is_equals o #prop o Thm.rep_thm;
    98     val thms = PureThy.get_thmss thy (map Name witn_names) @ witn_thms;
    99     val tac =
   100       witn1_tac THEN
   101       TRY (rewrite_goals_tac (List.filter is_def thms)) THEN
   102       TRY (REPEAT_FIRST (resolve_tac (filter_out is_def thms))) THEN
   103       if_none witn2_tac (TRY (ALLGOALS (CLASET' blast_tac)));
   104   in
   105     message ("Proving non-emptiness of set " ^ quote (string_of_cterm cset) ^ " ...");
   106     Tactic.prove thy [] [] goal (K tac)
   107   end
   108   handle ERROR => error ("Failed to prove non-emptiness of " ^ quote (string_of_cterm cset));
   109 
   110 
   111 (* prepare_typedef *)
   112 
   113 fun read_term thy used s =
   114   #1 (Thm.read_def_cterm (thy, K NONE, K NONE) used true (s, HOLogic.typeT));
   115 
   116 fun cert_term thy _ t = Thm.cterm_of thy t handle TERM (msg, _) => error msg;
   117 
   118 fun err_in_typedef name =
   119   error ("The error(s) above occurred in typedef " ^ quote name);
   120 
   121 fun prepare_typedef prep_term def name (t, vs, mx) raw_set opt_morphs thy =
   122   let
   123     val _ = Theory.requires thy "Typedef" "typedefs";
   124     val full = Sign.full_name thy;
   125 
   126     (*rhs*)
   127     val full_name = full name;
   128     val cset = prep_term thy vs raw_set;
   129     val {T = setT, t = set, ...} = Thm.rep_cterm cset;
   130     val rhs_tfrees = Term.add_tfrees set [];
   131     val rhs_tfreesT = Term.add_tfreesT setT [];
   132     val oldT = HOLogic.dest_setT setT handle TYPE _ =>
   133       error ("Not a set type: " ^ quote (Sign.string_of_typ thy setT));
   134     fun mk_nonempty A =
   135       HOLogic.mk_Trueprop (HOLogic.mk_exists ("x", oldT, HOLogic.mk_mem (Free ("x", oldT), A)));
   136     val goal = mk_nonempty set;
   137     val goal_pat = mk_nonempty (Var (if_none (Syntax.read_variable name) (name, 0), setT));
   138 
   139     (*lhs*)
   140     val defS = Sign.defaultS thy;
   141     val lhs_tfrees = map (fn v => (v, if_none (AList.lookup (op =) rhs_tfrees v) defS)) vs;
   142     val args_setT = lhs_tfrees
   143       |> filter (member (op =) rhs_tfrees andf (not o member (op =) rhs_tfreesT))
   144       |> map TFree;
   145 
   146     val tname = Syntax.type_name t mx;
   147     val full_tname = full tname;
   148     val newT = Type (full_tname, map TFree lhs_tfrees);
   149 
   150     val (Rep_name, Abs_name) = if_none opt_morphs ("Rep_" ^ name, "Abs_" ^ name);
   151     val setT' = map itselfT args_setT ---> setT;
   152     val setC = Term.list_comb (Const (full_name, setT'), map Logic.mk_type args_setT);
   153     val RepC = Const (full Rep_name, newT --> oldT);
   154     val AbsC = Const (full Abs_name, oldT --> newT);
   155     val x_new = Free ("x", newT);
   156     val y_old = Free ("y", oldT);
   157 
   158     val set' = if def then setC else set;
   159 
   160     val typedef_name = "type_definition_" ^ name;
   161     val typedefC =
   162       Const (type_definitionN, (newT --> oldT) --> (oldT --> newT) --> setT --> HOLogic.boolT);
   163     val typedef_prop =
   164       Logic.mk_implies (goal, HOLogic.mk_Trueprop (typedefC $ RepC $ AbsC $ set'));
   165 
   166     fun typedef_result (theory, nonempty) =
   167       theory
   168       |> put_typedef newT oldT (full Abs_name) (full Rep_name)
   169       |> add_typedecls [(t, vs, mx)]
   170       |> Theory.add_consts_i
   171        ((if def then [(name, setT', NoSyn)] else []) @
   172         [(Rep_name, newT --> oldT, NoSyn),
   173          (Abs_name, oldT --> newT, NoSyn)])
   174       |> (if def then (apsnd (SOME o hd) oo (PureThy.add_defs_i false o map Thm.no_attributes))
   175            [Logic.mk_defpair (setC, set)]
   176           else rpair NONE)
   177       |>>> PureThy.add_axioms_i [((typedef_name, typedef_prop),
   178           [apsnd (fn cond_axm => Drule.standard (nonempty RS cond_axm))])]
   179       |>> Theory.add_finals_i false [RepC, AbsC]
   180       |> (fn (theory', (set_def, [type_definition])) =>
   181         let
   182           fun make th = Drule.standard (th OF [type_definition]);
   183           val (theory'', [Rep, Rep_inverse, Abs_inverse, Rep_inject, Abs_inject,
   184               Rep_cases, Abs_cases, Rep_induct, Abs_induct]) =
   185             theory'
   186             |> Theory.add_path name
   187             |> PureThy.add_thms
   188               ([((Rep_name, make Rep), []),
   189                 ((Rep_name ^ "_inverse", make Rep_inverse), []),
   190                 ((Abs_name ^ "_inverse", make Abs_inverse), []),
   191                 ((Rep_name ^ "_inject", make Rep_inject), []),
   192                 ((Abs_name ^ "_inject", make Abs_inject), []),
   193                 ((Rep_name ^ "_cases", make Rep_cases),
   194                   [RuleCases.case_names [Rep_name], InductAttrib.cases_set_global full_name]),
   195                 ((Abs_name ^ "_cases", make Abs_cases),
   196                   [RuleCases.case_names [Abs_name], InductAttrib.cases_type_global full_tname]),
   197                 ((Rep_name ^ "_induct", make Rep_induct),
   198                   [RuleCases.case_names [Rep_name], InductAttrib.induct_set_global full_name]),
   199                 ((Abs_name ^ "_induct", make Abs_induct),
   200                   [RuleCases.case_names [Abs_name], InductAttrib.induct_type_global full_tname])])
   201             |>> Theory.parent_path;
   202           val result = {type_definition = type_definition, set_def = set_def,
   203             Rep = Rep, Rep_inverse = Rep_inverse, Abs_inverse = Abs_inverse,
   204             Rep_inject = Rep_inject, Abs_inject = Abs_inject, Rep_cases = Rep_cases,
   205             Abs_cases = Abs_cases, Rep_induct = Rep_induct, Abs_induct = Abs_induct};
   206         in ((theory'', type_definition), result) end);
   207 
   208 
   209     (* errors *)
   210 
   211     fun show_names pairs = commas_quote (map fst pairs);
   212 
   213     val illegal_vars =
   214       if null (term_vars set) andalso null (term_tvars set) then []
   215       else ["Illegal schematic variable(s) on rhs"];
   216 
   217     val dup_lhs_tfrees =
   218       (case duplicates lhs_tfrees of [] => []
   219       | dups => ["Duplicate type variables on lhs: " ^ show_names dups]);
   220 
   221     val extra_rhs_tfrees =
   222       (case fold (remove (op =)) lhs_tfrees rhs_tfrees of [] => []
   223       | extras => ["Extra type variables on rhs: " ^ show_names extras]);
   224 
   225     val illegal_frees =
   226       (case term_frees set of [] => []
   227       | xs => ["Illegal variables on rhs: " ^ show_names (map dest_Free xs)]);
   228 
   229     val errs = illegal_vars @ dup_lhs_tfrees @ extra_rhs_tfrees @ illegal_frees;
   230     val _ = if null errs then () else error (cat_lines errs);
   231 
   232     (*test theory errors now!*)
   233     val test_thy = Theory.copy thy;
   234     val _ = (test_thy,
   235       setmp quick_and_dirty true (SkipProof.make_thm test_thy) goal) |> typedef_result;
   236 
   237   in (cset, goal, goal_pat, typedef_result) end
   238   handle ERROR => err_in_typedef name;
   239 
   240 
   241 (* add_typedef interfaces *)
   242 
   243 local
   244 
   245 fun gen_typedef prep_term def name typ set opt_morphs tac1 names thms tac2 thy =
   246   let
   247     val (cset, goal, _, typedef_result) =
   248       prepare_typedef prep_term def name typ set opt_morphs thy;
   249     val non_empty = prove_nonempty thy cset goal (tac1, names, thms, tac2);
   250     val ((thy', _), result) = (thy, non_empty) |> typedef_result;
   251   in (thy', result) end;
   252 
   253 fun sane_typedef prep_term def opt_name typ set opt_morphs tac =
   254   gen_typedef prep_term def
   255     (if_none opt_name (#1 typ)) typ set opt_morphs all_tac [] [] (SOME tac);
   256 
   257 in
   258 
   259 fun add_typedef_x name typ set names thms tac =
   260   #1 o gen_typedef read_term true name typ set NONE (Tactic.rtac exI 1) names thms tac;
   261 
   262 val add_typedef = sane_typedef read_term;
   263 val add_typedef_i = sane_typedef cert_term;
   264 
   265 end;
   266 
   267 
   268 (* Isar typedef interface *)
   269 
   270 local
   271 
   272 fun gen_typedef prep_term ((def, name), typ, set, opt_morphs) thy =
   273   let
   274     val (_, goal, goal_pat, att_result) =
   275       prepare_typedef prep_term def name typ set opt_morphs thy;
   276     val att = #1 o att_result;
   277   in IsarThy.theorem_i Drule.internalK ("", [att]) (goal, ([goal_pat], [])) thy end;
   278 
   279 in
   280 
   281 val typedef = gen_typedef read_term;
   282 val typedef_i = gen_typedef cert_term;
   283 
   284 end;
   285 
   286 
   287 
   288 (** trivial code generator **)
   289 
   290 fun typedef_codegen thy defs gr dep module brack t =
   291   let
   292     fun get_name (Type (tname, _)) = tname
   293       | get_name _ = "";
   294     fun mk_fun s T ts =
   295       let
   296         val (gr', _) = Codegen.invoke_tycodegen thy defs dep module false (gr, T);
   297         val (gr'', ps) =
   298           foldl_map (Codegen.invoke_codegen thy defs dep module true) (gr', ts);
   299         val id = Codegen.mk_qual_id module (Codegen.get_const_id s gr'')
   300       in SOME (gr'', Codegen.mk_app brack (Pretty.str id) ps) end;
   301     fun lookup f T =
   302       (case Symtab.lookup (TypedefData.get thy) (get_name T) of
   303         NONE => ""
   304       | SOME s => f s);
   305   in
   306     (case strip_comb t of
   307        (Const (s, Type ("fun", [T, U])), ts) =>
   308          if lookup #4 T = s andalso
   309            is_none (Codegen.get_assoc_type thy (get_name T))
   310          then mk_fun s T ts
   311          else if lookup #3 U = s andalso
   312            is_none (Codegen.get_assoc_type thy (get_name U))
   313          then mk_fun s U ts
   314          else NONE
   315      | _ => NONE)
   316   end;
   317 
   318 fun mk_tyexpr [] s = Pretty.str s
   319   | mk_tyexpr [p] s = Pretty.block [p, Pretty.str (" " ^ s)]
   320   | mk_tyexpr ps s = Pretty.list "(" (") " ^ s) ps;
   321 
   322 fun typedef_tycodegen thy defs gr dep module brack (Type (s, Ts)) =
   323       (case Symtab.lookup (TypedefData.get thy) s of
   324          NONE => NONE
   325        | SOME (newT as Type (tname, Us), oldT, Abs_name, Rep_name) =>
   326            if is_some (Codegen.get_assoc_type thy tname) then NONE else
   327            let
   328              val module' = Codegen.if_library
   329                (Codegen.thyname_of_type tname thy) module;
   330              val node_id = tname ^ " (type)";
   331              val (gr', (((qs, (_, Abs_id)), (_, Rep_id)), ty_id)) = foldl_map
   332                  (Codegen.invoke_tycodegen thy defs dep module (length Ts = 1))
   333                    (gr, Ts) |>>>
   334                Codegen.mk_const_id module' Abs_name |>>>
   335                Codegen.mk_const_id module' Rep_name |>>>
   336                Codegen.mk_type_id module' s;
   337              val tyexpr = mk_tyexpr qs (Codegen.mk_qual_id module ty_id)
   338            in SOME (case try (Codegen.get_node gr') node_id of
   339                NONE =>
   340                let
   341                  val (gr'', p :: ps) = foldl_map
   342                    (Codegen.invoke_tycodegen thy defs node_id module' false)
   343                    (Codegen.add_edge (node_id, dep)
   344                       (Codegen.new_node (node_id, (NONE, "", "")) gr'), oldT :: Us);
   345                  val s =
   346                    Pretty.string_of (Pretty.block [Pretty.str "datatype ",
   347                      mk_tyexpr ps (snd ty_id),
   348                      Pretty.str " =", Pretty.brk 1, Pretty.str (Abs_id ^ " of"),
   349                      Pretty.brk 1, p, Pretty.str ";"]) ^ "\n\n" ^
   350                    Pretty.string_of (Pretty.block [Pretty.str ("fun " ^ Rep_id),
   351                      Pretty.brk 1, Pretty.str ("(" ^ Abs_id), Pretty.brk 1,
   352                      Pretty.str "x) = x;"]) ^ "\n\n" ^
   353                    (if "term_of" mem !Codegen.mode then
   354                       Pretty.string_of (Pretty.block [Pretty.str "fun ",
   355                         Codegen.mk_term_of gr'' module' false newT, Pretty.brk 1,
   356                         Pretty.str ("(" ^ Abs_id), Pretty.brk 1,
   357                         Pretty.str "x) =", Pretty.brk 1,
   358                         Pretty.block [Pretty.str ("Const (\"" ^ Abs_name ^ "\","),
   359                           Pretty.brk 1, Codegen.mk_type false (oldT --> newT),
   360                           Pretty.str ")"], Pretty.str " $", Pretty.brk 1,
   361                         Codegen.mk_term_of gr'' module' false oldT, Pretty.brk 1,
   362                         Pretty.str "x;"]) ^ "\n\n"
   363                     else "") ^
   364                    (if "test" mem !Codegen.mode then
   365                       Pretty.string_of (Pretty.block [Pretty.str "fun ",
   366                         Codegen.mk_gen gr'' module' false [] "" newT, Pretty.brk 1,
   367                         Pretty.str "i =", Pretty.brk 1,
   368                         Pretty.block [Pretty.str (Abs_id ^ " ("),
   369                           Codegen.mk_gen gr'' module' false [] "" oldT, Pretty.brk 1,
   370                           Pretty.str "i);"]]) ^ "\n\n"
   371                     else "")
   372                in Codegen.map_node node_id (K (NONE, module', s)) gr'' end
   373              | SOME _ => Codegen.add_edge (node_id, dep) gr', tyexpr)
   374            end)
   375   | typedef_tycodegen thy defs gr dep module brack _ = NONE;
   376 
   377 val setup =
   378   [TypedefData.init,
   379    Codegen.add_codegen "typedef" typedef_codegen,
   380    Codegen.add_tycodegen "typedef" typedef_tycodegen];
   381 
   382 
   383 
   384 (** outer syntax **)
   385 
   386 local structure P = OuterParse and K = OuterKeyword in
   387 
   388 val typedeclP =
   389   OuterSyntax.command "typedecl" "type declaration (HOL)" K.thy_decl
   390     (P.type_args -- P.name -- P.opt_infix >> (fn ((vs, t), mx) =>
   391       Toplevel.theory (add_typedecls [(t, vs, mx)])));
   392 
   393 
   394 val typedef_decl =
   395   Scan.optional (P.$$$ "(" |--
   396       ((P.$$$ "open" >> K false) -- Scan.option P.name || P.name >> (fn s => (true, SOME s)))
   397         --| P.$$$ ")") (true, NONE) --
   398     (P.type_args -- P.name) -- P.opt_infix -- (P.$$$ "=" |-- P.term) --
   399     Scan.option (P.$$$ "morphisms" |-- P.!!! (P.name -- P.name));
   400 
   401 fun mk_typedef ((((((def, opt_name), (vs, t)), mx), A), morphs)) =
   402   typedef ((def, if_none opt_name (Syntax.type_name t mx)), (t, vs, mx), A, morphs);
   403 
   404 val typedefP =
   405   OuterSyntax.command "typedef" "HOL type definition (requires non-emptiness proof)" K.thy_goal
   406     (typedef_decl >> (Toplevel.print oo (Toplevel.theory_to_proof o mk_typedef)));
   407 
   408 
   409 val _ = OuterSyntax.add_keywords ["morphisms"];
   410 val _ = OuterSyntax.add_parsers [typedeclP, typedefP];
   411 
   412 end;
   413 
   414 end;