src/HOL/Tools/function_package/fundef_package.ML
author wenzelm
Wed Feb 27 21:46:13 2008 +0100 (2008-02-27)
changeset 26171 5426a823455c
parent 26129 14f6dbb195c4
child 26529 03ad378ed5f0
permissions -rw-r--r--
more precise handling of "group" for termination;
     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 
    14                       -> FundefCommon.fundef_config
    15                       -> bool list
    16                       -> local_theory
    17                       -> Proof.state
    18 
    19     val add_fundef_i:  (string * typ option * mixfix) list
    20                        -> ((bstring * Attrib.src list) * term) list
    21                        -> FundefCommon.fundef_config
    22                        -> bool list
    23                        -> local_theory
    24                        -> Proof.state
    25 
    26     val setup_termination_proof : string option -> local_theory -> Proof.state
    27 
    28     val setup : theory -> theory
    29     val get_congs : theory -> thm list
    30 end
    31 
    32 
    33 structure FundefPackage : FUNDEF_PACKAGE =
    34 struct
    35 
    36 open FundefLib
    37 open FundefCommon
    38 
    39 val note_theorem = LocalTheory.note Thm.theoremK
    40 
    41 fun mk_defname fixes = fixes |> map (fst o fst) |> space_implode "_" 
    42 
    43 fun add_simps fnames post sort label moreatts simps lthy =
    44     let
    45       val atts = Attrib.internal (K Simplifier.simp_add) :: moreatts
    46       val spec = post simps
    47                    |> map (apfst (apsnd (append atts)))
    48 
    49       val (saved_spec_simps, lthy) =
    50         fold_map note_theorem spec lthy
    51 
    52       val saved_simps = flat (map snd saved_spec_simps)
    53       val simps_by_f = sort saved_simps
    54 
    55       fun add_for_f fname simps =
    56         note_theorem ((NameSpace.qualified fname label, []), simps) #> snd
    57     in
    58       (saved_simps,
    59        fold2 add_for_f fnames simps_by_f lthy)
    60     end
    61 
    62 fun fundef_afterqed config fixes post defname cont sort_cont cnames [[proof]] lthy =
    63     let
    64       val FundefResult {fs, R, psimps, trsimps, subset_pinducts, simple_pinducts, termination, domintros, cases, ...} = 
    65           cont (Goal.close_result proof)
    66 
    67       val fnames = map (fst o fst) fixes
    68       val qualify = NameSpace.qualified defname
    69       val addsmps = add_simps fnames post sort_cont
    70 
    71       val (((psimps', pinducts'), (_, [termination'])), lthy) =
    72           lthy
    73             |> addsmps "psimps" [] psimps
    74             ||> fold_option (snd oo addsmps "simps" []) trsimps
    75             ||>> note_theorem ((qualify "pinduct",
    76                    [Attrib.internal (K (RuleCases.case_names cnames)),
    77                     Attrib.internal (K (RuleCases.consumes 1)),
    78                     Attrib.internal (K (Induct.induct_pred ""))]), simple_pinducts)
    79             ||>> note_theorem ((qualify "termination", []), [termination])
    80             ||> (snd o note_theorem ((qualify "cases", 
    81                    [Attrib.internal (K (RuleCases.case_names cnames))]), [cases]))
    82             ||> fold_option (snd oo curry note_theorem (qualify "domintros", [])) domintros
    83 
    84       val cdata = FundefCtxData { add_simps=addsmps, case_names=cnames, psimps=psimps',
    85                                   pinducts=snd pinducts', termination=termination', fs=fs, R=R, defname=defname }
    86       val _ = Specification.print_consts lthy (K false) (map fst fixes)
    87     in
    88       lthy 
    89         |> LocalTheory.declaration (add_fundef_data o morph_fundef_data cdata)
    90     end
    91 
    92 
    93 fun gen_add_fundef set_group prep fixspec eqnss config flags lthy =
    94     let
    95       val ((fixes, spec), ctxt') = prep fixspec (map (fn (n_a, eq) => [(n_a, [eq])]) eqnss) lthy
    96       val (eqs, post, sort_cont, cnames) = FundefCommon.get_preproc lthy config flags ctxt' fixes spec
    97 
    98       val defname = mk_defname fixes
    99 
   100       val ((goalstate, cont), lthy) =
   101           FundefMutual.prepare_fundef_mutual config defname fixes eqs lthy
   102 
   103       val afterqed = fundef_afterqed config fixes post defname cont sort_cont cnames
   104     in
   105       lthy
   106         |> set_group ? LocalTheory.set_group (serial_string ())
   107         |> Proof.theorem_i NONE afterqed [[(Logic.unprotect (concl_of goalstate), [])]]
   108         |> Proof.refine (Method.primitive_text (fn _ => goalstate)) |> Seq.hd
   109     end
   110 
   111 fun total_termination_afterqed data [[totality]] lthy =
   112     let
   113       val FundefCtxData { add_simps, case_names, psimps, pinducts, defname, ... } = data
   114 
   115       val totality = Goal.close_result totality
   116 
   117       val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
   118 
   119       val tsimps = map remove_domain_condition psimps
   120       val tinduct = map remove_domain_condition pinducts
   121 
   122       val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
   123       val allatts = if has_guards then [] else [Attrib.internal (K RecfunCodegen.add_default)]
   124 
   125       val qualify = NameSpace.qualified defname;
   126     in
   127       lthy
   128         |> add_simps "simps" allatts tsimps |> snd
   129         |> note_theorem ((qualify "induct", [Attrib.internal (K (RuleCases.case_names case_names))]), tinduct) |> snd
   130     end
   131 
   132 
   133 fun setup_termination_proof term_opt lthy =
   134     let
   135       val data = the (case term_opt of
   136                         SOME t => import_fundef_data (Syntax.read_term lthy t) (Context.Proof lthy)
   137                       | NONE => import_last_fundef (Context.Proof lthy))
   138           handle Option.Option => raise ERROR ("Not a function: " ^ quote (the_default "" term_opt))
   139 
   140         val FundefCtxData {termination, R, ...} = data
   141         val domT = domain_type (fastype_of R)
   142         val goal = HOLogic.mk_Trueprop (HOLogic.mk_all ("x", domT, mk_acc domT R $ Free ("x", domT)))
   143     in
   144       lthy
   145         |> ProofContext.note_thmss_i "" [(("", [ContextRules.rule_del]), [([allI], [])])] |> snd
   146         |> ProofContext.note_thmss_i "" [(("", [ContextRules.intro_bang (SOME 1)]), [([allI], [])])] |> snd
   147         |> ProofContext.note_thmss_i ""
   148           [(("termination", [ContextRules.intro_bang (SOME 0)]),
   149             [([Goal.norm_result termination], [])])] |> snd
   150         |> Proof.theorem_i NONE (total_termination_afterqed data) [[(goal, [])]]
   151     end
   152 
   153 fun termination_cmd term_opt lthy =
   154   lthy
   155   |> LocalTheory.set_group (serial_string ())
   156   |> setup_termination_proof term_opt;
   157 
   158 val add_fundef = gen_add_fundef true Specification.read_specification
   159 val add_fundef_i = gen_add_fundef false Specification.check_specification
   160 
   161 
   162 (* Datatype hook to declare datatype congs as "fundef_congs" *)
   163 
   164 
   165 fun add_case_cong n thy =
   166     Context.theory_map (FundefCtxTree.map_fundef_congs (Thm.add_thm
   167                           (DatatypePackage.get_datatype thy n |> the
   168                            |> #case_cong
   169                            |> safe_mk_meta_eq)))
   170                        thy
   171 
   172 val case_cong = fold add_case_cong
   173 
   174 val setup_case_cong = DatatypePackage.interpretation case_cong
   175 
   176 
   177 
   178 (* ad-hoc method to convert elimination-style goals to existential statements *)
   179 
   180 fun insert_int_goal thy subg st =
   181     let
   182       val goal = hd (prems_of st)
   183       val (ps, imp) = dest_all_all goal
   184       val cps = map (cterm_of thy) ps
   185 
   186       val imp_subg = fold (fn p => fn t => betapply (t,p)) ps subg
   187       val new_subg = implies $ imp_subg $ imp
   188                       |> fold_rev mk_forall ps
   189                       |> cterm_of thy 
   190                       |> assume 
   191 
   192       val sg2 = imp_subg
   193                  |> fold_rev mk_forall ps
   194                  |> cterm_of thy 
   195                  |> assume
   196 
   197       val t' = new_subg
   198                 |> fold forall_elim cps
   199                 |> Thm.elim_implies (fold forall_elim cps sg2)
   200                 |> fold_rev forall_intr cps
   201 
   202       val st' = implies_elim st t'
   203                  |> implies_intr (cprop_of sg2)
   204                  |> implies_intr (cprop_of new_subg)
   205     in
   206       Seq.single st'
   207     end
   208 
   209 fun mk_cases_statement thy t =
   210     let
   211       fun mk_clause t = 
   212           let 
   213             val (qs, imp) = dest_all_all t
   214           in 
   215             Logic.strip_imp_prems imp
   216              |> map (ObjectLogic.atomize_term thy)
   217              |> foldr1 HOLogic.mk_conj
   218              |> fold_rev (fn Free (v,T) => fn t => HOLogic.mk_exists (v,T,t)) qs
   219           end
   220 
   221       val (ps, imp) = dest_all_all t
   222     in 
   223       Logic.strip_imp_prems imp
   224        |> map mk_clause
   225        |> foldr1 HOLogic.mk_disj
   226        |> HOLogic.mk_Trueprop
   227        |> fold_rev lambda ps
   228     end
   229 
   230 fun elim_to_cases1 ctxt st =
   231     let
   232       val thy = theory_of_thm st
   233       val [subg] = prems_of st
   234       val cex = mk_cases_statement thy subg
   235     in
   236       (insert_int_goal thy cex
   237        THEN REPEAT_ALL_NEW (Tactic.ematch_tac [disjE, exE, conjE]) 1
   238        THEN REPEAT (Goal.assume_rule_tac ctxt 1)
   239     (*   THEN REPEAT (etac thin_rl 1)*)) st
   240     end
   241 
   242 fun elim_to_cases_tac ctxt = SELECT_GOAL (elim_to_cases1 ctxt)
   243 
   244 val elim_to_cases_setup = Method.add_methods
   245   [("elim_to_cases", Method.ctxt_args (Method.SIMPLE_METHOD' o elim_to_cases_tac),
   246     "convert elimination-style goal to a disjunction of existentials")]
   247 
   248 (* setup *)
   249 
   250 val setup =
   251   Attrib.add_attributes
   252     [("fundef_cong", Attrib.add_del_args FundefCtxTree.cong_add FundefCtxTree.cong_del,
   253       "declaration of congruence rule for function definitions")]
   254   #> setup_case_cong
   255   #> FundefRelation.setup
   256   #> elim_to_cases_setup
   257 
   258 val get_congs = FundefCtxTree.get_fundef_congs o Context.Theory
   259 
   260 
   261 (* outer syntax *)
   262 
   263 local structure P = OuterParse and K = OuterKeyword in
   264 
   265 val _ = OuterSyntax.keywords ["otherwise"];
   266 
   267 val _ =
   268   OuterSyntax.command "function" "define general recursive functions" K.thy_goal
   269   (fundef_parser default_config
   270      >> (fn ((config, fixes), (flags, statements)) =>
   271             Toplevel.local_theory_to_proof (target_of config) (add_fundef fixes statements config flags)
   272             #> Toplevel.print));
   273 
   274 val _ =
   275   OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
   276   (P.opt_target -- Scan.option P.term
   277     >> (fn (target, name) =>
   278            Toplevel.print o
   279            Toplevel.local_theory_to_proof target (termination_cmd name)));
   280 
   281 end;
   282 
   283 
   284 end