src/HOL/Tools/function_package/fundef_package.ML
author krauss
Thu Apr 03 16:34:52 2008 +0200 (2008-04-03)
changeset 26529 03ad378ed5f0
parent 26171 5426a823455c
child 26580 c3e597a476fd
permissions -rw-r--r--
Function package no longer overwrites theorems.
Some tuning.
krauss@19564
     1
(*  Title:      HOL/Tools/function_package/fundef_package.ML
krauss@19564
     2
    ID:         $Id$
krauss@19564
     3
    Author:     Alexander Krauss, TU Muenchen
krauss@19564
     4
wenzelm@20363
     5
A package for general recursive function definitions.
krauss@19564
     6
Isar commands.
krauss@19564
     7
krauss@19564
     8
*)
krauss@19564
     9
wenzelm@20363
    10
signature FUNDEF_PACKAGE =
krauss@19564
    11
sig
wenzelm@20877
    12
    val add_fundef :  (string * string option * mixfix) list
krauss@23203
    13
                      -> ((bstring * Attrib.src list) * string) list 
wenzelm@20877
    14
                      -> FundefCommon.fundef_config
krauss@23203
    15
                      -> bool list
wenzelm@20877
    16
                      -> local_theory
krauss@22733
    17
                      -> Proof.state
krauss@20523
    18
wenzelm@20877
    19
    val add_fundef_i:  (string * typ option * mixfix) list
krauss@23203
    20
                       -> ((bstring * Attrib.src list) * term) list
krauss@22170
    21
                       -> FundefCommon.fundef_config
krauss@23203
    22
                       -> bool list
wenzelm@20877
    23
                       -> local_theory
krauss@22733
    24
                       -> Proof.state
krauss@21211
    25
krauss@21211
    26
    val setup_termination_proof : string option -> local_theory -> Proof.state
krauss@19564
    27
krauss@19564
    28
    val setup : theory -> theory
krauss@19770
    29
    val get_congs : theory -> thm list
krauss@19564
    30
end
krauss@19564
    31
krauss@19564
    32
krauss@23203
    33
structure FundefPackage : FUNDEF_PACKAGE =
krauss@19564
    34
struct
krauss@19564
    35
krauss@21051
    36
open FundefLib
krauss@19564
    37
open FundefCommon
krauss@19564
    38
wenzelm@21435
    39
val note_theorem = LocalTheory.note Thm.theoremK
wenzelm@21435
    40
krauss@22166
    41
fun mk_defname fixes = fixes |> map (fst o fst) |> space_implode "_" 
krauss@22166
    42
krauss@26529
    43
fun add_simps fnames post sort extra_qualify label moreatts simps lthy =
krauss@19564
    44
    let
krauss@23819
    45
      val atts = Attrib.internal (K Simplifier.simp_add) :: moreatts
krauss@23819
    46
      val spec = post simps
krauss@23819
    47
                   |> map (apfst (apsnd (append atts)))
krauss@26529
    48
                   |> map (apfst (apfst extra_qualify))
krauss@21255
    49
krauss@22166
    50
      val (saved_spec_simps, lthy) =
krauss@23819
    51
        fold_map note_theorem spec lthy
krauss@23819
    52
krauss@22498
    53
      val saved_simps = flat (map snd saved_spec_simps)
krauss@22166
    54
      val simps_by_f = sort saved_simps
krauss@19564
    55
krauss@22166
    56
      fun add_for_f fname simps =
krauss@23819
    57
        note_theorem ((NameSpace.qualified fname label, []), simps) #> snd
krauss@19564
    58
    in
krauss@22166
    59
      (saved_simps,
krauss@22166
    60
       fold2 add_for_f fnames simps_by_f lthy)
krauss@19564
    61
    end
krauss@19564
    62
krauss@25222
    63
fun fundef_afterqed config fixes post defname cont sort_cont cnames [[proof]] lthy =
krauss@20523
    64
    let
krauss@26529
    65
      val FundefResult {fs, R, psimps, trsimps,  simple_pinducts, termination, domintros, cases, ...} = 
krauss@22166
    66
          cont (Goal.close_result proof)
krauss@22166
    67
krauss@23819
    68
      val fnames = map (fst o fst) fixes
wenzelm@21391
    69
      val qualify = NameSpace.qualified defname
krauss@23819
    70
      val addsmps = add_simps fnames post sort_cont
wenzelm@21602
    71
wenzelm@21602
    72
      val (((psimps', pinducts'), (_, [termination'])), lthy) =
krauss@21255
    73
          lthy
krauss@26529
    74
            |> addsmps (NameSpace.qualified "partial") "psimps" [] psimps
krauss@26529
    75
            ||> fold_option (snd oo addsmps I "simps" []) trsimps
krauss@22166
    76
            ||>> note_theorem ((qualify "pinduct",
krauss@25222
    77
                   [Attrib.internal (K (RuleCases.case_names cnames)),
krauss@25222
    78
                    Attrib.internal (K (RuleCases.consumes 1)),
krauss@25222
    79
                    Attrib.internal (K (Induct.induct_pred ""))]), simple_pinducts)
krauss@22166
    80
            ||>> note_theorem ((qualify "termination", []), [termination])
krauss@25222
    81
            ||> (snd o note_theorem ((qualify "cases", 
krauss@25222
    82
                   [Attrib.internal (K (RuleCases.case_names cnames))]), [cases]))
krauss@22166
    83
            ||> fold_option (snd oo curry note_theorem (qualify "domintros", [])) domintros
krauss@21255
    84
krauss@25222
    85
      val cdata = FundefCtxData { add_simps=addsmps, case_names=cnames, psimps=psimps',
krauss@22733
    86
                                  pinducts=snd pinducts', termination=termination', fs=fs, R=R, defname=defname }
krauss@25201
    87
      val _ = Specification.print_consts lthy (K false) (map fst fixes)
krauss@20523
    88
    in
krauss@22623
    89
      lthy 
krauss@25201
    90
        |> LocalTheory.declaration (add_fundef_data o morph_fundef_data cdata)
krauss@25222
    91
    end
krauss@20523
    92
krauss@20523
    93
wenzelm@26129
    94
fun gen_add_fundef set_group prep fixspec eqnss config flags lthy =
krauss@20523
    95
    let
krauss@25088
    96
      val ((fixes, spec), ctxt') = prep fixspec (map (fn (n_a, eq) => [(n_a, [eq])]) eqnss) lthy
krauss@25222
    97
      val (eqs, post, sort_cont, cnames) = FundefCommon.get_preproc lthy config flags ctxt' fixes spec
krauss@22166
    98
krauss@22166
    99
      val defname = mk_defname fixes
krauss@22166
   100
krauss@23819
   101
      val ((goalstate, cont), lthy) =
krauss@23203
   102
          FundefMutual.prepare_fundef_mutual config defname fixes eqs lthy
krauss@20523
   103
krauss@25222
   104
      val afterqed = fundef_afterqed config fixes post defname cont sort_cont cnames
krauss@20523
   105
    in
krauss@22733
   106
      lthy
wenzelm@26129
   107
        |> set_group ? LocalTheory.set_group (serial_string ())
krauss@22733
   108
        |> Proof.theorem_i NONE afterqed [[(Logic.unprotect (concl_of goalstate), [])]]
krauss@22733
   109
        |> Proof.refine (Method.primitive_text (fn _ => goalstate)) |> Seq.hd
krauss@20523
   110
    end
krauss@20523
   111
krauss@22733
   112
fun total_termination_afterqed data [[totality]] lthy =
krauss@20523
   113
    let
krauss@25222
   114
      val FundefCtxData { add_simps, case_names, psimps, pinducts, defname, ... } = data
krauss@21255
   115
krauss@22166
   116
      val totality = Goal.close_result totality
krauss@19564
   117
krauss@21255
   118
      val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
krauss@19564
   119
krauss@22166
   120
      val tsimps = map remove_domain_condition psimps
krauss@22166
   121
      val tinduct = map remove_domain_condition pinducts
krauss@19770
   122
krauss@21511
   123
      val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
haftmann@24624
   124
      val allatts = if has_guards then [] else [Attrib.internal (K RecfunCodegen.add_default)]
wenzelm@21602
   125
krauss@21511
   126
      val qualify = NameSpace.qualified defname;
krauss@19564
   127
    in
krauss@21511
   128
      lthy
krauss@26529
   129
        |> add_simps I "simps" allatts tsimps |> snd
krauss@25222
   130
        |> note_theorem ((qualify "induct", [Attrib.internal (K (RuleCases.case_names case_names))]), tinduct) |> snd
wenzelm@20363
   131
    end
krauss@19564
   132
krauss@19564
   133
krauss@22733
   134
fun setup_termination_proof term_opt lthy =
krauss@20523
   135
    let
krauss@22733
   136
      val data = the (case term_opt of
wenzelm@24508
   137
                        SOME t => import_fundef_data (Syntax.read_term lthy t) (Context.Proof lthy)
krauss@22733
   138
                      | NONE => import_last_fundef (Context.Proof lthy))
krauss@22733
   139
          handle Option.Option => raise ERROR ("Not a function: " ^ quote (the_default "" term_opt))
krauss@20523
   140
krauss@22166
   141
        val FundefCtxData {termination, R, ...} = data
krauss@22325
   142
        val domT = domain_type (fastype_of R)
krauss@22325
   143
        val goal = HOLogic.mk_Trueprop (HOLogic.mk_all ("x", domT, mk_acc domT R $ Free ("x", domT)))
krauss@20523
   144
    in
wenzelm@20877
   145
      lthy
krauss@22325
   146
        |> ProofContext.note_thmss_i "" [(("", [ContextRules.rule_del]), [([allI], [])])] |> snd
krauss@22325
   147
        |> ProofContext.note_thmss_i "" [(("", [ContextRules.intro_bang (SOME 1)]), [([allI], [])])] |> snd
wenzelm@21602
   148
        |> ProofContext.note_thmss_i ""
krauss@22325
   149
          [(("termination", [ContextRules.intro_bang (SOME 0)]),
wenzelm@21602
   150
            [([Goal.norm_result termination], [])])] |> snd
krauss@22733
   151
        |> Proof.theorem_i NONE (total_termination_afterqed data) [[(goal, [])]]
krauss@20523
   152
    end
krauss@20523
   153
wenzelm@26171
   154
fun termination_cmd term_opt lthy =
wenzelm@26171
   155
  lthy
wenzelm@26171
   156
  |> LocalTheory.set_group (serial_string ())
wenzelm@26171
   157
  |> setup_termination_proof term_opt;
krauss@20523
   158
wenzelm@26129
   159
val add_fundef = gen_add_fundef true Specification.read_specification
wenzelm@26129
   160
val add_fundef_i = gen_add_fundef false Specification.check_specification
krauss@19611
   161
krauss@19564
   162
krauss@21235
   163
(* Datatype hook to declare datatype congs as "fundef_congs" *)
krauss@21235
   164
krauss@21235
   165
wenzelm@21602
   166
fun add_case_cong n thy =
krauss@24168
   167
    Context.theory_map (FundefCtxTree.map_fundef_congs (Thm.add_thm
krauss@21235
   168
                          (DatatypePackage.get_datatype thy n |> the
krauss@21235
   169
                           |> #case_cong
wenzelm@21602
   170
                           |> safe_mk_meta_eq)))
krauss@21235
   171
                       thy
krauss@21235
   172
haftmann@24626
   173
val case_cong = fold add_case_cong
krauss@21235
   174
wenzelm@24711
   175
val setup_case_cong = DatatypePackage.interpretation case_cong
haftmann@24626
   176
krauss@19564
   177
krauss@23819
   178
krauss@23473
   179
(* ad-hoc method to convert elimination-style goals to existential statements *)
krauss@23473
   180
krauss@23473
   181
fun insert_int_goal thy subg st =
krauss@23473
   182
    let
krauss@23473
   183
      val goal = hd (prems_of st)
krauss@23473
   184
      val (ps, imp) = dest_all_all goal
krauss@23473
   185
      val cps = map (cterm_of thy) ps
krauss@23473
   186
krauss@23473
   187
      val imp_subg = fold (fn p => fn t => betapply (t,p)) ps subg
krauss@23473
   188
      val new_subg = implies $ imp_subg $ imp
krauss@23473
   189
                      |> fold_rev mk_forall ps
krauss@23473
   190
                      |> cterm_of thy 
krauss@23473
   191
                      |> assume 
krauss@23473
   192
krauss@23473
   193
      val sg2 = imp_subg
krauss@23473
   194
                 |> fold_rev mk_forall ps
krauss@23473
   195
                 |> cterm_of thy 
krauss@23473
   196
                 |> assume
krauss@23473
   197
krauss@23473
   198
      val t' = new_subg
krauss@23473
   199
                |> fold forall_elim cps
wenzelm@24977
   200
                |> Thm.elim_implies (fold forall_elim cps sg2)
krauss@23473
   201
                |> fold_rev forall_intr cps
krauss@23473
   202
krauss@23473
   203
      val st' = implies_elim st t'
krauss@23473
   204
                 |> implies_intr (cprop_of sg2)
krauss@23473
   205
                 |> implies_intr (cprop_of new_subg)
krauss@23473
   206
    in
krauss@23473
   207
      Seq.single st'
krauss@23473
   208
    end
krauss@23473
   209
krauss@23473
   210
fun mk_cases_statement thy t =
krauss@23473
   211
    let
krauss@23473
   212
      fun mk_clause t = 
krauss@23473
   213
          let 
krauss@23473
   214
            val (qs, imp) = dest_all_all t
krauss@23473
   215
          in 
krauss@23473
   216
            Logic.strip_imp_prems imp
krauss@23473
   217
             |> map (ObjectLogic.atomize_term thy)
krauss@23473
   218
             |> foldr1 HOLogic.mk_conj
krauss@23473
   219
             |> fold_rev (fn Free (v,T) => fn t => HOLogic.mk_exists (v,T,t)) qs
krauss@23473
   220
          end
krauss@23473
   221
krauss@23473
   222
      val (ps, imp) = dest_all_all t
krauss@23473
   223
    in 
krauss@23473
   224
      Logic.strip_imp_prems imp
krauss@23473
   225
       |> map mk_clause
krauss@23473
   226
       |> foldr1 HOLogic.mk_disj
krauss@23473
   227
       |> HOLogic.mk_Trueprop
krauss@23473
   228
       |> fold_rev lambda ps
krauss@23473
   229
    end
krauss@23473
   230
krauss@23473
   231
fun elim_to_cases1 ctxt st =
krauss@23473
   232
    let
krauss@23473
   233
      val thy = theory_of_thm st
krauss@23473
   234
      val [subg] = prems_of st
krauss@23473
   235
      val cex = mk_cases_statement thy subg
krauss@23473
   236
    in
krauss@23473
   237
      (insert_int_goal thy cex
krauss@23473
   238
       THEN REPEAT_ALL_NEW (Tactic.ematch_tac [disjE, exE, conjE]) 1
krauss@23473
   239
       THEN REPEAT (Goal.assume_rule_tac ctxt 1)
krauss@23473
   240
    (*   THEN REPEAT (etac thin_rl 1)*)) st
krauss@23473
   241
    end
krauss@23473
   242
krauss@23473
   243
fun elim_to_cases_tac ctxt = SELECT_GOAL (elim_to_cases1 ctxt)
krauss@23473
   244
krauss@23473
   245
val elim_to_cases_setup = Method.add_methods
krauss@23473
   246
  [("elim_to_cases", Method.ctxt_args (Method.SIMPLE_METHOD' o elim_to_cases_tac),
krauss@23473
   247
    "convert elimination-style goal to a disjunction of existentials")]
krauss@23473
   248
krauss@19564
   249
(* setup *)
krauss@19564
   250
wenzelm@21602
   251
val setup =
wenzelm@22846
   252
  Attrib.add_attributes
krauss@24168
   253
    [("fundef_cong", Attrib.add_del_args FundefCtxTree.cong_add FundefCtxTree.cong_del,
wenzelm@22846
   254
      "declaration of congruence rule for function definitions")]
haftmann@24626
   255
  #> setup_case_cong
wenzelm@22846
   256
  #> FundefRelation.setup
krauss@23473
   257
  #> elim_to_cases_setup
krauss@19564
   258
krauss@24168
   259
val get_congs = FundefCtxTree.get_fundef_congs o Context.Theory
krauss@19770
   260
krauss@21235
   261
krauss@19564
   262
(* outer syntax *)
krauss@19564
   263
krauss@19564
   264
local structure P = OuterParse and K = OuterKeyword in
krauss@19564
   265
krauss@25045
   266
val _ = OuterSyntax.keywords ["otherwise"];
wenzelm@24867
   267
wenzelm@24867
   268
val _ =
krauss@19564
   269
  OuterSyntax.command "function" "define general recursive functions" K.thy_goal
krauss@22498
   270
  (fundef_parser default_config
krauss@23203
   271
     >> (fn ((config, fixes), (flags, statements)) =>
krauss@23203
   272
            Toplevel.local_theory_to_proof (target_of config) (add_fundef fixes statements config flags)
krauss@21211
   273
            #> Toplevel.print));
krauss@20523
   274
wenzelm@24867
   275
val _ =
krauss@19564
   276
  OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
krauss@22733
   277
  (P.opt_target -- Scan.option P.term
wenzelm@21000
   278
    >> (fn (target, name) =>
wenzelm@21000
   279
           Toplevel.print o
wenzelm@26171
   280
           Toplevel.local_theory_to_proof target (termination_cmd name)));
krauss@19564
   281
krauss@19564
   282
end;
krauss@19564
   283
krauss@19564
   284
wenzelm@19585
   285
end