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