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