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