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