src/HOL/Tools/function_package/fundef_common.ML
author krauss
Mon, 16 Jul 2007 21:22:43 +0200
changeset 23819 2040846d1bbe
parent 23766 77e796fe89eb
child 24039 273698405054
permissions -rw-r--r--
some interface cleanup
krauss@19564
     1
(*  Title:      HOL/Tools/function_package/fundef_common.ML
krauss@19564
     2
    ID:         $Id$
krauss@19564
     3
    Author:     Alexander Krauss, TU Muenchen
krauss@19564
     4
krauss@19564
     5
A package for general recursive function definitions. 
krauss@23203
     6
Common definitions and other infrastructure.
krauss@19564
     7
*)
krauss@19564
     8
krauss@19564
     9
structure FundefCommon =
krauss@19564
    10
struct
krauss@19564
    11
wenzelm@23215
    12
local open FundefLib in
wenzelm@23215
    13
krauss@22498
    14
(* Profiling *)
krauss@21255
    15
val profile = ref false;
krauss@21255
    16
krauss@21255
    17
fun PROFILE msg = if !profile then timeap_msg msg else I
krauss@21255
    18
krauss@22498
    19
berghofe@23766
    20
val acc_const_name = "Accessible_Part.accp"
krauss@20523
    21
fun mk_acc domT R =
krauss@22733
    22
    Const (acc_const_name, (domT --> domT --> HOLogic.boolT) --> domT --> HOLogic.boolT) $ R 
krauss@19564
    23
krauss@21319
    24
val function_name = suffix "C"
krauss@21319
    25
val graph_name = suffix "_graph"
krauss@21319
    26
val rel_name = suffix "_rel"
krauss@21319
    27
val dom_name = suffix "_dom"
krauss@21319
    28
krauss@19564
    29
krauss@19583
    30
datatype fundef_result =
krauss@19583
    31
  FundefResult of
krauss@19564
    32
     {
krauss@22733
    33
      fs: term list,
krauss@20523
    34
      G: term,
krauss@20523
    35
      R: term,
krauss@19770
    36
krauss@20523
    37
      psimps : thm list, 
krauss@22166
    38
      trsimps : thm list option, 
krauss@22166
    39
krauss@19770
    40
      subset_pinducts : thm list, 
krauss@19770
    41
      simple_pinducts : thm list, 
krauss@19770
    42
      cases : thm,
krauss@19770
    43
      termination : thm,
krauss@22166
    44
      domintros : thm list option
krauss@19770
    45
     }
krauss@19770
    46
krauss@22733
    47
krauss@21255
    48
datatype fundef_context_data =
krauss@21255
    49
  FundefCtxData of
krauss@21255
    50
     {
krauss@22733
    51
      defname : string,
krauss@22733
    52
krauss@23819
    53
      (* contains no logical entities: invariant under morphisms *)
krauss@22166
    54
      add_simps : string -> Attrib.src list -> thm list -> local_theory -> thm list * local_theory,
krauss@19770
    55
krauss@22733
    56
      fs : term list,
krauss@21255
    57
      R : term,
krauss@21255
    58
      
krauss@21255
    59
      psimps: thm list,
krauss@21255
    60
      pinducts: thm list,
krauss@21255
    61
      termination: thm
krauss@21255
    62
     }
krauss@21255
    63
krauss@22733
    64
fun morph_fundef_data phi (FundefCtxData {add_simps, fs, R, psimps, pinducts, termination, defname}) =
krauss@22623
    65
    let
krauss@22733
    66
      val term = Morphism.term phi val thm = Morphism.thm phi val fact = Morphism.fact phi
krauss@22733
    67
      val name = Morphism.name phi
krauss@22623
    68
    in
krauss@23819
    69
      FundefCtxData { add_simps = add_simps,
krauss@22733
    70
                      fs = map term fs, R = term R, psimps = fact psimps, 
krauss@22733
    71
                      pinducts = fact pinducts, termination = thm termination,
krauss@22733
    72
                      defname = name defname }
krauss@22623
    73
    end
krauss@22623
    74
krauss@20523
    75
structure FundefData = GenericDataFun
wenzelm@22846
    76
(
wenzelm@22846
    77
  type T = (term * fundef_context_data) NetRules.T;
haftmann@22760
    78
  val empty = NetRules.init
haftmann@22760
    79
    (op aconv o pairself fst : (term * fundef_context_data) * (term * fundef_context_data) -> bool)
haftmann@22760
    80
    fst;
krauss@19564
    81
  val copy = I;
krauss@19564
    82
  val extend = I;
krauss@22733
    83
  fun merge _ (tab1, tab2) = NetRules.merge (tab1, tab2)
wenzelm@22846
    84
);
krauss@19564
    85
krauss@19564
    86
krauss@19564
    87
structure FundefCongs = GenericDataFun
wenzelm@22846
    88
(
wenzelm@22846
    89
  type T = thm list
wenzelm@22846
    90
  val empty = []
wenzelm@22846
    91
  val extend = I
wenzelm@22846
    92
  fun merge _ = Drule.merge_rules
wenzelm@22846
    93
);
krauss@19564
    94
krauss@19564
    95
krauss@22733
    96
(* Generally useful?? *)
krauss@22733
    97
fun lift_morphism thy f = 
krauss@22733
    98
    let 
krauss@22733
    99
      val term = Drule.term_rule thy f
krauss@22733
   100
    in
krauss@22733
   101
      Morphism.thm_morphism f $> Morphism.term_morphism term $> Morphism.typ_morphism (Logic.type_map term)
krauss@22733
   102
    end
krauss@19564
   103
krauss@22733
   104
fun import_fundef_data t ctxt =
krauss@22733
   105
    let
krauss@22733
   106
      val thy = Context.theory_of ctxt
krauss@22733
   107
      val ct = cterm_of thy t
krauss@22733
   108
      val inst_morph = lift_morphism thy o Thm.instantiate 
krauss@19564
   109
krauss@22733
   110
      fun match data = 
wenzelm@22903
   111
          SOME (morph_fundef_data (inst_morph (Thm.match (cterm_of thy (fst data), ct))) (snd data))
krauss@22733
   112
          handle Pattern.MATCH => NONE
krauss@22733
   113
    in 
krauss@22733
   114
      get_first match (NetRules.retrieve (FundefData.get ctxt) t)
krauss@22733
   115
    end
krauss@19564
   116
krauss@22733
   117
fun import_last_fundef ctxt =
krauss@22733
   118
    case NetRules.rules (FundefData.get ctxt) of
krauss@22733
   119
      [] => NONE
krauss@22733
   120
    | (t, data) :: _ =>
krauss@22733
   121
      let 
krauss@22733
   122
        val ([t'], ctxt') = Variable.import_terms true [t] (Context.proof_of ctxt)
krauss@22733
   123
      in
krauss@22733
   124
        import_fundef_data t' (Context.Proof ctxt')
krauss@22733
   125
      end
krauss@22733
   126
krauss@22733
   127
val all_fundef_data = NetRules.rules o FundefData.get
krauss@21319
   128
krauss@19564
   129
val map_fundef_congs = FundefCongs.map 
krauss@19564
   130
val get_fundef_congs = FundefCongs.get
krauss@19564
   131
krauss@20654
   132
krauss@21319
   133
krauss@22733
   134
structure TerminationRule = GenericDataFun
wenzelm@22846
   135
(
wenzelm@22846
   136
  type T = thm list
wenzelm@22846
   137
  val empty = []
wenzelm@22846
   138
  val extend = I
wenzelm@22846
   139
  fun merge _ = Drule.merge_rules
wenzelm@22846
   140
);
krauss@21319
   141
krauss@22733
   142
val get_termination_rules = TerminationRule.get
krauss@22733
   143
val store_termination_rule = TerminationRule.map o cons
krauss@22733
   144
val apply_termination_rule = resolve_tac o get_termination_rules o Context.Proof
krauss@22733
   145
krauss@22733
   146
fun add_fundef_data (data as FundefCtxData {fs, termination, ...}) =
krauss@22733
   147
    FundefData.map (fold (fn f => NetRules.insert (f, data)) fs)
krauss@22733
   148
    #> store_termination_rule termination
krauss@21319
   149
krauss@20654
   150
(* Configuration management *)
krauss@20654
   151
datatype fundef_opt 
krauss@20654
   152
  = Sequential
krauss@20654
   153
  | Default of string
krauss@21051
   154
  | Target of xstring
krauss@21319
   155
  | DomIntros
krauss@22166
   156
  | Tailrec
krauss@20654
   157
krauss@20654
   158
datatype fundef_config
krauss@20654
   159
  = FundefConfig of
krauss@20654
   160
   {
krauss@20654
   161
    sequential: bool,
krauss@20654
   162
    default: string,
krauss@21319
   163
    target: xstring option,
krauss@22166
   164
    domintros: bool,
krauss@22166
   165
    tailrec: bool
krauss@20654
   166
   }
krauss@20654
   167
krauss@23203
   168
fun apply_opt Sequential (FundefConfig {sequential, default, target, domintros,tailrec}) = 
krauss@23203
   169
    FundefConfig {sequential=true, default=default, target=target, domintros=domintros, tailrec=tailrec}
krauss@23203
   170
  | apply_opt (Default d) (FundefConfig {sequential, default, target, domintros,tailrec}) = 
krauss@23203
   171
    FundefConfig {sequential=sequential, default=d, target=target, domintros=domintros, tailrec=tailrec}
krauss@23203
   172
  | apply_opt (Target t) (FundefConfig {sequential, default, target, domintros,tailrec}) =
krauss@23203
   173
    FundefConfig {sequential=sequential, default=default, target=SOME t, domintros=domintros, tailrec=tailrec}
krauss@23203
   174
  | apply_opt DomIntros (FundefConfig {sequential, default, target, domintros,tailrec}) =
krauss@23203
   175
    FundefConfig {sequential=sequential, default=default, target=target, domintros=true,tailrec=tailrec}
krauss@23203
   176
  | apply_opt Tailrec (FundefConfig {sequential, default, target, domintros,tailrec}) =
krauss@23203
   177
    FundefConfig {sequential=sequential, default=default, target=target, domintros=domintros,tailrec=true}
krauss@20654
   178
krauss@22498
   179
fun target_of (FundefConfig {target, ...}) = target
krauss@21051
   180
krauss@23819
   181
val default_config = FundefConfig { sequential=false, default="%x. arbitrary", 
krauss@23819
   182
                                    target=NONE, domintros=false, tailrec=false }
krauss@23819
   183
krauss@23819
   184
krauss@23189
   185
(* Common operations on equations *)
krauss@23189
   186
krauss@23189
   187
fun open_all_all (Const ("all", _) $ Abs (n, T, b)) = apfst (cons (n, T)) (open_all_all b)
krauss@23189
   188
  | open_all_all t = ([], t)
krauss@23189
   189
krauss@23189
   190
exception MalformedEquation of term
krauss@23189
   191
krauss@23189
   192
fun split_def geq =
krauss@23189
   193
    let
krauss@23189
   194
      val (qs, imp) = open_all_all geq
krauss@23189
   195
krauss@23189
   196
      val gs = Logic.strip_imp_prems imp
krauss@23189
   197
      val eq = Logic.strip_imp_concl imp
krauss@23189
   198
krauss@23189
   199
      val (f_args, rhs) = HOLogic.dest_eq (HOLogic.dest_Trueprop eq)
krauss@23189
   200
          handle TERM _ => raise MalformedEquation geq
krauss@23189
   201
krauss@23189
   202
      val (head, args) = strip_comb f_args
krauss@23189
   203
krauss@23189
   204
      val fname = fst (dest_Free head)
krauss@23189
   205
          handle TERM _ => raise MalformedEquation geq
krauss@23189
   206
    in
krauss@23189
   207
      (fname, qs, gs, args, rhs)
krauss@23189
   208
    end
krauss@23189
   209
krauss@23189
   210
exception ArgumentCount of string
krauss@23189
   211
krauss@23189
   212
fun mk_arities fqgars =
krauss@23189
   213
    let fun f (fname, _, _, args, _) arities =
krauss@23189
   214
            let val k = length args
krauss@23189
   215
            in
krauss@23189
   216
              case Symtab.lookup arities fname of
krauss@23189
   217
                NONE => Symtab.update (fname, k) arities
krauss@23189
   218
              | SOME i => (if i = k then arities else raise ArgumentCount fname)
krauss@23189
   219
            end
krauss@23189
   220
    in
krauss@23189
   221
      fold f fqgars Symtab.empty
krauss@23189
   222
    end
krauss@23189
   223
krauss@23189
   224
krauss@23203
   225
(* Check for all sorts of errors in the input *)
krauss@23203
   226
fun check_defs ctxt fixes eqs =
krauss@23203
   227
    let
krauss@23203
   228
      val fnames = map (fst o fst) fixes
krauss@23203
   229
                                
krauss@23203
   230
      fun check geq = 
krauss@23203
   231
          let
krauss@23203
   232
            fun input_error msg = cat_lines [msg, ProofContext.string_of_term ctxt geq]
krauss@23203
   233
                                  
krauss@23203
   234
            val fqgar as (fname, qs, gs, args, rhs) = split_def geq
krauss@23203
   235
                                 
krauss@23203
   236
            val _ = fname mem fnames 
krauss@23203
   237
                    orelse error (input_error ("Head symbol of left hand side must be " ^ plural "" "one out of " fnames 
krauss@23203
   238
                                               ^ commas_quote fnames))
krauss@23203
   239
                                            
krauss@23203
   240
            fun add_bvs t is = add_loose_bnos (t, 0, is)
krauss@23203
   241
            val rvs = (add_bvs rhs [] \\ fold add_bvs args [])
krauss@23203
   242
                        |> map (fst o nth (rev qs))
krauss@23203
   243
                      
krauss@23203
   244
            val _ = null rvs orelse error (input_error ("Variable" ^ plural " " "s " rvs ^ commas_quote rvs
krauss@23203
   245
                                                        ^ " occur" ^ plural "s" "" rvs ^ " on right hand side only:"))
krauss@23203
   246
                                    
krauss@23819
   247
            val _ = forall (not o Term.exists_subterm (fn Free (n, _) => n mem fnames | _ => false)) gs 
krauss@23203
   248
                    orelse error (input_error "Recursive Calls not allowed in premises")
krauss@23203
   249
          in
krauss@23203
   250
            fqgar
krauss@23203
   251
          end
krauss@23203
   252
krauss@23203
   253
      val _ = mk_arities (map check eqs)
krauss@23203
   254
          handle ArgumentCount fname => 
krauss@23203
   255
                 error ("Function " ^ quote fname ^ " has different numbers of arguments in different equations")
krauss@23203
   256
    in
krauss@23203
   257
      ()
krauss@23203
   258
    end
krauss@23203
   259
krauss@23203
   260
(* Preprocessors *)
krauss@23203
   261
krauss@23203
   262
type fixes = ((string * typ) * mixfix) list
krauss@23203
   263
type 'a spec = ((bstring * Attrib.src list) * 'a list) list
krauss@23819
   264
type preproc = fundef_config -> bool list -> Proof.context -> fixes -> term spec 
krauss@23819
   265
               -> (term list * (thm list -> thm spec) * (thm list -> thm list list))
krauss@23819
   266
krauss@23819
   267
val fname_of = fst o dest_Free o fst o strip_comb o fst o HOLogic.dest_eq o HOLogic.dest_Trueprop o Logic.strip_imp_concl o snd o dest_all_all
krauss@23203
   268
krauss@23203
   269
fun empty_preproc check _ _ ctxt fixes spec =
krauss@23203
   270
    let 
krauss@23203
   271
      val (nas,tss) = split_list spec
krauss@23203
   272
      val _ = check ctxt fixes (flat tss)
krauss@23819
   273
      val ts = flat tss
krauss@23819
   274
      val fnames = map (fst o fst) fixes
krauss@23819
   275
      val indices = map (fn eq => find_index (curry op = (fname_of eq)) fnames) ts
krauss@23819
   276
krauss@23819
   277
      fun sort xs = partition_list (fn i => fn (j,_) => i = j) 0 (length fnames - 1) (indices ~~ xs)
krauss@23819
   278
                        |> map (map snd)
krauss@23203
   279
    in
krauss@23819
   280
      (ts, curry op ~~ nas o Library.unflat tss, sort)
krauss@23203
   281
    end
krauss@23203
   282
krauss@23203
   283
structure Preprocessor = GenericDataFun
krauss@23203
   284
(
krauss@23203
   285
  type T = preproc
wenzelm@23206
   286
  val empty : T = empty_preproc check_defs
krauss@23203
   287
  val extend = I
krauss@23203
   288
  fun merge _ (a, _) = a
krauss@23203
   289
);
krauss@23203
   290
krauss@23203
   291
val get_preproc = Preprocessor.get o Context.Proof
krauss@23203
   292
val set_preproc = Preprocessor.map o K
krauss@23203
   293
krauss@23203
   294
krauss@23203
   295
krauss@23203
   296
local 
krauss@23203
   297
  structure P = OuterParse and K = OuterKeyword 
krauss@23203
   298
krauss@23203
   299
  val opt_sequential = Scan.optional ((P.$$$ "(" |-- P.$$$ "sequential" --| P.$$$ ")") >> K true) false
krauss@23203
   300
                       
krauss@23203
   301
  val option_parser = (P.$$$ "sequential" >> K Sequential)
krauss@23203
   302
                   || ((P.reserved "default" |-- P.term) >> Default)
krauss@23203
   303
                   || (P.reserved "domintros" >> K DomIntros)
krauss@23203
   304
                   || (P.reserved "tailrec" >> K Tailrec)
krauss@23203
   305
                   || ((P.$$$ "in" |-- P.xname) >> Target)
krauss@23203
   306
krauss@23203
   307
  fun config_parser default = (Scan.optional (P.$$$ "(" |-- P.!!! (P.list1 (P.group "option" option_parser)) --| P.$$$ ")") [])
krauss@23203
   308
                              >> (fn opts => fold apply_opt opts default)
krauss@23203
   309
krauss@23203
   310
  val otherwise = P.$$$ "(" |-- P.$$$ "otherwise" --| P.$$$ ")"
krauss@23203
   311
krauss@23203
   312
  fun pipe_error t = P.!!! (Scan.fail_with (K (cat_lines ["Equations must be separated by " ^ quote "|", quote t])))
krauss@23203
   313
krauss@23203
   314
  val statement_ow = SpecParse.opt_thm_name ":" -- (P.prop -- Scan.optional (otherwise >> K true) false)
krauss@23203
   315
                     --| Scan.ahead ((P.term :-- pipe_error) || Scan.succeed ("",""))
krauss@23203
   316
krauss@23203
   317
  val statements_ow = P.enum1 "|" statement_ow
krauss@23203
   318
krauss@23203
   319
  val flags_statements = statements_ow
krauss@23203
   320
                         >> (fn sow => (map (snd o snd) sow, map (apsnd fst) sow))
krauss@23203
   321
in
krauss@23203
   322
  fun fundef_parser default_cfg = (config_parser default_cfg -- P.fixes --| P.$$$ "where" -- flags_statements)
krauss@23203
   323
end
krauss@23203
   324
krauss@23203
   325
wenzelm@23215
   326
end
krauss@19564
   327
end
krauss@19564
   328