src/HOL/Tools/typedef_package.ML
author wenzelm
Thu Aug 03 17:30:36 2006 +0200 (2006-08-03)
changeset 20328 5b240a4216b0
parent 20046 9c8909fc5865
child 20357 5fb92bd3aaea
permissions -rw-r--r--
RuleInsts.bires_inst_tac;
     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   type info =
    13    {rep_type: typ, abs_type: typ, Rep_name: string, Abs_name: string,
    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,
    16     Abs_cases: thm, Rep_induct: thm, Abs_induct: thm};
    17   val get_info: theory -> string -> info option
    18   val add_typedef: bool -> string option -> bstring * string list * mixfix ->
    19     string -> (bstring * bstring) option -> tactic -> theory -> info * theory
    20   val add_typedef_i: bool -> string option -> bstring * string list * mixfix ->
    21     term -> (bstring * bstring) option -> tactic -> theory -> info * theory
    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
    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 HOL_arity (raw_name, args, mx) thy =
    52   thy |> AxClass.axiomatize_arity_i
    53     (Sign.full_name thy (Syntax.type_name raw_name mx),
    54       replicate (length args) HOLogic.typeS, HOLogic.typeS);
    55 
    56 fun add_typedecls decls thy =
    57   thy
    58   |> Theory.add_typedecls decls
    59   |> can (Theory.assert_super HOL.thy) ? fold HOL_arity decls;
    60 
    61 
    62 
    63 (** type definitions **)
    64 
    65 (* messages *)
    66 
    67 val quiet_mode = ref false;
    68 fun message s = if ! quiet_mode then () else writeln s;
    69 
    70 
    71 (* theory data *)
    72 
    73 type info =
    74  {rep_type: typ, abs_type: typ, Rep_name: string, Abs_name: string,
    75   type_definition: thm, set_def: thm option, Rep: thm, Rep_inverse: thm,
    76   Abs_inverse: thm, Rep_inject: thm, Abs_inject: thm, Rep_cases: thm,
    77   Abs_cases: thm, Rep_induct: thm, Abs_induct: thm};
    78 
    79 structure TypedefData = TheoryDataFun
    80 (struct
    81   val name = "HOL/typedef";
    82   type T = info Symtab.table;
    83   val empty = Symtab.empty;
    84   val copy = I;
    85   val extend = I;
    86   fun merge _ tabs : T = Symtab.merge (K true) tabs;
    87   fun print _ _ = ();
    88 end);
    89 
    90 val get_info = Symtab.lookup o TypedefData.get;
    91 fun put_info name info = TypedefData.map (Symtab.update (name, info));
    92 
    93 
    94 (* prepare_typedef *)
    95 
    96 fun read_term thy used s =
    97   #1 (Thm.read_def_cterm (thy, K NONE, K NONE) used true (s, HOLogic.typeT));
    98 
    99 fun cert_term thy _ t = Thm.cterm_of thy t handle TERM (msg, _) => error msg;
   100 
   101 fun err_in_typedef msg name =
   102   cat_error msg ("The error(s) above occurred in typedef " ^ quote name);
   103 
   104 fun prepare_typedef prep_term def name (t, vs, mx) raw_set opt_morphs thy =
   105   let
   106     val _ = Theory.requires thy "Typedef" "typedefs";
   107     val full = Sign.full_name thy;
   108 
   109     (*rhs*)
   110     val full_name = full name;
   111     val cset = prep_term thy vs raw_set;
   112     val {T = setT, t = set, ...} = Thm.rep_cterm cset;
   113     val rhs_tfrees = Term.add_tfrees set [];
   114     val rhs_tfreesT = Term.add_tfreesT setT [];
   115     val oldT = HOLogic.dest_setT setT handle TYPE _ =>
   116       error ("Not a set type: " ^ quote (Sign.string_of_typ thy setT));
   117     fun mk_nonempty A =
   118       HOLogic.mk_Trueprop (HOLogic.mk_exists ("x", oldT, HOLogic.mk_mem (Free ("x", oldT), A)));
   119     val goal = mk_nonempty set;
   120     val goal_pat = mk_nonempty (Var (the_default (name, 0) (Syntax.read_variable name), setT));
   121 
   122     (*lhs*)
   123     val defS = Sign.defaultS thy;
   124     val lhs_tfrees = map (fn v => (v, the_default defS (AList.lookup (op =) rhs_tfrees v))) vs;
   125     val args_setT = lhs_tfrees
   126       |> filter (member (op =) rhs_tfrees andf (not o member (op =) rhs_tfreesT))
   127       |> map TFree;
   128 
   129     val tname = Syntax.type_name t mx;
   130     val full_tname = full tname;
   131     val newT = Type (full_tname, map TFree lhs_tfrees);
   132 
   133     val (Rep_name, Abs_name) = the_default ("Rep_" ^ name, "Abs_" ^ name) opt_morphs;
   134     val setT' = map Term.itselfT args_setT ---> setT;
   135     val setC = Term.list_comb (Const (full_name, setT'), map Logic.mk_type args_setT);
   136     val RepC = Const (full Rep_name, newT --> oldT);
   137     val AbsC = Const (full Abs_name, oldT --> newT);
   138     val x_new = Free ("x", newT);
   139     val y_old = Free ("y", oldT);
   140 
   141     val set' = if def then setC else set;
   142 
   143     val typedef_name = "type_definition_" ^ name;
   144     val typedefC =
   145       Const (type_definitionN, (newT --> oldT) --> (oldT --> newT) --> setT --> HOLogic.boolT);
   146     val typedef_prop =
   147       Logic.mk_implies (goal, HOLogic.mk_Trueprop (typedefC $ RepC $ AbsC $ set'));
   148     val typedef_deps = Term.fold_aterms (fn Const c => insert (op =) c | _ => I) set' [];
   149 
   150     fun add_def eq thy =
   151       if def then
   152         thy
   153         |> PureThy.add_defs_i false [Thm.no_attributes eq]
   154         |-> (fn [th] => pair (SOME th))
   155       else (NONE, thy);
   156 
   157     fun typedef_result nonempty context =
   158       Context.the_theory context
   159       |> add_typedecls [(t, vs, mx)]
   160       |> Theory.add_consts_i
   161        ((if def then [(name, setT', NoSyn)] else []) @
   162         [(Rep_name, newT --> oldT, NoSyn),
   163          (Abs_name, oldT --> newT, NoSyn)])
   164       |> add_def (Logic.mk_defpair (setC, set))
   165       ||>> PureThy.add_axioms_i [((typedef_name, typedef_prop),
   166           [apsnd (fn cond_axm => nonempty RS cond_axm)])]
   167       ||> Theory.add_deps "" (dest_Const RepC) typedef_deps
   168       ||> Theory.add_deps "" (dest_Const AbsC) typedef_deps
   169       |-> (fn (set_def, [type_definition]) => fn thy1 =>
   170         let
   171           fun make th = Drule.standard (th OF [type_definition]);
   172           val abs_inject = make Abs_inject;
   173           val abs_inverse = make Abs_inverse;
   174           val ([Rep, Rep_inverse, Abs_inverse, Rep_inject, Abs_inject,
   175               Rep_cases, Abs_cases, Rep_induct, Abs_induct], thy2) =
   176             thy1
   177             |> Theory.add_path name
   178             |> PureThy.add_thms
   179               ([((Rep_name, make Rep), []),
   180                 ((Rep_name ^ "_inverse", make Rep_inverse), []),
   181                 ((Abs_name ^ "_inverse", abs_inverse), []),
   182                 ((Rep_name ^ "_inject", make Rep_inject), []),
   183                 ((Abs_name ^ "_inject", abs_inject), []),
   184                 ((Rep_name ^ "_cases", make Rep_cases),
   185                   [RuleCases.case_names [Rep_name], InductAttrib.cases_set full_name]),
   186                 ((Abs_name ^ "_cases", make Abs_cases),
   187                   [RuleCases.case_names [Abs_name], InductAttrib.cases_type full_tname]),
   188                 ((Rep_name ^ "_induct", make Rep_induct),
   189                   [RuleCases.case_names [Rep_name], InductAttrib.induct_set full_name]),
   190                 ((Abs_name ^ "_induct", make Abs_induct),
   191                   [RuleCases.case_names [Abs_name], InductAttrib.induct_type full_tname])])
   192             ||> Theory.parent_path;
   193           val info = {rep_type = oldT, abs_type = newT,
   194             Rep_name = full Rep_name, Abs_name = full Abs_name,
   195               type_definition = type_definition, set_def = set_def,
   196               Rep = Rep, Rep_inverse = Rep_inverse, Abs_inverse = Abs_inverse,
   197               Rep_inject = Rep_inject, Abs_inject = Abs_inject, Rep_cases = Rep_cases,
   198             Abs_cases = Abs_cases, Rep_induct = Rep_induct, Abs_induct = Abs_induct};
   199           val thy3 = thy2 |> put_info full_tname info;
   200         in (info, Context.Theory thy3) end);
   201 
   202 
   203     (* errors *)
   204 
   205     fun show_names pairs = commas_quote (map fst pairs);
   206 
   207     val illegal_vars =
   208       if null (term_vars set) andalso null (term_tvars set) then []
   209       else ["Illegal schematic variable(s) on rhs"];
   210 
   211     val dup_lhs_tfrees =
   212       (case duplicates (op =) lhs_tfrees of [] => []
   213       | dups => ["Duplicate type variables on lhs: " ^ show_names dups]);
   214 
   215     val extra_rhs_tfrees =
   216       (case fold (remove (op =)) lhs_tfrees rhs_tfrees of [] => []
   217       | extras => ["Extra type variables on rhs: " ^ show_names extras]);
   218 
   219     val illegal_frees =
   220       (case term_frees set of [] => []
   221       | xs => ["Illegal variables on rhs: " ^ show_names (map dest_Free xs)]);
   222 
   223     val errs = illegal_vars @ dup_lhs_tfrees @ extra_rhs_tfrees @ illegal_frees;
   224     val _ = if null errs then () else error (cat_lines errs);
   225 
   226     (*test theory errors now!*)
   227     val test_thy = Theory.copy thy;
   228     val _ =
   229       Context.Theory test_thy
   230       |> typedef_result (setmp quick_and_dirty true (SkipProof.make_thm test_thy) goal);
   231 
   232   in (cset, goal, goal_pat, typedef_result) end
   233   handle ERROR msg => err_in_typedef msg name;
   234 
   235 
   236 (* add_typedef interfaces *)
   237 
   238 local
   239 
   240 fun gen_typedef prep_term def opt_name typ set opt_morphs tac thy =
   241   let
   242     val name = the_default (#1 typ) opt_name;
   243     val (cset, goal, _, typedef_result) =
   244       prepare_typedef prep_term def name typ set opt_morphs thy;
   245     val _ = message ("Proving non-emptiness of set " ^ quote (string_of_cterm cset) ^ " ...");
   246     val non_empty = Goal.prove_global thy [] [] goal (K tac) handle ERROR msg =>
   247       cat_error msg ("Failed to prove non-emptiness of " ^ quote (string_of_cterm cset));
   248   in
   249     Context.Theory thy
   250     |> typedef_result non_empty
   251     ||> Context.the_theory
   252   end;
   253 
   254 in
   255 
   256 val add_typedef = gen_typedef read_term;
   257 val add_typedef_i = gen_typedef cert_term;
   258 
   259 end;
   260 
   261 
   262 (* Isar typedef interface *)
   263 
   264 local
   265 
   266 fun gen_typedef prep_term ((def, name), typ, set, opt_morphs) thy =
   267   let
   268     val (_, goal, goal_pat, typedef_result) =
   269       prepare_typedef prep_term def name typ set opt_morphs thy;
   270     fun att (thy, th) =
   271       let val ({type_definition, ...}, thy') = typedef_result th thy
   272       in (thy', type_definition) end;
   273   in IsarThy.theorem_i PureThy.internalK ("", [att]) (goal, [goal_pat]) thy end;
   274 
   275 in
   276 
   277 val typedef = gen_typedef read_term;
   278 val typedef_i = gen_typedef cert_term;
   279 
   280 end;
   281 
   282 val setup = TypedefData.init;
   283 
   284 
   285 
   286 (** outer syntax **)
   287 
   288 local structure P = OuterParse and K = OuterKeyword in
   289 
   290 val typedeclP =
   291   OuterSyntax.command "typedecl" "type declaration (HOL)" K.thy_decl
   292     (P.type_args -- P.name -- P.opt_infix >> (fn ((vs, t), mx) =>
   293       Toplevel.theory (add_typedecls [(t, vs, mx)])));
   294 
   295 
   296 val typedef_decl =
   297   Scan.optional (P.$$$ "(" |--
   298       ((P.$$$ "open" >> K false) -- Scan.option P.name || P.name >> (fn s => (true, SOME s)))
   299         --| P.$$$ ")") (true, NONE) --
   300     (P.type_args -- P.name) -- P.opt_infix -- (P.$$$ "=" |-- P.term) --
   301     Scan.option (P.$$$ "morphisms" |-- P.!!! (P.name -- P.name));
   302 
   303 fun mk_typedef ((((((def, opt_name), (vs, t)), mx), A), morphs)) =
   304   typedef ((def, the_default (Syntax.type_name t mx) opt_name), (t, vs, mx), A, morphs);
   305 
   306 val typedefP =
   307   OuterSyntax.command "typedef" "HOL type definition (requires non-emptiness proof)" K.thy_goal
   308     (typedef_decl >> (Toplevel.print oo (Toplevel.theory_to_proof o mk_typedef)));
   309 
   310 
   311 val _ = OuterSyntax.add_keywords ["morphisms"];
   312 val _ = OuterSyntax.add_parsers [typedeclP, typedefP];
   313 
   314 end;
   315 
   316 end;