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