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