src/HOL/Tools/function_package/fundef_package.ML
author krauss
Fri Jun 01 15:57:45 2007 +0200 (2007-06-01)
changeset 23189 4574ab8f3b21
parent 22846 fb79144af9a3
child 23203 a5026e73cfcf
permissions -rw-r--r--
simplified interfaces, some restructuring
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@22498
    13
                      -> ((bstring * Attrib.src list) * (string * bool)) list 
wenzelm@20877
    14
                      -> FundefCommon.fundef_config
wenzelm@20877
    15
                      -> local_theory
krauss@22733
    16
                      -> Proof.state
krauss@20523
    17
wenzelm@20877
    18
    val add_fundef_i:  (string * typ option * mixfix) list
krauss@22498
    19
                       -> ((bstring * Attrib.src list) * (term * bool)) list
krauss@22170
    20
                       -> FundefCommon.fundef_config
wenzelm@20877
    21
                       -> local_theory
krauss@22733
    22
                       -> 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@23189
    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@23189
    45
krauss@23189
    46
(* Check for all sorts of errors in the input *)
krauss@23189
    47
fun check_def ctxt fixes eqs =
krauss@23189
    48
    let
krauss@23189
    49
      val fnames = map (fst o fst) fixes
krauss@23189
    50
                                
krauss@23189
    51
      fun check geq = 
krauss@23189
    52
          let
krauss@23189
    53
            fun input_error msg = cat_lines [msg, ProofContext.string_of_term ctxt geq]
krauss@23189
    54
                                  
krauss@23189
    55
            val fqgar as (fname, qs, gs, args, rhs) = split_def geq
krauss@23189
    56
                                 
krauss@23189
    57
            val _ = fname mem fnames 
krauss@23189
    58
                    orelse error (input_error ("Head symbol of left hand side must be " ^ plural "" "one out of " fnames 
krauss@23189
    59
                                               ^ commas_quote fnames))
krauss@23189
    60
                                            
krauss@23189
    61
            fun add_bvs t is = add_loose_bnos (t, 0, is)
krauss@23189
    62
            val rvs = (add_bvs rhs [] \\ fold add_bvs args [])
krauss@23189
    63
                        |> map (fst o nth (rev qs))
krauss@23189
    64
                      
krauss@23189
    65
            val _ = null rvs orelse error (input_error ("Variable" ^ plural " " "s " rvs ^ commas_quote rvs
krauss@23189
    66
                                                        ^ " occur" ^ plural "s" "" rvs ^ " on right hand side only:"))
krauss@23189
    67
                                    
krauss@23189
    68
            val _ = forall (forall_aterms (fn Free (n, _) => not (n mem fnames) | _ => true)) gs orelse
krauss@23189
    69
                    error (input_error "Recursive Calls not allowed in premises")
krauss@23189
    70
          in
krauss@23189
    71
            fqgar
krauss@23189
    72
          end
krauss@23189
    73
    in
krauss@23189
    74
      (mk_arities (map check eqs); ())
krauss@23189
    75
      handle ArgumentCount fname => 
krauss@23189
    76
             error ("Function " ^ quote fname ^ " has different numbers of arguments in different equations")
krauss@23189
    77
    end
krauss@23189
    78
krauss@23189
    79
krauss@23189
    80
fun mk_catchall fixes arities =
krauss@23189
    81
    let
krauss@23189
    82
      fun mk_eqn ((fname, fT), _) =
krauss@23189
    83
          let 
krauss@23189
    84
            val n = the (Symtab.lookup arities fname)
krauss@23189
    85
            val (argTs, rT) = chop n (binder_types fT)
krauss@23189
    86
                                   |> apsnd (fn Ts => Ts ---> body_type fT) 
krauss@23189
    87
                              
krauss@23189
    88
            val qs = map Free (Name.invent_list [] "a" n ~~ argTs)
krauss@23189
    89
          in
krauss@23189
    90
            HOLogic.mk_eq(list_comb (Free (fname, fT), qs),
krauss@23189
    91
                          Const ("HOL.undefined", rT))
krauss@23189
    92
              |> HOLogic.mk_Trueprop
krauss@23189
    93
              |> fold_rev mk_forall qs
krauss@23189
    94
          end
krauss@23189
    95
    in
krauss@23189
    96
      map mk_eqn fixes
krauss@23189
    97
    end
krauss@23189
    98
krauss@23189
    99
fun add_catchall fixes spec =
krauss@23189
   100
    let 
krauss@23189
   101
      val catchalls = mk_catchall fixes (mk_arities (map split_def (map (snd o snd) spec)))
krauss@23189
   102
    in
krauss@23189
   103
      spec @ map (pair ("",[]) o pair true) catchalls
krauss@23189
   104
    end
krauss@23189
   105
krauss@20523
   106
fun burrow_snd f ps = (* ('a list -> 'b list) -> ('c * 'a) list -> ('c * 'b) list *)
krauss@20523
   107
    let val (xs, ys) = split_list ps
krauss@20523
   108
    in xs ~~ f ys end
krauss@20270
   109
krauss@20523
   110
fun restore_spec_structure reps spec =
krauss@22498
   111
    (burrow_snd o burrow o K) reps spec
wenzelm@20363
   112
krauss@22166
   113
fun add_simps fixes spec sort label moreatts simps lthy =
krauss@19564
   114
    let
krauss@20523
   115
      val fnames = map (fst o fst) fixes
krauss@21255
   116
krauss@22166
   117
      val (saved_spec_simps, lthy) =
krauss@22498
   118
        fold_map note_theorem (restore_spec_structure simps spec) lthy
krauss@22498
   119
      val saved_simps = flat (map snd saved_spec_simps)
krauss@21255
   120
krauss@22166
   121
      val simps_by_f = sort saved_simps
krauss@19564
   122
krauss@22166
   123
      fun add_for_f fname simps =
wenzelm@21435
   124
        note_theorem
wenzelm@21658
   125
          ((NameSpace.qualified fname label, Attrib.internal (K Simplifier.simp_add) :: moreatts),
krauss@22166
   126
            simps) #> snd
krauss@19564
   127
    in
krauss@22166
   128
      (saved_simps,
krauss@22166
   129
       fold2 add_for_f fnames simps_by_f lthy)
krauss@19564
   130
    end
krauss@19564
   131
krauss@22166
   132
fun fundef_afterqed config fixes spec defname cont sort_cont [[proof]] lthy =
krauss@20523
   133
    let
krauss@22733
   134
      val FundefResult {fs, R, psimps, trsimps, subset_pinducts, simple_pinducts, termination, domintros, cases, ...} = 
krauss@22166
   135
          cont (Goal.close_result proof)
krauss@22166
   136
wenzelm@21391
   137
      val qualify = NameSpace.qualified defname
krauss@22170
   138
      val addsmps = add_simps fixes spec sort_cont
wenzelm@21602
   139
wenzelm@21602
   140
      val (((psimps', pinducts'), (_, [termination'])), lthy) =
krauss@21255
   141
          lthy
krauss@22170
   142
            |> addsmps "psimps" [] psimps
krauss@22170
   143
            ||> fold_option (snd oo addsmps "simps" []) trsimps
krauss@22166
   144
            ||>> note_theorem ((qualify "pinduct",
krauss@22166
   145
                                [Attrib.internal (K (InductAttrib.induct_set ""))]), simple_pinducts)
krauss@22166
   146
            ||>> note_theorem ((qualify "termination", []), [termination])
krauss@22166
   147
            ||> (snd o note_theorem ((qualify "cases", []), [cases]))
krauss@22166
   148
            ||> fold_option (snd oo curry note_theorem (qualify "domintros", [])) domintros
krauss@21255
   149
krauss@22170
   150
      val cdata = FundefCtxData { add_simps=addsmps, psimps=psimps',
krauss@22733
   151
                                  pinducts=snd pinducts', termination=termination', fs=fs, R=R, defname=defname }
wenzelm@22668
   152
      val cdata' = cdata |> morph_fundef_data (LocalTheory.target_morphism lthy);  (* FIXME !? *)
krauss@20523
   153
    in
krauss@22623
   154
      lthy 
krauss@22733
   155
        |> LocalTheory.declaration (fn phi => add_fundef_data (morph_fundef_data phi cdata)) (* save in target *)
krauss@22733
   156
        |> Context.proof_map (add_fundef_data cdata') (* also save in local context *)
krauss@20523
   157
    end (* FIXME: Add cases for induct and cases thm *)
krauss@20523
   158
krauss@20523
   159
krauss@20523
   160
krauss@20523
   161
fun prep_with_flags prep fixspec eqnss_flags global_flag lthy =
krauss@19564
   162
    let
krauss@22498
   163
      val flags = map (fn x => global_flag orelse (snd (snd x))) eqnss_flags
krauss@22498
   164
      val eqns = map (apsnd (single o fst)) eqnss_flags
krauss@20523
   165
krauss@20523
   166
      val ((fixes, _), ctxt') = prep fixspec [] lthy
krauss@22498
   167
krauss@22498
   168
      fun prep_eqn e = the_single (snd (fst (prep [] [e] ctxt')))
krauss@22498
   169
                         |> apsnd the_single
krauss@22498
   170
krauss@23189
   171
      val raw_spec = map prep_eqn eqns
krauss@22498
   172
                     |> map (apsnd (fn t => fold_rev (mk_forall o Free) (frees_in_term ctxt' t) t)) (* Add quantifiers *)
krauss@23189
   173
krauss@23189
   174
      val _ = check_def ctxt' fixes (map snd raw_spec)
krauss@23189
   175
krauss@23189
   176
      val spec = raw_spec
krauss@23189
   177
                     |> burrow_snd (fn ts => flags ~~ ts)
krauss@23189
   178
                     (*|> (if global_flag then add_catchall fixes else I) *) (* Completion: still disabled *)
krauss@23189
   179
                     |> burrow_snd (FundefSplit.split_some_equations ctxt')
krauss@23189
   180
krauss@20523
   181
    in
krauss@20523
   182
      ((fixes, spec), ctxt')
krauss@20523
   183
    end
krauss@20523
   184
krauss@20654
   185
fun gen_add_fundef prep_spec fixspec eqnss_flags config lthy =
krauss@20523
   186
    let
krauss@23189
   187
      val FundefConfig {sequential, ...} = config
krauss@20654
   188
krauss@20654
   189
      val ((fixes, spec), ctxt') = prep_with_flags prep_spec fixspec eqnss_flags sequential lthy
krauss@22166
   190
krauss@22166
   191
      val defname = mk_defname fixes
krauss@22166
   192
krauss@22498
   193
      val t_eqns = spec |> map snd |> flat (* flatten external structure *)
krauss@20523
   194
krauss@22166
   195
      val ((goalstate, cont, sort_cont), lthy) =
krauss@23189
   196
          FundefMutual.prepare_fundef_mutual config defname fixes t_eqns lthy
krauss@20523
   197
krauss@22166
   198
      val afterqed = fundef_afterqed config fixes spec defname cont sort_cont
krauss@20523
   199
    in
krauss@22733
   200
      lthy
krauss@22733
   201
        |> Proof.theorem_i NONE afterqed [[(Logic.unprotect (concl_of goalstate), [])]]
krauss@22733
   202
        |> Proof.refine (Method.primitive_text (fn _ => goalstate)) |> Seq.hd
krauss@20523
   203
    end
krauss@20523
   204
krauss@20523
   205
krauss@22733
   206
fun total_termination_afterqed data [[totality]] lthy =
krauss@20523
   207
    let
krauss@22733
   208
      val FundefCtxData { add_simps, psimps, pinducts, defname, ... } = data
krauss@21255
   209
krauss@22166
   210
      val totality = Goal.close_result totality
krauss@19564
   211
krauss@21255
   212
      val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
krauss@19564
   213
krauss@22166
   214
      val tsimps = map remove_domain_condition psimps
krauss@22166
   215
      val tinduct = map remove_domain_condition pinducts
krauss@19770
   216
krauss@21511
   217
        (* FIXME: How to generate code from (possibly) local contexts*)
krauss@21511
   218
      val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
wenzelm@21658
   219
      val allatts = if has_guards then [] else [Attrib.internal (K (RecfunCodegen.add NONE))]
wenzelm@21602
   220
krauss@21511
   221
      val qualify = NameSpace.qualified defname;
krauss@19564
   222
    in
krauss@21511
   223
      lthy
krauss@22166
   224
        |> add_simps "simps" allatts tsimps |> snd
krauss@22166
   225
        |> note_theorem ((qualify "induct", []), tinduct) |> snd
wenzelm@20363
   226
    end
krauss@19564
   227
krauss@19564
   228
krauss@22733
   229
fun setup_termination_proof term_opt lthy =
krauss@20523
   230
    let
krauss@22733
   231
      val data = the (case term_opt of
krauss@22733
   232
                        SOME t => import_fundef_data (ProofContext.read_term lthy t) (Context.Proof lthy)
krauss@22733
   233
                      | NONE => import_last_fundef (Context.Proof lthy))
krauss@22733
   234
          handle Option.Option => raise ERROR ("Not a function: " ^ quote (the_default "" term_opt))
krauss@20523
   235
krauss@22166
   236
        val FundefCtxData {termination, R, ...} = data
krauss@22325
   237
        val domT = domain_type (fastype_of R)
krauss@22325
   238
        val goal = HOLogic.mk_Trueprop (HOLogic.mk_all ("x", domT, mk_acc domT R $ Free ("x", domT)))
krauss@20523
   239
    in
wenzelm@20877
   240
      lthy
krauss@22325
   241
        |> ProofContext.note_thmss_i "" [(("", [ContextRules.rule_del]), [([allI], [])])] |> snd
krauss@22325
   242
        |> ProofContext.note_thmss_i "" [(("", [ContextRules.intro_bang (SOME 1)]), [([allI], [])])] |> snd
wenzelm@21602
   243
        |> ProofContext.note_thmss_i ""
krauss@22325
   244
          [(("termination", [ContextRules.intro_bang (SOME 0)]),
wenzelm@21602
   245
            [([Goal.norm_result termination], [])])] |> snd
krauss@22733
   246
        |> Proof.theorem_i NONE (total_termination_afterqed data) [[(goal, [])]]
krauss@20523
   247
    end
krauss@20523
   248
krauss@20523
   249
krauss@20523
   250
val add_fundef = gen_add_fundef Specification.read_specification
krauss@20523
   251
val add_fundef_i = gen_add_fundef Specification.cert_specification
krauss@19611
   252
krauss@19564
   253
krauss@19564
   254
krauss@19564
   255
(* congruence rules *)
krauss@19564
   256
wenzelm@19617
   257
val cong_add = Thm.declaration_attribute (map_fundef_congs o Drule.add_rule o safe_mk_meta_eq);
wenzelm@19617
   258
val cong_del = Thm.declaration_attribute (map_fundef_congs o Drule.del_rule o safe_mk_meta_eq);
krauss@19564
   259
krauss@21235
   260
(* Datatype hook to declare datatype congs as "fundef_congs" *)
krauss@21235
   261
krauss@21235
   262
wenzelm@21602
   263
fun add_case_cong n thy =
wenzelm@21602
   264
    Context.theory_map (map_fundef_congs (Drule.add_rule
krauss@21235
   265
                          (DatatypePackage.get_datatype thy n |> the
krauss@21235
   266
                           |> #case_cong
wenzelm@21602
   267
                           |> safe_mk_meta_eq)))
krauss@21235
   268
                       thy
krauss@21235
   269
krauss@21235
   270
val case_cong_hook = fold add_case_cong
krauss@21235
   271
wenzelm@21602
   272
val setup_case_cong_hook =
krauss@21235
   273
    DatatypeHooks.add case_cong_hook
krauss@21235
   274
    #> (fn thy => case_cong_hook (Symtab.keys (DatatypePackage.get_datatypes thy)) thy)
krauss@19564
   275
krauss@19564
   276
(* setup *)
krauss@19564
   277
wenzelm@21602
   278
val setup =
wenzelm@22846
   279
  Attrib.add_attributes
wenzelm@22846
   280
    [("fundef_cong", Attrib.add_del_args cong_add cong_del,
wenzelm@22846
   281
      "declaration of congruence rule for function definitions")]
wenzelm@22846
   282
  #> setup_case_cong_hook
wenzelm@22846
   283
  #> FundefRelation.setup
krauss@19564
   284
krauss@19770
   285
val get_congs = FundefCommon.get_fundef_congs o Context.Theory
krauss@19770
   286
krauss@19770
   287
krauss@21235
   288
krauss@19564
   289
(* outer syntax *)
krauss@19564
   290
krauss@19564
   291
local structure P = OuterParse and K = OuterKeyword in
krauss@19564
   292
krauss@19564
   293
val functionP =
krauss@19564
   294
  OuterSyntax.command "function" "define general recursive functions" K.thy_goal
krauss@22498
   295
  (fundef_parser default_config
krauss@22498
   296
     >> (fn ((config, fixes), statements) =>
krauss@22733
   297
            Toplevel.local_theory_to_proof (target_of config) (add_fundef fixes statements config)
krauss@21211
   298
            #> Toplevel.print));
krauss@20523
   299
krauss@19564
   300
val terminationP =
krauss@19564
   301
  OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
krauss@22733
   302
  (P.opt_target -- Scan.option P.term
wenzelm@21000
   303
    >> (fn (target, name) =>
wenzelm@21000
   304
           Toplevel.print o
krauss@21211
   305
           Toplevel.local_theory_to_proof target (setup_termination_proof name)));
krauss@19564
   306
krauss@19564
   307
val _ = OuterSyntax.add_parsers [functionP];
krauss@19564
   308
val _ = OuterSyntax.add_parsers [terminationP];
krauss@20654
   309
val _ = OuterSyntax.add_keywords ["sequential", "otherwise"];
krauss@19564
   310
krauss@19564
   311
end;
krauss@19564
   312
krauss@19564
   313
wenzelm@19585
   314
end