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