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