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