src/HOL/Tools/function_package/fundef_package.ML
author krauss
Tue Apr 10 18:09:58 2007 +0200 (2007-04-10)
changeset 22623 5fcee5b319a2
parent 22498 62cdd4b3e96b
child 22635 d33735c0f225
permissions -rw-r--r--
proper handling of morphisms
     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 * bool)) 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 * bool)) list
    20                        -> FundefCommon.fundef_config
    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 : FUNDEF_PACKAGE =
    36 struct
    37 
    38 open FundefLib
    39 open FundefCommon
    40 
    41 val note_theorem = LocalTheory.note Thm.theoremK
    42 
    43 fun mk_defname fixes = fixes |> map (fst o fst) |> space_implode "_" 
    44 
    45 fun burrow_snd f ps = (* ('a list -> 'b list) -> ('c * 'a) list -> ('c * 'b) list *)
    46     let val (xs, ys) = split_list ps
    47     in xs ~~ f ys end
    48 
    49 fun restore_spec_structure reps spec =
    50     (burrow_snd o burrow o K) reps spec
    51 
    52 fun add_simps fixes spec sort label moreatts simps lthy =
    53     let
    54       val fnames = map (fst o fst) fixes
    55 
    56       val (saved_spec_simps, lthy) =
    57         fold_map note_theorem (restore_spec_structure simps spec) lthy
    58       val saved_simps = flat (map snd saved_spec_simps)
    59 
    60       val simps_by_f = sort saved_simps
    61 
    62       fun add_for_f fname simps =
    63         note_theorem
    64           ((NameSpace.qualified fname label, Attrib.internal (K Simplifier.simp_add) :: moreatts),
    65             simps) #> snd
    66     in
    67       (saved_simps,
    68        fold2 add_for_f fnames simps_by_f lthy)
    69     end
    70 
    71 
    72 fun pr_ctxdata (x: fundef_context_data) = (Output.debug (K (PolyML.makestring x)); x)
    73 
    74 fun fundef_afterqed config fixes spec defname cont sort_cont [[proof]] lthy =
    75     let
    76       val FundefResult {f, R, psimps, trsimps, subset_pinducts, simple_pinducts, termination, domintros, cases, ...} = 
    77           cont (Goal.close_result proof)
    78 
    79       val qualify = NameSpace.qualified defname
    80       val addsmps = add_simps fixes spec sort_cont
    81 
    82       val (((psimps', pinducts'), (_, [termination'])), lthy) =
    83           lthy
    84             |> addsmps "psimps" [] psimps
    85             ||> fold_option (snd oo addsmps "simps" []) trsimps
    86             ||>> note_theorem ((qualify "pinduct",
    87                                 [Attrib.internal (K (InductAttrib.induct_set ""))]), simple_pinducts)
    88             ||>> note_theorem ((qualify "termination", []), [termination])
    89             ||> (snd o note_theorem ((qualify "cases", []), [cases]))
    90             ||> fold_option (snd oo curry note_theorem (qualify "domintros", [])) domintros
    91 
    92       val cdata = FundefCtxData { add_simps=addsmps, psimps=psimps',
    93                                   pinducts=snd pinducts', termination=termination', f=f, R=R }
    94             |> morph_fundef_data (LocalTheory.target_morphism lthy)
    95     in
    96       lthy 
    97         |> LocalTheory.declaration (fn phi => add_fundef_data defname (pr_ctxdata (morph_fundef_data phi cdata))) (* save in target *)
    98         |> Context.proof_map (add_fundef_data defname cdata) (* also save in local context *)
    99     end (* FIXME: Add cases for induct and cases thm *)
   100 
   101 
   102 
   103 fun prep_with_flags prep fixspec eqnss_flags global_flag lthy =
   104     let
   105       val flags = map (fn x => global_flag orelse (snd (snd x))) eqnss_flags
   106       val eqns = map (apsnd (single o fst)) eqnss_flags
   107 
   108       val ((fixes, _), ctxt') = prep fixspec [] lthy
   109 
   110       fun prep_eqn e = the_single (snd (fst (prep [] [e] ctxt')))
   111                          |> apsnd the_single
   112 
   113       val spec = map prep_eqn eqns
   114                      |> map (apsnd (fn t => fold_rev (mk_forall o Free) (frees_in_term ctxt' t) t)) (* Add quantifiers *)
   115                      |> burrow_snd (fn ts => FundefSplit.split_some_equations ctxt' (flags ~~ ts))
   116     in
   117       ((fixes, spec), ctxt')
   118     end
   119 
   120 fun gen_add_fundef prep_spec fixspec eqnss_flags config lthy =
   121     let
   122       val FundefConfig {sequential, default, tailrec, ...} = config
   123 
   124       val ((fixes, spec), ctxt') = prep_with_flags prep_spec fixspec eqnss_flags sequential lthy
   125 
   126       val defname = mk_defname fixes
   127 
   128       val t_eqns = spec |> map snd |> flat (* flatten external structure *)
   129 
   130       val ((goalstate, cont, sort_cont), lthy) =
   131           FundefMutual.prepare_fundef_mutual config defname fixes t_eqns default lthy
   132 
   133       val afterqed = fundef_afterqed config fixes spec defname cont sort_cont
   134     in
   135       (defname, lthy
   136          |> Proof.theorem_i NONE afterqed [[(Logic.unprotect (concl_of goalstate), [])]]
   137          |> Proof.refine (Method.primitive_text (fn _ => goalstate)) |> Seq.hd)
   138     end
   139 
   140 
   141 fun total_termination_afterqed defname data [[totality]] lthy =
   142     let
   143       val FundefCtxData { add_simps, psimps, pinducts, ... } = data
   144 
   145       val totality = Goal.close_result totality
   146 
   147       val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
   148 
   149       val tsimps = map remove_domain_condition psimps
   150       val tinduct = map remove_domain_condition pinducts
   151 
   152         (* FIXME: How to generate code from (possibly) local contexts*)
   153       val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
   154       val allatts = if has_guards then [] else [Attrib.internal (K (RecfunCodegen.add NONE))]
   155 
   156       val qualify = NameSpace.qualified defname;
   157     in
   158       lthy
   159         |> add_simps "simps" allatts tsimps |> snd
   160         |> note_theorem ((qualify "induct", []), tinduct) |> snd
   161     end
   162 
   163 
   164 fun setup_termination_proof name_opt lthy =
   165     let
   166         val defname = the_default (get_last_fundef (Context.Proof lthy)) name_opt
   167         val data = the (get_fundef_data defname (Context.Proof lthy))
   168                    handle Option.Option => raise ERROR ("No such function definition: " ^ defname)
   169 
   170         val FundefCtxData {termination, R, ...} = data
   171         val domT = domain_type (fastype_of R)
   172         val goal = HOLogic.mk_Trueprop (HOLogic.mk_all ("x", domT, mk_acc domT R $ Free ("x", domT)))
   173     in
   174       lthy
   175         |> ProofContext.note_thmss_i "" [(("", [ContextRules.rule_del]), [([allI], [])])] |> snd
   176         |> ProofContext.note_thmss_i "" [(("", [ContextRules.intro_bang (SOME 1)]), [([allI], [])])] |> snd
   177         |> ProofContext.note_thmss_i ""
   178           [(("termination", [ContextRules.intro_bang (SOME 0)]),
   179             [([Goal.norm_result termination], [])])] |> snd
   180         |> set_termination_rule termination
   181         |> Proof.theorem_i NONE (total_termination_afterqed defname data) [[(goal, [])]]
   182     end
   183 
   184 
   185 val add_fundef = gen_add_fundef Specification.read_specification
   186 val add_fundef_i = gen_add_fundef Specification.cert_specification
   187 
   188 
   189 
   190 (* congruence rules *)
   191 
   192 val cong_add = Thm.declaration_attribute (map_fundef_congs o Drule.add_rule o safe_mk_meta_eq);
   193 val cong_del = Thm.declaration_attribute (map_fundef_congs o Drule.del_rule o safe_mk_meta_eq);
   194 
   195 (* Datatype hook to declare datatype congs as "fundef_congs" *)
   196 
   197 
   198 fun add_case_cong n thy =
   199     Context.theory_map (map_fundef_congs (Drule.add_rule
   200                           (DatatypePackage.get_datatype thy n |> the
   201                            |> #case_cong
   202                            |> safe_mk_meta_eq)))
   203                        thy
   204 
   205 val case_cong_hook = fold add_case_cong
   206 
   207 val setup_case_cong_hook =
   208     DatatypeHooks.add case_cong_hook
   209     #> (fn thy => case_cong_hook (Symtab.keys (DatatypePackage.get_datatypes thy)) thy)
   210 
   211 (* setup *)
   212 
   213 val setup =
   214     FundefData.init
   215       #> FundefCongs.init
   216       #> TerminationRule.init
   217       #>  Attrib.add_attributes
   218             [("fundef_cong", Attrib.add_del_args cong_add cong_del, "declaration of congruence rule for function definitions")]
   219       #> setup_case_cong_hook
   220       #> FundefRelation.setup
   221 
   222 val get_congs = FundefCommon.get_fundef_congs o Context.Theory
   223 
   224 
   225 
   226 (* outer syntax *)
   227 
   228 local structure P = OuterParse and K = OuterKeyword in
   229 
   230 val functionP =
   231   OuterSyntax.command "function" "define general recursive functions" K.thy_goal
   232   (fundef_parser default_config
   233      >> (fn ((config, fixes), statements) =>
   234             Toplevel.local_theory_to_proof (target_of config) (add_fundef fixes statements config #> snd)
   235             #> Toplevel.print));
   236 
   237 val terminationP =
   238   OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
   239   (P.opt_target -- Scan.option P.name
   240     >> (fn (target, name) =>
   241            Toplevel.print o
   242            Toplevel.local_theory_to_proof target (setup_termination_proof name)));
   243 
   244 val _ = OuterSyntax.add_parsers [functionP];
   245 val _ = OuterSyntax.add_parsers [terminationP];
   246 val _ = OuterSyntax.add_keywords ["sequential", "otherwise"];
   247 
   248 end;
   249 
   250 
   251 end