src/HOL/Tools/function_package/fundef_package.ML
author krauss
Tue Apr 08 18:30:40 2008 +0200 (2008-04-08)
changeset 26580 c3e597a476fd
parent 26529 03ad378ed5f0
child 26594 1c676ae50311
permissions -rw-r--r--
Generic conversion and tactic "atomize_elim" to convert elimination rules
to the object logic
     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 extra_qualify 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                    |> map (apfst (apfst extra_qualify))
    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 cnames [[proof]] lthy =
    64     let
    65       val FundefResult {fs, R, psimps, trsimps,  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 (NameSpace.qualified "partial") "psimps" [] psimps
    75             ||> fold_option (snd oo addsmps I "simps" []) trsimps
    76             ||>> note_theorem ((qualify "pinduct",
    77                    [Attrib.internal (K (RuleCases.case_names cnames)),
    78                     Attrib.internal (K (RuleCases.consumes 1)),
    79                     Attrib.internal (K (Induct.induct_pred ""))]), simple_pinducts)
    80             ||>> note_theorem ((qualify "termination", []), [termination])
    81             ||> (snd o note_theorem ((qualify "cases", 
    82                    [Attrib.internal (K (RuleCases.case_names cnames))]), [cases]))
    83             ||> fold_option (snd oo curry note_theorem (qualify "domintros", [])) domintros
    84 
    85       val cdata = FundefCtxData { add_simps=addsmps, case_names=cnames, psimps=psimps',
    86                                   pinducts=snd pinducts', termination=termination', fs=fs, R=R, defname=defname }
    87       val _ = Specification.print_consts lthy (K false) (map fst fixes)
    88     in
    89       lthy 
    90         |> LocalTheory.declaration (add_fundef_data o morph_fundef_data cdata)
    91     end
    92 
    93 
    94 fun gen_add_fundef set_group prep fixspec eqnss config flags lthy =
    95     let
    96       val ((fixes, spec), ctxt') = prep fixspec (map (fn (n_a, eq) => [(n_a, [eq])]) eqnss) lthy
    97       val (eqs, post, sort_cont, cnames) = FundefCommon.get_preproc lthy config flags ctxt' fixes spec
    98 
    99       val defname = mk_defname fixes
   100 
   101       val ((goalstate, cont), lthy) =
   102           FundefMutual.prepare_fundef_mutual config defname fixes eqs lthy
   103 
   104       val afterqed = fundef_afterqed config fixes post defname cont sort_cont cnames
   105     in
   106       lthy
   107         |> set_group ? LocalTheory.set_group (serial_string ())
   108         |> Proof.theorem_i NONE afterqed [[(Logic.unprotect (concl_of goalstate), [])]]
   109         |> Proof.refine (Method.primitive_text (fn _ => goalstate)) |> Seq.hd
   110     end
   111 
   112 fun total_termination_afterqed data [[totality]] lthy =
   113     let
   114       val FundefCtxData { add_simps, case_names, psimps, pinducts, defname, ... } = data
   115 
   116       val totality = Goal.close_result totality
   117 
   118       val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
   119 
   120       val tsimps = map remove_domain_condition psimps
   121       val tinduct = map remove_domain_condition pinducts
   122 
   123       val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
   124       val allatts = if has_guards then [] else [Attrib.internal (K RecfunCodegen.add_default)]
   125 
   126       val qualify = NameSpace.qualified defname;
   127     in
   128       lthy
   129         |> add_simps I "simps" allatts tsimps |> snd
   130         |> note_theorem ((qualify "induct", [Attrib.internal (K (RuleCases.case_names case_names))]), tinduct) |> snd
   131     end
   132 
   133 
   134 fun setup_termination_proof term_opt lthy =
   135     let
   136       val data = the (case term_opt of
   137                         SOME t => import_fundef_data (Syntax.read_term lthy t) (Context.Proof lthy)
   138                       | NONE => import_last_fundef (Context.Proof lthy))
   139           handle Option.Option => raise ERROR ("Not a function: " ^ quote (the_default "" term_opt))
   140 
   141         val FundefCtxData {termination, R, ...} = data
   142         val domT = domain_type (fastype_of R)
   143         val goal = HOLogic.mk_Trueprop (HOLogic.mk_all ("x", domT, mk_acc domT R $ Free ("x", domT)))
   144     in
   145       lthy
   146         |> ProofContext.note_thmss_i "" [(("", [ContextRules.rule_del]), [([allI], [])])] |> snd
   147         |> ProofContext.note_thmss_i "" [(("", [ContextRules.intro_bang (SOME 1)]), [([allI], [])])] |> snd
   148         |> ProofContext.note_thmss_i ""
   149           [(("termination", [ContextRules.intro_bang (SOME 0)]),
   150             [([Goal.norm_result termination], [])])] |> snd
   151         |> Proof.theorem_i NONE (total_termination_afterqed data) [[(goal, [])]]
   152     end
   153 
   154 fun termination_cmd term_opt lthy =
   155   lthy
   156   |> LocalTheory.set_group (serial_string ())
   157   |> setup_termination_proof term_opt;
   158 
   159 val add_fundef = gen_add_fundef true Specification.read_specification
   160 val add_fundef_i = gen_add_fundef false Specification.check_specification
   161 
   162 
   163 (* Datatype hook to declare datatype congs as "fundef_congs" *)
   164 
   165 
   166 fun add_case_cong n thy =
   167     Context.theory_map (FundefCtxTree.map_fundef_congs (Thm.add_thm
   168                           (DatatypePackage.get_datatype thy n |> the
   169                            |> #case_cong
   170                            |> safe_mk_meta_eq)))
   171                        thy
   172 
   173 val case_cong = fold add_case_cong
   174 
   175 val setup_case_cong = DatatypePackage.interpretation case_cong
   176 
   177 (* setup *)
   178 
   179 val setup =
   180   Attrib.add_attributes
   181     [("fundef_cong", Attrib.add_del_args FundefCtxTree.cong_add FundefCtxTree.cong_del,
   182       "declaration of congruence rule for function definitions")]
   183   #> setup_case_cong
   184   #> FundefRelation.setup
   185 
   186 val get_congs = FundefCtxTree.get_fundef_congs o Context.Theory
   187 
   188 
   189 (* outer syntax *)
   190 
   191 local structure P = OuterParse and K = OuterKeyword in
   192 
   193 val _ = OuterSyntax.keywords ["otherwise"];
   194 
   195 val _ =
   196   OuterSyntax.command "function" "define general recursive functions" K.thy_goal
   197   (fundef_parser default_config
   198      >> (fn ((config, fixes), (flags, statements)) =>
   199             Toplevel.local_theory_to_proof (target_of config) (add_fundef fixes statements config flags)
   200             #> Toplevel.print));
   201 
   202 val _ =
   203   OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
   204   (P.opt_target -- Scan.option P.term
   205     >> (fn (target, name) =>
   206            Toplevel.print o
   207            Toplevel.local_theory_to_proof target (termination_cmd name)));
   208 
   209 end;
   210 
   211 
   212 end