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