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