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