src/HOL/Tools/function_package/fundef_package.ML
author krauss
Thu Feb 15 17:35:19 2007 +0100 (2007-02-15)
changeset 22325 be61bd159a99
parent 22170 5682eeaefaf4
child 22498 62cdd4b3e96b
permissions -rw-r--r--
changed termination goal to use object quantifier
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@22170
    13
                      -> ((bstring * Attrib.src list) * (string * bool) list) list list
wenzelm@20877
    14
                      -> FundefCommon.fundef_config
wenzelm@20877
    15
                      -> local_theory
krauss@21211
    16
                      -> string * Proof.state
krauss@20523
    17
wenzelm@20877
    18
    val add_fundef_i:  (string * typ option * mixfix) list
krauss@22170
    19
                       -> ((bstring * Attrib.src list) * (term * bool) list) list list
krauss@22170
    20
                       -> FundefCommon.fundef_config
wenzelm@20877
    21
                       -> local_theory
krauss@21211
    22
                       -> string * Proof.state
krauss@21211
    23
krauss@21211
    24
    val setup_termination_proof : string option -> local_theory -> Proof.state
krauss@19564
    25
krauss@19564
    26
    val cong_add: attribute
krauss@19564
    27
    val cong_del: attribute
wenzelm@20363
    28
krauss@19564
    29
    val setup : theory -> theory
krauss@21235
    30
    val setup_case_cong_hook : theory -> theory
krauss@19770
    31
    val get_congs : theory -> thm list
krauss@19564
    32
end
krauss@19564
    33
krauss@19564
    34
krauss@22170
    35
structure FundefPackage : FUNDEF_PACKAGE =
krauss@19564
    36
struct
krauss@19564
    37
krauss@21051
    38
open FundefLib
krauss@19564
    39
open FundefCommon
krauss@19564
    40
wenzelm@21435
    41
val note_theorem = LocalTheory.note Thm.theoremK
wenzelm@21435
    42
krauss@22166
    43
fun mk_defname fixes = fixes |> map (fst o fst) |> space_implode "_" 
krauss@22166
    44
krauss@20523
    45
fun burrow_snd f ps = (* ('a list -> 'b list) -> ('c * 'a) list -> ('c * 'b) list *)
krauss@20523
    46
    let val (xs, ys) = split_list ps
krauss@20523
    47
    in xs ~~ f ys end
krauss@20270
    48
krauss@20523
    49
fun restore_spec_structure reps spec =
krauss@20523
    50
    (burrow o burrow_snd o burrow o K) reps spec
wenzelm@20363
    51
krauss@22166
    52
fun add_simps fixes spec sort label moreatts simps lthy =
krauss@19564
    53
    let
krauss@20523
    54
      val fnames = map (fst o fst) fixes
krauss@21255
    55
krauss@22166
    56
      val (saved_spec_simps, lthy) =
krauss@22166
    57
        fold_map (fold_map note_theorem) (restore_spec_structure simps spec) lthy
krauss@22166
    58
      val saved_simps = flat (map snd (flat saved_spec_simps))
krauss@21255
    59
krauss@22166
    60
      val simps_by_f = sort saved_simps
krauss@19564
    61
krauss@22166
    62
      fun add_for_f fname simps =
wenzelm@21435
    63
        note_theorem
wenzelm@21658
    64
          ((NameSpace.qualified fname label, Attrib.internal (K Simplifier.simp_add) :: moreatts),
krauss@22166
    65
            simps) #> snd
krauss@19564
    66
    in
krauss@22166
    67
      (saved_simps,
krauss@22166
    68
       fold2 add_for_f fnames simps_by_f lthy)
krauss@19564
    69
    end
krauss@19564
    70
krauss@19564
    71
krauss@22166
    72
fun fundef_afterqed config fixes spec defname cont sort_cont [[proof]] lthy =
krauss@20523
    73
    let
krauss@22166
    74
      val FundefResult {f, R, psimps, trsimps, subset_pinducts, simple_pinducts, termination, domintros, cases, ...} = 
krauss@22166
    75
          cont (Goal.close_result proof)
krauss@22166
    76
wenzelm@21391
    77
      val qualify = NameSpace.qualified defname
krauss@22170
    78
      val addsmps = add_simps fixes spec sort_cont
wenzelm@21602
    79
wenzelm@21602
    80
      val (((psimps', pinducts'), (_, [termination'])), lthy) =
krauss@21255
    81
          lthy
krauss@22170
    82
            |> addsmps "psimps" [] psimps
krauss@22170
    83
            ||> fold_option (snd oo addsmps "simps" []) trsimps
krauss@22166
    84
            ||>> note_theorem ((qualify "pinduct",
krauss@22166
    85
                                [Attrib.internal (K (InductAttrib.induct_set ""))]), simple_pinducts)
krauss@22166
    86
            ||>> note_theorem ((qualify "termination", []), [termination])
krauss@22166
    87
            ||> (snd o note_theorem ((qualify "cases", []), [cases]))
krauss@22166
    88
            ||> fold_option (snd oo curry note_theorem (qualify "domintros", [])) domintros
krauss@21255
    89
krauss@22170
    90
      val cdata = FundefCtxData { add_simps=addsmps, psimps=psimps',
krauss@21255
    91
                                  pinducts=snd pinducts', termination=termination', f=f, R=R }
krauss@20523
    92
    in
wenzelm@21491
    93
      lthy  (* FIXME proper handling of morphism *)
wenzelm@21491
    94
        |> LocalTheory.declaration (fn phi => add_fundef_data defname cdata) (* save in target *)
krauss@21255
    95
        |> Context.proof_map (add_fundef_data defname cdata) (* also save in local context *)
krauss@20523
    96
    end (* FIXME: Add cases for induct and cases thm *)
krauss@20523
    97
krauss@20523
    98
krauss@20523
    99
krauss@20523
   100
fun prep_with_flags prep fixspec eqnss_flags global_flag lthy =
krauss@19564
   101
    let
krauss@20523
   102
      val eqnss = map (map (apsnd (map fst))) eqnss_flags
krauss@20523
   103
      val flags = map (map (map (fn (_, f) => global_flag orelse f) o snd)) eqnss_flags
krauss@20523
   104
krauss@20523
   105
      val ((fixes, _), ctxt') = prep fixspec [] lthy
krauss@20523
   106
      val spec = map (fn eqns => snd (fst (prep [] eqns ctxt'))) eqnss
krauss@20523
   107
                     |> map (map (apsnd (map (fn t => fold_rev (mk_forall o Free) (frees_in_term ctxt' t) t)))) (* Add quantifiers *)
krauss@20523
   108
                     |> map2 (map2 (fn fs => fn (r, thms) => (r, fs ~~ thms))) flags
wenzelm@20877
   109
                     |> (burrow o burrow_snd o burrow)
krauss@20523
   110
                          (FundefSplit.split_some_equations lthy)
krauss@20523
   111
                     |> map (map (apsnd flat))
krauss@20523
   112
    in
krauss@20523
   113
      ((fixes, spec), ctxt')
krauss@20523
   114
    end
krauss@20523
   115
krauss@19564
   116
krauss@20654
   117
fun gen_add_fundef prep_spec fixspec eqnss_flags config lthy =
krauss@20523
   118
    let
krauss@22166
   119
      val FundefConfig {sequential, default, tailrec, ...} = config
krauss@20654
   120
krauss@20654
   121
      val ((fixes, spec), ctxt') = prep_with_flags prep_spec fixspec eqnss_flags sequential lthy
krauss@22166
   122
krauss@22166
   123
      val defname = mk_defname fixes
krauss@22166
   124
krauss@20523
   125
      val t_eqns = spec
krauss@20523
   126
                     |> flat |> map snd |> flat (* flatten external structure *)
krauss@20523
   127
krauss@22166
   128
      val ((goalstate, cont, sort_cont), lthy) =
krauss@22166
   129
          FundefMutual.prepare_fundef_mutual config defname fixes t_eqns default lthy
krauss@20523
   130
krauss@22166
   131
      val afterqed = fundef_afterqed config fixes spec defname cont sort_cont
krauss@20523
   132
    in
krauss@22166
   133
      (defname, lthy
krauss@22166
   134
         |> Proof.theorem_i NONE afterqed [[(Logic.unprotect (concl_of goalstate), [])]]
krauss@22166
   135
         |> Proof.refine (Method.primitive_text (fn _ => goalstate)) |> Seq.hd)
krauss@20523
   136
    end
krauss@20523
   137
krauss@20523
   138
krauss@20523
   139
fun total_termination_afterqed defname data [[totality]] lthy =
krauss@20523
   140
    let
krauss@22166
   141
      val FundefCtxData { add_simps, psimps, pinducts, ... } = data
krauss@21255
   142
krauss@22166
   143
      val totality = Goal.close_result totality
krauss@19564
   144
krauss@21255
   145
      val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
krauss@19564
   146
krauss@22166
   147
      val tsimps = map remove_domain_condition psimps
krauss@22166
   148
      val tinduct = map remove_domain_condition pinducts
krauss@19770
   149
krauss@21511
   150
        (* FIXME: How to generate code from (possibly) local contexts*)
krauss@21511
   151
      val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
wenzelm@21658
   152
      val allatts = if has_guards then [] else [Attrib.internal (K (RecfunCodegen.add NONE))]
wenzelm@21602
   153
krauss@21511
   154
      val qualify = NameSpace.qualified defname;
krauss@19564
   155
    in
krauss@21511
   156
      lthy
krauss@22166
   157
        |> add_simps "simps" allatts tsimps |> snd
krauss@22166
   158
        |> note_theorem ((qualify "induct", []), tinduct) |> snd
wenzelm@20363
   159
    end
krauss@19564
   160
krauss@19564
   161
krauss@21211
   162
fun setup_termination_proof name_opt lthy =
krauss@20523
   163
    let
krauss@22166
   164
        val defname = the_default (get_last_fundef (Context.Proof lthy)) name_opt
krauss@22166
   165
        val data = the (get_fundef_data defname (Context.Proof lthy))
krauss@22166
   166
                   handle Option.Option => raise ERROR ("No such function definition: " ^ defname)
krauss@20523
   167
krauss@22166
   168
        val FundefCtxData {termination, R, ...} = data
krauss@22325
   169
        val domT = domain_type (fastype_of R)
krauss@22325
   170
        val goal = HOLogic.mk_Trueprop (HOLogic.mk_all ("x", domT, mk_acc domT R $ Free ("x", domT)))
krauss@20523
   171
    in
wenzelm@20877
   172
      lthy
krauss@22325
   173
        |> ProofContext.note_thmss_i "" [(("", [ContextRules.rule_del]), [([allI], [])])] |> snd
krauss@22325
   174
        |> ProofContext.note_thmss_i "" [(("", [ContextRules.intro_bang (SOME 1)]), [([allI], [])])] |> snd
wenzelm@21602
   175
        |> ProofContext.note_thmss_i ""
krauss@22325
   176
          [(("termination", [ContextRules.intro_bang (SOME 0)]),
wenzelm@21602
   177
            [([Goal.norm_result termination], [])])] |> snd
krauss@21319
   178
        |> set_termination_rule termination
krauss@22166
   179
        |> Proof.theorem_i NONE (total_termination_afterqed defname data) [[(goal, [])]]
krauss@20523
   180
    end
krauss@20523
   181
krauss@20523
   182
krauss@20523
   183
val add_fundef = gen_add_fundef Specification.read_specification
krauss@20523
   184
val add_fundef_i = gen_add_fundef Specification.cert_specification
krauss@19611
   185
krauss@19564
   186
krauss@19564
   187
krauss@19564
   188
(* congruence rules *)
krauss@19564
   189
wenzelm@19617
   190
val cong_add = Thm.declaration_attribute (map_fundef_congs o Drule.add_rule o safe_mk_meta_eq);
wenzelm@19617
   191
val cong_del = Thm.declaration_attribute (map_fundef_congs o Drule.del_rule o safe_mk_meta_eq);
krauss@19564
   192
krauss@21235
   193
(* Datatype hook to declare datatype congs as "fundef_congs" *)
krauss@21235
   194
krauss@21235
   195
wenzelm@21602
   196
fun add_case_cong n thy =
wenzelm@21602
   197
    Context.theory_map (map_fundef_congs (Drule.add_rule
krauss@21235
   198
                          (DatatypePackage.get_datatype thy n |> the
krauss@21235
   199
                           |> #case_cong
wenzelm@21602
   200
                           |> safe_mk_meta_eq)))
krauss@21235
   201
                       thy
krauss@21235
   202
krauss@21235
   203
val case_cong_hook = fold add_case_cong
krauss@21235
   204
wenzelm@21602
   205
val setup_case_cong_hook =
krauss@21235
   206
    DatatypeHooks.add case_cong_hook
krauss@21235
   207
    #> (fn thy => case_cong_hook (Symtab.keys (DatatypePackage.get_datatypes thy)) thy)
krauss@19564
   208
krauss@19564
   209
(* setup *)
krauss@19564
   210
wenzelm@21602
   211
val setup =
wenzelm@21602
   212
    FundefData.init
krauss@21235
   213
      #> FundefCongs.init
krauss@21319
   214
      #> TerminationRule.init
krauss@21235
   215
      #>  Attrib.add_attributes
krauss@21235
   216
            [("fundef_cong", Attrib.add_del_args cong_add cong_del, "declaration of congruence rule for function definitions")]
krauss@21235
   217
      #> setup_case_cong_hook
krauss@21319
   218
      #> FundefRelation.setup
krauss@19564
   219
krauss@19770
   220
val get_congs = FundefCommon.get_fundef_congs o Context.Theory
krauss@19770
   221
krauss@19770
   222
krauss@21235
   223
krauss@19564
   224
(* outer syntax *)
krauss@19564
   225
krauss@19564
   226
local structure P = OuterParse and K = OuterKeyword in
krauss@19564
   227
krauss@20270
   228
krauss@20270
   229
krauss@20523
   230
fun or_list1 s = P.enum1 "|" s
krauss@20523
   231
krauss@20523
   232
val opt_sequential = Scan.optional ((P.$$$ "(" |-- P.$$$ "sequential" --| P.$$$ ")") >> K true) false
krauss@20523
   233
krauss@20523
   234
val otherwise = P.$$$ "(" |-- P.$$$ "otherwise" --| P.$$$ ")"
wenzelm@22102
   235
val statement_ow = P.and_list1 (SpecParse.opt_thm_name ":" -- Scan.repeat1 (P.prop -- Scan.optional (otherwise >> K true) false))
krauss@20523
   236
val statements_ow = or_list1 statement_ow
krauss@20270
   237
krauss@20270
   238
krauss@19564
   239
val functionP =
krauss@19564
   240
  OuterSyntax.command "function" "define general recursive functions" K.thy_goal
wenzelm@22102
   241
  ((config_parser default_config -- P.opt_target -- P.fixes --| P.$$$ "where" -- statements_ow)
krauss@20654
   242
     >> (fn (((config, target), fixes), statements) =>
krauss@21211
   243
            Toplevel.local_theory_to_proof target (add_fundef fixes statements config #> snd)
krauss@21211
   244
            #> Toplevel.print));
krauss@20523
   245
krauss@19564
   246
krauss@21051
   247
krauss@19564
   248
val terminationP =
krauss@19564
   249
  OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
wenzelm@22102
   250
  (P.opt_target -- Scan.option P.name
wenzelm@21000
   251
    >> (fn (target, name) =>
wenzelm@21000
   252
           Toplevel.print o
krauss@21211
   253
           Toplevel.local_theory_to_proof target (setup_termination_proof name)));
krauss@19564
   254
krauss@20338
   255
krauss@19564
   256
val _ = OuterSyntax.add_parsers [functionP];
krauss@19564
   257
val _ = OuterSyntax.add_parsers [terminationP];
krauss@20654
   258
val _ = OuterSyntax.add_keywords ["sequential", "otherwise"];
krauss@19564
   259
krauss@19564
   260
end;
krauss@19564
   261
krauss@19564
   262
wenzelm@19585
   263
end