src/HOL/Tools/function_package/fundef_package.ML
author krauss
Wed Nov 08 22:24:54 2006 +0100 (2006-11-08)
changeset 21255 617fdb08abe9
parent 21240 8e75fb38522c
child 21319 cf814e36f788
permissions -rw-r--r--
added profiling code, improved handling of proof terms, generation of domain
introduction rules becomes optional (global reference FundefCommon.domintros)
     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 
    54       val (saved_spec_psimps, lthy) = fold_map (fold_map LocalTheory.note) (restore_spec_structure psimps spec) lthy
    55       val saved_psimps = flat (map snd (flat saved_spec_psimps))
    56 
    57       val psimps_by_f = FundefMutual.sort_by_function mutual_info fnames saved_psimps
    58 
    59       fun add_for_f fname psimps =
    60           LocalTheory.note ((NameSpace.append fname label, Attrib.internal Simplifier.simp_add :: moreatts), psimps) #> snd
    61     in
    62       (saved_psimps,
    63        fold2 add_for_f fnames psimps_by_f lthy)
    64     end
    65 
    66 
    67 fun fundef_afterqed fixes spec mutual_info defname data [[result]] lthy =
    68     let
    69       val Prep {f, R, ...} = data
    70       val fundef_data = FundefMutual.mk_partial_rules_mutual lthy mutual_info data result
    71       val FundefMResult {psimps, subset_pinducts, simple_pinducts, termination, domintros, cases, ...} = fundef_data
    72       val qualify = NameSpace.append defname
    73           
    74       val (((psimps', pinducts'), (_, [termination'])), lthy) = 
    75           lthy
    76             |> PROFILE "adding_psimps" (add_simps "psimps" [] mutual_info fixes psimps spec)
    77             ||>> PROFILE "adding pinduct" (LocalTheory.note ((qualify "pinduct", [Attrib.internal (InductAttrib.induct_set "")]), simple_pinducts))
    78             ||>> PROFILE "adding termination" (LocalTheory.note ((qualify "termination", []), [termination]))
    79             ||> (snd o PROFILE "adding cases" (LocalTheory.note ((qualify "cases", []), [cases])))
    80             ||> (snd o PROFILE "adding domintros" (LocalTheory.note ((qualify "domintros", []), domintros)))
    81 
    82       val cdata = FundefCtxData { fixes=fixes, spec=spec, mutual=mutual_info, psimps=psimps',
    83                                   pinducts=snd pinducts', termination=termination', f=f, R=R }
    84 
    85       
    86     in
    87       lthy
    88         |> LocalTheory.declaration (add_fundef_data defname cdata) (* save in target *)
    89         |> Context.proof_map (add_fundef_data defname cdata) (* also save in local context *)
    90     end (* FIXME: Add cases for induct and cases thm *)
    91 
    92 
    93 
    94 fun prep_with_flags prep fixspec eqnss_flags global_flag lthy =
    95     let
    96       val eqnss = map (map (apsnd (map fst))) eqnss_flags
    97       val flags = map (map (map (fn (_, f) => global_flag orelse f) o snd)) eqnss_flags
    98 
    99       val ((fixes, _), ctxt') = prep fixspec [] lthy
   100       val spec = map (fn eqns => snd (fst (prep [] eqns ctxt'))) eqnss
   101                      |> map (map (apsnd (map (fn t => fold_rev (mk_forall o Free) (frees_in_term ctxt' t) t)))) (* Add quantifiers *)
   102                      |> map2 (map2 (fn fs => fn (r, thms) => (r, fs ~~ thms))) flags
   103                      |> (burrow o burrow_snd o burrow)
   104                           (FundefSplit.split_some_equations lthy)
   105                      |> map (map (apsnd flat))
   106     in
   107       ((fixes, spec), ctxt')
   108     end
   109 
   110 
   111 fun gen_add_fundef prep_spec fixspec eqnss_flags config lthy =
   112     let
   113       val FundefConfig {sequential, default, ...} = config
   114 
   115       val ((fixes, spec), ctxt') = prep_with_flags prep_spec fixspec eqnss_flags sequential lthy
   116       val t_eqns = spec
   117                      |> flat |> map snd |> flat (* flatten external structure *)
   118 
   119       val ((mutual_info, name, prep_result as Prep {goal, goalI, ...}), lthy) =
   120           FundefMutual.prepare_fundef_mutual fixes t_eqns default lthy
   121 
   122       val afterqed = fundef_afterqed fixes spec mutual_info name prep_result
   123     in
   124       (name, lthy
   125          |> Proof.theorem_i PureThy.internalK NONE afterqed NONE ("", []) [(("", []), [(goal, [])])]
   126          |> Proof.refine (Method.primitive_text (fn _ => goalI)) |> Seq.hd)
   127     end
   128 
   129 
   130 fun total_termination_afterqed defname data [[totality]] lthy =
   131     let
   132       val FundefCtxData { fixes, spec, mutual, psimps, pinducts, ... } = data
   133 
   134       val totality = PROFILE "closing" Drule.close_derivation totality
   135 
   136       val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
   137 
   138       val tsimps = PROFILE "making tsimps" (map remove_domain_condition) psimps
   139       val tinduct = PROFILE "making tinduct" (map remove_domain_condition) pinducts
   140 
   141         (* FIXME: How to generate code from (possibly) local contexts
   142         val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
   143         val allatts = if has_guards then [] else [Attrib.internal (RecfunCodegen.add NONE)]
   144         *)
   145         val qualify = NameSpace.append defname;
   146     in
   147         lthy
   148           |> PROFILE "adding tsimps" (add_simps "simps" [] mutual fixes tsimps spec) |> snd
   149           |> PROFILE "adding tinduct" (LocalTheory.note ((qualify "induct", []), tinduct)) |> snd
   150     end
   151 
   152 
   153 fun setup_termination_proof name_opt lthy =
   154     let
   155         val name = the_default (get_last_fundef (Context.Proof lthy)) name_opt
   156         val data = the (get_fundef_data name (Context.Proof lthy))
   157                    handle Option.Option => raise ERROR ("No such function definition: " ^ name)
   158 
   159         val FundefCtxData {termination, f, R, ...} = data
   160         val goal = FundefTermination.mk_total_termination_goal f R
   161     in
   162       lthy
   163         |> ProofContext.note_thmss_i [(("termination",
   164                                         [ContextRules.intro_query NONE]), [(ProofContext.standard lthy [termination], [])])] |> snd
   165         |> Proof.theorem_i PureThy.internalK NONE
   166                            (total_termination_afterqed name data) NONE ("", [])
   167                            [(("", []), [(goal, [])])]
   168     end
   169 
   170 
   171 val add_fundef = gen_add_fundef Specification.read_specification
   172 val add_fundef_i = gen_add_fundef Specification.cert_specification
   173 
   174 
   175 
   176 (* congruence rules *)
   177 
   178 val cong_add = Thm.declaration_attribute (map_fundef_congs o Drule.add_rule o safe_mk_meta_eq);
   179 val cong_del = Thm.declaration_attribute (map_fundef_congs o Drule.del_rule o safe_mk_meta_eq);
   180 
   181 (* Datatype hook to declare datatype congs as "fundef_congs" *)
   182 
   183 
   184 fun add_case_cong n thy = 
   185     Context.theory_map (map_fundef_congs (Drule.add_rule 
   186                           (DatatypePackage.get_datatype thy n |> the
   187                            |> #case_cong
   188                            |> safe_mk_meta_eq))) 
   189                        thy
   190 
   191 val case_cong_hook = fold add_case_cong
   192 
   193 val setup_case_cong_hook = 
   194     DatatypeHooks.add case_cong_hook
   195     #> (fn thy => case_cong_hook (Symtab.keys (DatatypePackage.get_datatypes thy)) thy)
   196 
   197 (* setup *)
   198 
   199 val setup = 
   200     FundefData.init 
   201       #> FundefCongs.init
   202       #>  Attrib.add_attributes
   203             [("fundef_cong", Attrib.add_del_args cong_add cong_del, "declaration of congruence rule for function definitions")]
   204       #> setup_case_cong_hook
   205 
   206 val get_congs = FundefCommon.get_fundef_congs o Context.Theory
   207 
   208 
   209 
   210 (* outer syntax *)
   211 
   212 local structure P = OuterParse and K = OuterKeyword in
   213 
   214 
   215 
   216 fun or_list1 s = P.enum1 "|" s
   217 
   218 val opt_sequential = Scan.optional ((P.$$$ "(" |-- P.$$$ "sequential" --| P.$$$ ")") >> K true) false
   219 
   220 val otherwise = P.$$$ "(" |-- P.$$$ "otherwise" --| P.$$$ ")"
   221 val statement_ow = P.and_list1 (P.opt_thm_name ":" -- Scan.repeat1 (P.prop -- Scan.optional (otherwise >> K true) false))
   222 val statements_ow = or_list1 statement_ow
   223 
   224 
   225 val functionP =
   226   OuterSyntax.command "function" "define general recursive functions" K.thy_goal
   227   ((config_parser default_config -- P.opt_locale_target -- P.fixes --| P.$$$ "where" -- statements_ow)
   228      >> (fn (((config, target), fixes), statements) =>
   229             Toplevel.local_theory_to_proof target (add_fundef fixes statements config #> snd)
   230             #> Toplevel.print));
   231 
   232 
   233 
   234 val terminationP =
   235   OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
   236   (P.opt_locale_target -- Scan.option P.name
   237     >> (fn (target, name) =>
   238            Toplevel.print o
   239            Toplevel.local_theory_to_proof target (setup_termination_proof name)));
   240 
   241 
   242 val _ = OuterSyntax.add_parsers [functionP];
   243 val _ = OuterSyntax.add_parsers [terminationP];
   244 val _ = OuterSyntax.add_keywords ["sequential", "otherwise"];
   245 
   246 end;
   247 
   248 
   249 end