src/HOL/Tools/function_package/fundef_package.ML
author krauss
Fri Apr 20 10:06:11 2007 +0200 (2007-04-20)
changeset 22733 0b14bb35be90
parent 22725 83099f0a9d8d
child 22846 fb79144af9a3
permissions -rw-r--r--
definition lookup via terms, not names. Methods "relation" and "lexicographic_order"
do not depend on "termination" setup.
     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                       -> 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                        -> 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 fun fundef_afterqed config fixes spec defname cont sort_cont [[proof]] lthy =
    72     let
    73       val FundefResult {fs, R, psimps, trsimps, subset_pinducts, simple_pinducts, termination, domintros, cases, ...} = 
    74           cont (Goal.close_result proof)
    75 
    76       val qualify = NameSpace.qualified defname
    77       val addsmps = add_simps fixes spec sort_cont
    78 
    79       val (((psimps', pinducts'), (_, [termination'])), lthy) =
    80           lthy
    81             |> addsmps "psimps" [] psimps
    82             ||> fold_option (snd oo addsmps "simps" []) trsimps
    83             ||>> note_theorem ((qualify "pinduct",
    84                                 [Attrib.internal (K (InductAttrib.induct_set ""))]), simple_pinducts)
    85             ||>> note_theorem ((qualify "termination", []), [termination])
    86             ||> (snd o note_theorem ((qualify "cases", []), [cases]))
    87             ||> fold_option (snd oo curry note_theorem (qualify "domintros", [])) domintros
    88 
    89       val cdata = FundefCtxData { add_simps=addsmps, psimps=psimps',
    90                                   pinducts=snd pinducts', termination=termination', fs=fs, R=R, defname=defname }
    91       val cdata' = cdata |> morph_fundef_data (LocalTheory.target_morphism lthy);  (* FIXME !? *)
    92     in
    93       lthy 
    94         |> LocalTheory.declaration (fn phi => add_fundef_data (morph_fundef_data phi cdata)) (* save in target *)
    95         |> Context.proof_map (add_fundef_data cdata') (* also save in local context *)
    96     end (* FIXME: Add cases for induct and cases thm *)
    97 
    98 
    99 
   100 fun prep_with_flags prep fixspec eqnss_flags global_flag lthy =
   101     let
   102       val flags = map (fn x => global_flag orelse (snd (snd x))) eqnss_flags
   103       val eqns = map (apsnd (single o fst)) eqnss_flags
   104 
   105       val ((fixes, _), ctxt') = prep fixspec [] lthy
   106 
   107       fun prep_eqn e = the_single (snd (fst (prep [] [e] ctxt')))
   108                          |> apsnd the_single
   109 
   110       val spec = map prep_eqn eqns
   111                      |> map (apsnd (fn t => fold_rev (mk_forall o Free) (frees_in_term ctxt' t) t)) (* Add quantifiers *)
   112                      |> burrow_snd (fn ts => FundefSplit.split_some_equations ctxt' (flags ~~ ts))
   113     in
   114       ((fixes, spec), ctxt')
   115     end
   116 
   117 fun gen_add_fundef prep_spec fixspec eqnss_flags config lthy =
   118     let
   119       val FundefConfig {sequential, default, tailrec, ...} = config
   120 
   121       val ((fixes, spec), ctxt') = prep_with_flags prep_spec fixspec eqnss_flags sequential lthy
   122 
   123       val defname = mk_defname fixes
   124 
   125       val t_eqns = spec |> map snd |> flat (* flatten external structure *)
   126 
   127       val ((goalstate, cont, sort_cont), lthy) =
   128           FundefMutual.prepare_fundef_mutual config defname fixes t_eqns default lthy
   129 
   130       val afterqed = fundef_afterqed config fixes spec defname cont sort_cont
   131     in
   132       lthy
   133         |> Proof.theorem_i NONE afterqed [[(Logic.unprotect (concl_of goalstate), [])]]
   134         |> Proof.refine (Method.primitive_text (fn _ => goalstate)) |> Seq.hd
   135     end
   136 
   137 
   138 fun total_termination_afterqed data [[totality]] lthy =
   139     let
   140       val FundefCtxData { add_simps, psimps, pinducts, defname, ... } = data
   141 
   142       val totality = Goal.close_result totality
   143 
   144       val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
   145 
   146       val tsimps = map remove_domain_condition psimps
   147       val tinduct = map remove_domain_condition pinducts
   148 
   149         (* FIXME: How to generate code from (possibly) local contexts*)
   150       val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
   151       val allatts = if has_guards then [] else [Attrib.internal (K (RecfunCodegen.add NONE))]
   152 
   153       val qualify = NameSpace.qualified defname;
   154     in
   155       lthy
   156         |> add_simps "simps" allatts tsimps |> snd
   157         |> note_theorem ((qualify "induct", []), tinduct) |> snd
   158     end
   159 
   160 
   161 fun setup_termination_proof term_opt lthy =
   162     let
   163       val data = the (case term_opt of
   164                         SOME t => import_fundef_data (ProofContext.read_term lthy t) (Context.Proof lthy)
   165                       | NONE => import_last_fundef (Context.Proof lthy))
   166           handle Option.Option => raise ERROR ("Not a function: " ^ quote (the_default "" term_opt))
   167 
   168         val FundefCtxData {termination, R, ...} = data
   169         val domT = domain_type (fastype_of R)
   170         val goal = HOLogic.mk_Trueprop (HOLogic.mk_all ("x", domT, mk_acc domT R $ Free ("x", domT)))
   171     in
   172       lthy
   173         |> ProofContext.note_thmss_i "" [(("", [ContextRules.rule_del]), [([allI], [])])] |> snd
   174         |> ProofContext.note_thmss_i "" [(("", [ContextRules.intro_bang (SOME 1)]), [([allI], [])])] |> snd
   175         |> ProofContext.note_thmss_i ""
   176           [(("termination", [ContextRules.intro_bang (SOME 0)]),
   177             [([Goal.norm_result termination], [])])] |> snd
   178         |> Proof.theorem_i NONE (total_termination_afterqed data) [[(goal, [])]]
   179     end
   180 
   181 
   182 val add_fundef = gen_add_fundef Specification.read_specification
   183 val add_fundef_i = gen_add_fundef Specification.cert_specification
   184 
   185 
   186 
   187 (* congruence rules *)
   188 
   189 val cong_add = Thm.declaration_attribute (map_fundef_congs o Drule.add_rule o safe_mk_meta_eq);
   190 val cong_del = Thm.declaration_attribute (map_fundef_congs o Drule.del_rule o safe_mk_meta_eq);
   191 
   192 (* Datatype hook to declare datatype congs as "fundef_congs" *)
   193 
   194 
   195 fun add_case_cong n thy =
   196     Context.theory_map (map_fundef_congs (Drule.add_rule
   197                           (DatatypePackage.get_datatype thy n |> the
   198                            |> #case_cong
   199                            |> safe_mk_meta_eq)))
   200                        thy
   201 
   202 val case_cong_hook = fold add_case_cong
   203 
   204 val setup_case_cong_hook =
   205     DatatypeHooks.add case_cong_hook
   206     #> (fn thy => case_cong_hook (Symtab.keys (DatatypePackage.get_datatypes thy)) thy)
   207 
   208 (* setup *)
   209 
   210 val setup =
   211     FundefData.init
   212       #> FundefCongs.init
   213       #> TerminationRule.init
   214       #>  Attrib.add_attributes
   215             [("fundef_cong", Attrib.add_del_args cong_add cong_del, "declaration of congruence rule for function definitions")]
   216       #> setup_case_cong_hook
   217       #> FundefRelation.setup
   218 
   219 val get_congs = FundefCommon.get_fundef_congs o Context.Theory
   220 
   221 
   222 
   223 (* outer syntax *)
   224 
   225 local structure P = OuterParse and K = OuterKeyword in
   226 
   227 val functionP =
   228   OuterSyntax.command "function" "define general recursive functions" K.thy_goal
   229   (fundef_parser default_config
   230      >> (fn ((config, fixes), statements) =>
   231             Toplevel.local_theory_to_proof (target_of config) (add_fundef fixes statements config)
   232             #> Toplevel.print));
   233 
   234 val terminationP =
   235   OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
   236   (P.opt_target -- Scan.option P.term
   237     >> (fn (target, name) =>
   238            Toplevel.print o
   239            Toplevel.local_theory_to_proof target (setup_termination_proof name)));
   240 
   241 val _ = OuterSyntax.add_parsers [functionP];
   242 val _ = OuterSyntax.add_parsers [terminationP];
   243 val _ = OuterSyntax.add_keywords ["sequential", "otherwise"];
   244 
   245 end;
   246 
   247 
   248 end