src/HOL/Tools/function_package/fundef_package.ML
author krauss
Tue Nov 07 21:28:14 2006 +0100 (2006-11-07)
changeset 21235 674e2731b519
parent 21211 5370cfbf3070
child 21237 b803f9870e97
permissions -rw-r--r--
Added datatype hook to declare all case_congs as "fundef_cong" automatically.
     1 (*  Title:      HOL/Tools/function_package/fundef_package.ML
     2     ID:         $Id$
     3     Author:     Alexander Krauss, TU Muenchen
     4 
     5 A package for general recursive function definitions.
     6 Isar commands.
     7 
     8 *)
     9 
    10 signature FUNDEF_PACKAGE =
    11 sig
    12     val add_fundef :  (string * string option * mixfix) list
    13                       -> ((bstring * Attrib.src list) * string list) list list
    14                       -> FundefCommon.fundef_config
    15                       -> local_theory
    16                       -> string * Proof.state
    17 
    18     val add_fundef_i:  (string * typ option * mixfix) list
    19                        -> ((bstring * Attrib.src list) * term list) list list
    20                        -> bool
    21                        -> local_theory
    22                        -> string * Proof.state
    23 
    24     val setup_termination_proof : string option -> local_theory -> Proof.state
    25 
    26     val cong_add: attribute
    27     val cong_del: attribute
    28 
    29     val setup : theory -> theory
    30     val setup_case_cong_hook : theory -> theory
    31     val get_congs : theory -> thm list
    32 end
    33 
    34 
    35 structure FundefPackage  =
    36 struct
    37 
    38 open FundefLib
    39 open FundefCommon
    40 
    41 (*fn (ctxt,s) => Variable.importT_terms (fst (ProofContext.read_termTs ctxt (K false) (K NONE) (K NONE) [] [s])) ctxt;*)
    42 
    43 fun burrow_snd f ps = (* ('a list -> 'b list) -> ('c * 'a) list -> ('c * 'b) list *)
    44     let val (xs, ys) = split_list ps
    45     in xs ~~ f ys end
    46 
    47 fun restore_spec_structure reps spec =
    48     (burrow o burrow_snd o burrow o K) reps spec
    49 
    50 fun add_simps label moreatts mutual_info fixes psimps spec lthy =
    51     let
    52       val fnames = map (fst o fst) fixes
    53       val psimps_by_f = FundefMutual.sort_by_function mutual_info fnames psimps
    54 
    55       fun add_for_f fname psimps =
    56           LocalTheory.note ((NameSpace.append fname label, Attrib.internal Simplifier.simp_add :: moreatts), psimps) #> snd
    57     in
    58       lthy
    59         |> fold_map (fold_map LocalTheory.note) (restore_spec_structure psimps spec) |> snd
    60         |> fold2 add_for_f fnames psimps_by_f
    61     end
    62 
    63 
    64 fun fundef_afterqed fixes spec mutual_info defname data [[result]] lthy =
    65     let
    66         val fundef_data = FundefMutual.mk_partial_rules_mutual lthy mutual_info data result
    67         val FundefMResult {psimps, subset_pinducts, simple_pinducts, termination, domintros, cases, ...} = fundef_data
    68         val qualify = NameSpace.append defname;
    69     in
    70       lthy
    71         |> add_simps "psimps" [] mutual_info fixes psimps spec
    72         |> LocalTheory.note ((qualify "domintros", []), domintros) |> snd
    73         |> LocalTheory.note ((qualify "termination", []), [termination]) |> snd
    74         |> LocalTheory.note ((qualify "cases", []), [cases]) |> snd
    75         |> LocalTheory.note ((qualify "pinduct", [Attrib.internal (InductAttrib.induct_set "")]), simple_pinducts) |> snd
    76         |> LocalTheory.declaration (add_fundef_data defname (fundef_data, mutual_info, (fixes,spec)))
    77     end (* FIXME: Add cases for induct and cases thm *)
    78 
    79 
    80 
    81 fun prep_with_flags prep fixspec eqnss_flags global_flag lthy =
    82     let
    83       val eqnss = map (map (apsnd (map fst))) eqnss_flags
    84       val flags = map (map (map (fn (_, f) => global_flag orelse f) o snd)) eqnss_flags
    85 
    86       val ((fixes, _), ctxt') = prep fixspec [] lthy
    87       val spec = map (fn eqns => snd (fst (prep [] eqns ctxt'))) eqnss
    88                      |> map (map (apsnd (map (fn t => fold_rev (mk_forall o Free) (frees_in_term ctxt' t) t)))) (* Add quantifiers *)
    89                      |> map2 (map2 (fn fs => fn (r, thms) => (r, fs ~~ thms))) flags
    90                      |> (burrow o burrow_snd o burrow)
    91                           (FundefSplit.split_some_equations lthy)
    92                      |> map (map (apsnd flat))
    93     in
    94       ((fixes, spec), ctxt')
    95     end
    96 
    97 
    98 fun gen_add_fundef prep_spec fixspec eqnss_flags config lthy =
    99     let
   100       val FundefConfig {sequential, default, ...} = config
   101 
   102       val ((fixes, spec), ctxt') = prep_with_flags prep_spec fixspec eqnss_flags sequential lthy
   103       val t_eqns = spec
   104                      |> flat |> map snd |> flat (* flatten external structure *)
   105 
   106       val ((mutual_info, name, prep_result as Prep {goal, goalI, ...}), lthy) =
   107           FundefMutual.prepare_fundef_mutual fixes t_eqns default lthy
   108 
   109       val afterqed = fundef_afterqed fixes spec mutual_info name prep_result
   110     in
   111       (name, lthy
   112          |> Proof.theorem_i PureThy.internalK NONE afterqed NONE ("", []) [(("", []), [(goal, [])])]
   113          |> Proof.refine (Method.primitive_text (fn _ => goalI)) |> Seq.hd)
   114     end
   115 
   116 
   117 fun total_termination_afterqed defname data [[totality]] lthy =
   118     let
   119         val (FundefMResult {psimps, simple_pinducts, ... }, mutual_info, (fixes, stmts)) = data
   120 
   121         val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
   122 
   123         val tsimps = map remove_domain_condition psimps
   124         val tinduct = map remove_domain_condition simple_pinducts
   125 
   126         (* FIXME: How to generate code from (possibly) local contexts
   127         val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
   128         val allatts = if has_guards then [] else [Attrib.internal (RecfunCodegen.add NONE)]
   129         *)
   130         val qualify = NameSpace.append defname;
   131     in
   132         lthy
   133           |> add_simps "simps" [] mutual_info fixes tsimps stmts
   134           |> LocalTheory.note ((qualify "induct", []), tinduct) |> snd
   135     end
   136 
   137 
   138 fun setup_termination_proof name_opt lthy =
   139     let
   140         val name = the_default (get_last_fundef (Context.Proof lthy)) name_opt
   141         val data = the (get_fundef_data name (Context.Proof lthy))
   142                    handle Option.Option => raise ERROR ("No such function definition: " ^ name)
   143 
   144         val (res as FundefMResult {termination, ...}, _, _) = data
   145         val goal = FundefTermination.mk_total_termination_goal data
   146     in
   147       lthy
   148         |> ProofContext.note_thmss_i [(("termination",
   149                                  [ContextRules.intro_query NONE]), [(ProofContext.standard lthy [termination], [])])] |> snd
   150         |> Proof.theorem_i PureThy.internalK NONE
   151                            (total_termination_afterqed name data) NONE ("", [])
   152                            [(("", []), [(goal, [])])]
   153     end
   154 
   155 
   156 val add_fundef = gen_add_fundef Specification.read_specification
   157 val add_fundef_i = gen_add_fundef Specification.cert_specification
   158 
   159 
   160 
   161 (* congruence rules *)
   162 
   163 val cong_add = Thm.declaration_attribute (map_fundef_congs o Drule.add_rule o safe_mk_meta_eq);
   164 val cong_del = Thm.declaration_attribute (map_fundef_congs o Drule.del_rule o safe_mk_meta_eq);
   165 
   166 (* Datatype hook to declare datatype congs as "fundef_congs" *)
   167 
   168 
   169 fun add_case_cong n thy = 
   170     Context.theory_map (map_fundef_congs (Drule.add_rule 
   171                           (DatatypePackage.get_datatype thy n |> the
   172                            |> #case_cong
   173                            |> safe_mk_meta_eq))) 
   174                        thy
   175 
   176 val case_cong_hook = fold add_case_cong
   177 
   178 val setup_case_cong_hook = 
   179     DatatypeHooks.add case_cong_hook
   180     #> (fn thy => case_cong_hook (Symtab.keys (DatatypePackage.get_datatypes thy)) thy)
   181 
   182 (* setup *)
   183 
   184 val setup = 
   185     FundefData.init 
   186       #> FundefCongs.init
   187       #>  Attrib.add_attributes
   188             [("fundef_cong", Attrib.add_del_args cong_add cong_del, "declaration of congruence rule for function definitions")]
   189       #> setup_case_cong_hook
   190 
   191 val get_congs = FundefCommon.get_fundef_congs o Context.Theory
   192 
   193 
   194 
   195 (* outer syntax *)
   196 
   197 local structure P = OuterParse and K = OuterKeyword in
   198 
   199 
   200 
   201 fun or_list1 s = P.enum1 "|" s
   202 
   203 val opt_sequential = Scan.optional ((P.$$$ "(" |-- P.$$$ "sequential" --| P.$$$ ")") >> K true) false
   204 
   205 val otherwise = P.$$$ "(" |-- P.$$$ "otherwise" --| P.$$$ ")"
   206 val statement_ow = P.and_list1 (P.opt_thm_name ":" -- Scan.repeat1 (P.prop -- Scan.optional (otherwise >> K true) false))
   207 val statements_ow = or_list1 statement_ow
   208 
   209 
   210 val functionP =
   211   OuterSyntax.command "function" "define general recursive functions" K.thy_goal
   212   ((config_parser default_config -- P.opt_locale_target -- P.fixes --| P.$$$ "where" -- statements_ow)
   213      >> (fn (((config, target), fixes), statements) =>
   214             Toplevel.local_theory_to_proof target (add_fundef fixes statements config #> snd)
   215             #> Toplevel.print));
   216 
   217 
   218 
   219 val terminationP =
   220   OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
   221   (P.opt_locale_target -- Scan.option P.name
   222     >> (fn (target, name) =>
   223            Toplevel.print o
   224            Toplevel.local_theory_to_proof target (setup_termination_proof name)));
   225 
   226 
   227 val _ = OuterSyntax.add_parsers [functionP];
   228 val _ = OuterSyntax.add_parsers [terminationP];
   229 val _ = OuterSyntax.add_keywords ["sequential", "otherwise"];
   230 
   231 end;
   232 
   233 
   234 end