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