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