src/HOL/Tools/primrec.ML
author haftmann
Tue Jun 23 18:10:39 2009 +0200 (2009-06-23)
changeset 31786 a5ad48ae17e5
parent 31784 bd3486c57ba3
child 31902 862ae16a799d
permissions -rw-r--r--
corrected handling of free variables in arguments
haftmann@31723
     1
(*  Title:      HOL/Tools/primrec.ML
haftmann@25557
     2
    Author:     Stefan Berghofer, TU Muenchen; Norbert Voelker, FernUni Hagen;
haftmann@25557
     3
                Florian Haftmann, TU Muenchen
berghofe@5178
     4
wenzelm@6359
     5
Package for defining functions on datatypes by primitive recursion.
berghofe@5178
     6
*)
berghofe@5178
     7
haftmann@31723
     8
signature PRIMREC =
berghofe@5178
     9
sig
haftmann@29581
    10
  val add_primrec: (binding * typ option * mixfix) list ->
wenzelm@28084
    11
    (Attrib.binding * term) list -> local_theory -> thm list * local_theory
wenzelm@30487
    12
  val add_primrec_cmd: (binding * string option * mixfix) list ->
wenzelm@30487
    13
    (Attrib.binding * string) list -> local_theory -> thm list * local_theory
haftmann@29581
    14
  val add_primrec_global: (binding * typ option * mixfix) list ->
wenzelm@28084
    15
    (Attrib.binding * term) list -> theory -> thm list * theory
berghofe@26679
    16
  val add_primrec_overloaded: (string * (string * typ) * bool) list ->
haftmann@29581
    17
    (binding * typ option * mixfix) list ->
wenzelm@28084
    18
    (Attrib.binding * term) list -> theory -> thm list * theory
haftmann@31269
    19
  val add_primrec_simple: ((binding * typ) * mixfix) list -> term list ->
haftmann@31262
    20
    local_theory -> (string * thm list list) * local_theory
berghofe@5178
    21
end;
berghofe@5178
    22
haftmann@31723
    23
structure Primrec : PRIMREC =
berghofe@5178
    24
struct
berghofe@5178
    25
berghofe@5178
    26
open DatatypeAux;
berghofe@5178
    27
haftmann@25557
    28
exception PrimrecError of string * term option;
wenzelm@6359
    29
haftmann@25557
    30
fun primrec_error msg = raise PrimrecError (msg, NONE);
haftmann@25557
    31
fun primrec_error_eqn msg eqn = raise PrimrecError (msg, SOME eqn);
berghofe@23765
    32
haftmann@30451
    33
fun message s = if ! Toplevel.debug then tracing s else ();
berghofe@23765
    34
berghofe@23765
    35
berghofe@5178
    36
(* preprocessing of equations *)
berghofe@5178
    37
haftmann@25559
    38
fun process_eqn is_fixed spec rec_fns =
berghofe@5178
    39
  let
haftmann@25566
    40
    val (vs, Ts) = split_list (strip_qnt_vars "all" spec);
haftmann@25557
    41
    val body = strip_qnt_body "all" spec;
haftmann@25566
    42
    val (vs', _) = Name.variants vs (Name.make_context (fold_aterms
haftmann@25566
    43
      (fn Free (v, _) => insert (op =) v | _ => I) body []));
haftmann@25566
    44
    val eqn = curry subst_bounds (map2 (curry Free) vs' Ts |> rev) body;
haftmann@25557
    45
    val (lhs, rhs) = HOLogic.dest_eq (HOLogic.dest_Trueprop eqn)
haftmann@25557
    46
      handle TERM _ => primrec_error "not a proper equation";
berghofe@5178
    47
    val (recfun, args) = strip_comb lhs;
haftmann@25557
    48
    val fname = case recfun of Free (v, _) => if is_fixed v then v
haftmann@25557
    49
          else primrec_error "illegal head of function equation"
haftmann@25557
    50
      | _ => primrec_error "illegal head of function equation";
berghofe@5178
    51
berghofe@5178
    52
    val (ls', rest)  = take_prefix is_Free args;
berghofe@5178
    53
    val (middle, rs') = take_suffix is_Free rest;
berghofe@5178
    54
    val rpos = length ls';
berghofe@5178
    55
haftmann@25557
    56
    val (constr, cargs') = if null middle then primrec_error "constructor missing"
berghofe@5178
    57
      else strip_comb (hd middle);
berghofe@5178
    58
    val (cname, T) = dest_Const constr
haftmann@25557
    59
      handle TERM _ => primrec_error "ill-formed constructor";
berghofe@7016
    60
    val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
haftmann@25557
    61
      primrec_error "cannot determine datatype associated with function"
berghofe@5178
    62
haftmann@20176
    63
    val (ls, cargs, rs) =
haftmann@20176
    64
      (map dest_Free ls', map dest_Free cargs', map dest_Free rs')
haftmann@25557
    65
      handle TERM _ => primrec_error "illegal argument in pattern";
berghofe@5178
    66
    val lfrees = ls @ rs @ cargs;
berghofe@5178
    67
berghofe@12474
    68
    fun check_vars _ [] = ()
haftmann@25557
    69
      | check_vars s vars = primrec_error (s ^ commas_quote (map fst vars)) eqn;
berghofe@5178
    70
  in
wenzelm@22692
    71
    if length middle > 1 then
haftmann@25557
    72
      primrec_error "more than one non-variable in pattern"
berghofe@12474
    73
    else
wenzelm@18964
    74
     (check_vars "repeated variable names in pattern: " (duplicates (op =) lfrees);
berghofe@12474
    75
      check_vars "extra variables on rhs: "
wenzelm@29265
    76
        (map dest_Free (OldTerm.term_frees rhs) |> subtract (op =) lfrees
haftmann@25559
    77
          |> filter_out (is_fixed o fst));
haftmann@25557
    78
      case AList.lookup (op =) rec_fns fname of
skalberg@15531
    79
        NONE =>
haftmann@25557
    80
          (fname, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eqn))]))::rec_fns
skalberg@15531
    81
      | SOME (_, rpos', eqns) =>
wenzelm@17184
    82
          if AList.defined (op =) eqns cname then
haftmann@25557
    83
            primrec_error "constructor already occurred as pattern"
berghofe@5178
    84
          else if rpos <> rpos' then
haftmann@25557
    85
            primrec_error "position of recursive argument inconsistent"
berghofe@5178
    86
          else
haftmann@25557
    87
            AList.update (op =)
haftmann@25557
    88
              (fname, (tname, rpos, (cname, (ls, cargs, rs, rhs, eqn))::eqns))
haftmann@17314
    89
              rec_fns)
haftmann@25557
    90
  end handle PrimrecError (msg, NONE) => primrec_error_eqn msg spec;
berghofe@5178
    91
haftmann@25557
    92
fun process_fun descr eqns (i, fname) (fnames, fnss) =
berghofe@5178
    93
  let
haftmann@25557
    94
    val (_, (tname, _, constrs)) = nth descr i;
berghofe@5178
    95
berghofe@5178
    96
    (* substitute "fname ls x rs" by "y ls rs" for (x, (_, y)) in subs *)
berghofe@5178
    97
haftmann@21064
    98
    fun subst [] t fs = (t, fs)
haftmann@21064
    99
      | subst subs (Abs (a, T, t)) fs =
haftmann@21064
   100
          fs
haftmann@21064
   101
          |> subst subs t
haftmann@21064
   102
          |-> (fn t' => pair (Abs (a, T, t')))
haftmann@21064
   103
      | subst subs (t as (_ $ _)) fs =
haftmann@21064
   104
          let
haftmann@21064
   105
            val (f, ts) = strip_comb t;
berghofe@5178
   106
          in
haftmann@25557
   107
            if is_Free f
haftmann@25557
   108
              andalso member (fn ((v, _), (w, _)) => v = w) eqns (dest_Free f) then
berghofe@5178
   109
              let
haftmann@25557
   110
                val (fname', _) = dest_Free f;
haftmann@25557
   111
                val (_, rpos, _) = the (AList.lookup (op =) eqns fname');
haftmann@27301
   112
                val (ls, rs) = chop rpos ts
haftmann@27301
   113
                val (x', rs') = case rs
haftmann@27301
   114
                 of x' :: rs => (x', rs)
haftmann@27301
   115
                  | [] => primrec_error ("not enough arguments in recursive application\n"
haftmann@27301
   116
                      ^ "of function " ^ quote fname' ^ " on rhs");
haftmann@27301
   117
                val (x, xs) = strip_comb x';
haftmann@21064
   118
              in case AList.lookup (op =) subs x
haftmann@21064
   119
               of NONE =>
haftmann@21064
   120
                    fs
haftmann@21064
   121
                    |> fold_map (subst subs) ts
haftmann@21064
   122
                    |-> (fn ts' => pair (list_comb (f, ts')))
haftmann@21064
   123
                | SOME (i', y) =>
haftmann@21064
   124
                    fs
haftmann@27301
   125
                    |> fold_map (subst subs) (xs @ ls @ rs')
haftmann@25557
   126
                    ||> process_fun descr eqns (i', fname')
haftmann@21064
   127
                    |-> (fn ts' => pair (list_comb (y, ts')))
berghofe@5178
   128
              end
berghofe@5178
   129
            else
haftmann@21064
   130
              fs
haftmann@21064
   131
              |> fold_map (subst subs) (f :: ts)
haftmann@21064
   132
              |-> (fn (f'::ts') => pair (list_comb (f', ts')))
berghofe@5178
   133
          end
haftmann@21064
   134
      | subst _ t fs = (t, fs);
berghofe@5178
   135
berghofe@5178
   136
    (* translate rec equations into function arguments suitable for rec comb *)
berghofe@5178
   137
haftmann@25557
   138
    fun trans eqns (cname, cargs) (fnames', fnss', fns) =
wenzelm@17184
   139
      (case AList.lookup (op =) eqns cname of
skalberg@15531
   140
          NONE => (warning ("No equation for constructor " ^ quote cname ^
wenzelm@6427
   141
            "\nin definition of function " ^ quote fname);
haftmann@25557
   142
              (fnames', fnss', (Const ("HOL.undefined", dummyT))::fns))
skalberg@15531
   143
        | SOME (ls, cargs', rs, rhs, eq) =>
berghofe@5178
   144
            let
haftmann@21064
   145
              val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
berghofe@5178
   146
              val rargs = map fst recs;
wenzelm@22692
   147
              val subs = map (rpair dummyT o fst)
wenzelm@29276
   148
                (rev (Term.rename_wrt_term rhs rargs));
haftmann@27301
   149
              val (rhs', (fnames'', fnss'')) = subst (map2 (fn (x, y) => fn z =>
haftmann@27301
   150
                (Free x, (body_index y, Free z))) recs subs) rhs (fnames', fnss')
haftmann@25557
   151
                  handle PrimrecError (s, NONE) => primrec_error_eqn s eq
haftmann@25557
   152
            in (fnames'', fnss'',
haftmann@20176
   153
                (list_abs_free (cargs' @ subs @ ls @ rs, rhs'))::fns)
berghofe@5178
   154
            end)
berghofe@5178
   155
haftmann@25557
   156
  in (case AList.lookup (op =) fnames i of
skalberg@15531
   157
      NONE =>
haftmann@25557
   158
        if exists (fn (_, v) => fname = v) fnames then
haftmann@25557
   159
          primrec_error ("inconsistent functions for datatype " ^ quote tname)
berghofe@5178
   160
        else
berghofe@5178
   161
          let
haftmann@25557
   162
            val (_, _, eqns) = the (AList.lookup (op =) eqns fname);
haftmann@25557
   163
            val (fnames', fnss', fns) = fold_rev (trans eqns) constrs
haftmann@25557
   164
              ((i, fname)::fnames, fnss, [])
berghofe@5178
   165
          in
haftmann@25557
   166
            (fnames', (i, (fname, #1 (snd (hd eqns)), fns))::fnss')
berghofe@5178
   167
          end
haftmann@25557
   168
    | SOME fname' =>
haftmann@25557
   169
        if fname = fname' then (fnames, fnss)
haftmann@25557
   170
        else primrec_error ("inconsistent functions for datatype " ^ quote tname))
berghofe@5178
   171
  end;
berghofe@5178
   172
wenzelm@6359
   173
berghofe@5178
   174
(* prepare functions needed for definitions *)
berghofe@5178
   175
haftmann@21064
   176
fun get_fns fns ((i : int, (tname, _, constrs)), rec_name) (fs, defs) =
wenzelm@17184
   177
  case AList.lookup (op =) fns i of
skalberg@15531
   178
     NONE =>
berghofe@5178
   179
       let
haftmann@22480
   180
         val dummy_fns = map (fn (_, cargs) => Const ("HOL.undefined",
skalberg@15570
   181
           replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
berghofe@5178
   182
             dummyT ---> HOLogic.unitT)) constrs;
wenzelm@6427
   183
         val _ = warning ("No function definition for datatype " ^ quote tname)
berghofe@5178
   184
       in
berghofe@5178
   185
         (dummy_fns @ fs, defs)
berghofe@5178
   186
       end
haftmann@21064
   187
   | SOME (fname, ls, fs') => (fs' @ fs, (fname, ls, rec_name, tname) :: defs);
berghofe@5178
   188
wenzelm@6359
   189
berghofe@5178
   190
(* make definition *)
berghofe@5178
   191
haftmann@25557
   192
fun make_def ctxt fixes fs (fname, ls, rec_name, tname) =
berghofe@5178
   193
  let
haftmann@30451
   194
    val SOME (var, varT) = get_first (fn ((b, T), mx) =>
haftmann@30451
   195
      if Binding.name_of b = fname then SOME ((b, mx), T) else NONE) fixes;
wenzelm@30364
   196
    val def_name = Thm.def_name (Long_Name.base_name fname);
haftmann@30451
   197
    val raw_rhs = fold_rev (fn T => fn t => Abs ("", T, t)) (map snd ls @ [dummyT])
haftmann@30451
   198
      (list_comb (Const (rec_name, dummyT), fs @ map Bound (0 :: (length ls downto 1))))
haftmann@30451
   199
    val rhs = singleton (Syntax.check_terms ctxt)
haftmann@30451
   200
      (TypeInfer.constrain varT raw_rhs);
haftmann@28965
   201
  in (var, ((Binding.name def_name, []), rhs)) end;
berghofe@5178
   202
wenzelm@6359
   203
berghofe@5178
   204
(* find datatypes which contain all datatypes in tnames' *)
berghofe@5178
   205
haftmann@31737
   206
fun find_dts (dt_info : info Symtab.table) _ [] = []
berghofe@5178
   207
  | find_dts dt_info tnames' (tname::tnames) =
wenzelm@17412
   208
      (case Symtab.lookup dt_info tname of
haftmann@25557
   209
          NONE => primrec_error (quote tname ^ " is not a datatype")
skalberg@15531
   210
        | SOME dt =>
berghofe@5178
   211
            if tnames' subset (map (#1 o snd) (#descr dt)) then
berghofe@5178
   212
              (tname, dt)::(find_dts dt_info tnames' tnames)
berghofe@5178
   213
            else find_dts dt_info tnames' tnames);
berghofe@5178
   214
haftmann@25557
   215
haftmann@31262
   216
(* distill primitive definition(s) from primrec specification *)
haftmann@25557
   217
haftmann@31262
   218
fun distill lthy fixes eqs = 
haftmann@25557
   219
  let
haftmann@25559
   220
    val eqns = fold_rev (process_eqn (fn v => Variable.is_fixed lthy v
haftmann@31262
   221
      orelse exists (fn ((w, _), _) => v = Binding.name_of w) fixes)) eqs [];
haftmann@25557
   222
    val tnames = distinct (op =) (map (#1 o snd) eqns);
haftmann@31784
   223
    val dts = find_dts (Datatype.get_all (ProofContext.theory_of lthy)) tnames tnames;
haftmann@25557
   224
    val main_fns = map (fn (tname, {index, ...}) =>
haftmann@25557
   225
      (index, (fst o the o find_first (fn (_, x) => #1 x = tname)) eqns)) dts;
wenzelm@22692
   226
    val {descr, rec_names, rec_rewrites, ...} =
haftmann@25557
   227
      if null dts then primrec_error
haftmann@25557
   228
        ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
haftmann@18362
   229
      else snd (hd dts);
haftmann@25557
   230
    val (fnames, fnss) = fold_rev (process_fun descr eqns) main_fns ([], []);
haftmann@31262
   231
    val (fs, raw_defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
haftmann@31262
   232
    val defs = map (make_def lthy fixes fs) raw_defs;
haftmann@31262
   233
    val names = map snd fnames;
haftmann@31262
   234
    val names_eqns = map fst eqns;
haftmann@31262
   235
    val _ = if gen_eq_set (op =) (names, names_eqns) then ()
haftmann@31262
   236
      else primrec_error ("functions " ^ commas_quote names_eqns ^
haftmann@25557
   237
        "\nare not mutually recursive");
haftmann@31262
   238
    val rec_rewrites' = map mk_meta_eq rec_rewrites;
haftmann@31262
   239
    val prefix = space_implode "_" (map (Long_Name.base_name o #1) raw_defs);
haftmann@31262
   240
    fun prove lthy defs =
haftmann@31262
   241
      let
haftmann@31786
   242
        val frees = (fold o Term.fold_aterms) (fn Free (x, _) =>
haftmann@31786
   243
          if Variable.is_fixed lthy x then I else insert (op =) x | _ => I) eqs [];
haftmann@31262
   244
        val rewrites = rec_rewrites' @ map (snd o snd) defs;
haftmann@31262
   245
        fun tac _ = EVERY [rewrite_goals_tac rewrites, rtac refl 1];
haftmann@31262
   246
        val _ = message ("Proving equations for primrec function(s) " ^ commas_quote names);
haftmann@31786
   247
      in map (fn eq => [Goal.prove lthy frees [] eq tac]) eqs end;
haftmann@31262
   248
  in ((prefix, (fs, defs)), prove) end
haftmann@31262
   249
  handle PrimrecError (msg, some_eqn) =>
haftmann@31262
   250
    error ("Primrec definition error:\n" ^ msg ^ (case some_eqn
haftmann@31262
   251
     of SOME eqn => "\nin\n" ^ quote (Syntax.string_of_term lthy eqn)
haftmann@31262
   252
      | NONE => ""));
haftmann@31262
   253
haftmann@31262
   254
haftmann@31262
   255
(* primrec definition *)
haftmann@31262
   256
haftmann@31269
   257
fun add_primrec_simple fixes ts lthy =
haftmann@31262
   258
  let
haftmann@31269
   259
    val ((prefix, (fs, defs)), prove) = distill lthy fixes ts;
haftmann@31262
   260
  in
haftmann@31262
   261
    lthy
haftmann@31262
   262
    |> fold_map (LocalTheory.define Thm.definitionK) defs
haftmann@31262
   263
    |-> (fn defs => `(fn lthy => (prefix, prove lthy defs)))
haftmann@31262
   264
  end;
haftmann@31262
   265
haftmann@31262
   266
local
haftmann@31262
   267
haftmann@31262
   268
fun gen_primrec set_group prep_spec raw_fixes raw_spec lthy =
haftmann@31262
   269
  let
haftmann@31262
   270
    val (fixes, spec) = fst (prep_spec raw_fixes raw_spec lthy);
haftmann@31262
   271
    fun attr_bindings prefix = map (fn ((b, attrs), _) =>
haftmann@31262
   272
      (Binding.qualify false prefix b, Code.add_default_eqn_attrib :: attrs)) spec;
haftmann@31296
   273
    fun simp_attr_binding prefix = (Binding.qualify true prefix (Binding.name "simps"),
haftmann@31262
   274
      map (Attrib.internal o K)
haftmann@31262
   275
        [Simplifier.simp_add, Nitpick_Const_Simp_Thms.add, Quickcheck_RecFun_Simp_Thms.add]);
berghofe@8480
   276
  in
haftmann@25557
   277
    lthy
wenzelm@26129
   278
    |> set_group ? LocalTheory.set_group (serial_string ())
haftmann@31269
   279
    |> add_primrec_simple fixes (map snd spec)
haftmann@31262
   280
    |-> (fn (prefix, simps) => fold_map (LocalTheory.note Thm.generatedK)
haftmann@31262
   281
          (attr_bindings prefix ~~ simps)
haftmann@31262
   282
    #-> (fn simps' => LocalTheory.note Thm.generatedK
haftmann@31262
   283
          (simp_attr_binding prefix, maps snd simps')))
haftmann@25604
   284
    |>> snd
haftmann@31262
   285
  end;
haftmann@20841
   286
haftmann@20841
   287
in
haftmann@20841
   288
wenzelm@30487
   289
val add_primrec = gen_primrec false Specification.check_spec;
wenzelm@30487
   290
val add_primrec_cmd = gen_primrec true Specification.read_spec;
haftmann@20841
   291
wenzelm@22692
   292
end;
wenzelm@19688
   293
berghofe@26679
   294
fun add_primrec_global fixes specs thy =
berghofe@26679
   295
  let
berghofe@26679
   296
    val lthy = TheoryTarget.init NONE thy;
berghofe@26679
   297
    val (simps, lthy') = add_primrec fixes specs lthy;
berghofe@26679
   298
    val simps' = ProofContext.export lthy' lthy simps;
wenzelm@28394
   299
  in (simps', LocalTheory.exit_global lthy') end;
berghofe@26679
   300
berghofe@26679
   301
fun add_primrec_overloaded ops fixes specs thy =
berghofe@26679
   302
  let
berghofe@26679
   303
    val lthy = TheoryTarget.overloading ops thy;
berghofe@26679
   304
    val (simps, lthy') = add_primrec fixes specs lthy;
berghofe@26679
   305
    val simps' = ProofContext.export lthy' lthy simps;
wenzelm@28394
   306
  in (simps', LocalTheory.exit_global lthy') end;
berghofe@26679
   307
berghofe@5178
   308
wenzelm@6359
   309
(* outer syntax *)
wenzelm@6359
   310
wenzelm@17057
   311
local structure P = OuterParse and K = OuterKeyword in
wenzelm@6359
   312
wenzelm@19688
   313
val opt_unchecked_name =
wenzelm@19688
   314
  Scan.optional (P.$$$ "(" |-- P.!!!
wenzelm@19688
   315
    (((P.$$$ "unchecked" >> K true) -- Scan.optional P.name "" ||
wenzelm@19688
   316
      P.name >> pair false) --| P.$$$ ")")) (false, "");
wenzelm@19688
   317
haftmann@25557
   318
val old_primrec_decl =
wenzelm@30223
   319
  opt_unchecked_name -- Scan.repeat1 ((SpecParse.opt_thm_name ":" >> apfst Binding.name_of) -- P.prop);
wenzelm@6359
   320
wenzelm@30487
   321
val primrec_decl = P.opt_target -- P.fixes -- SpecParse.where_alt_specs;
haftmann@25557
   322
wenzelm@24867
   323
val _ =
wenzelm@6723
   324
  OuterSyntax.command "primrec" "define primitive recursive functions on datatypes" K.thy_decl
wenzelm@30487
   325
    ((primrec_decl >> (fn ((opt_target, fixes), specs) =>
wenzelm@30487
   326
      Toplevel.local_theory opt_target (add_primrec_cmd fixes specs #> snd)))
haftmann@25557
   327
    || (old_primrec_decl >> (fn ((unchecked, alt_name), eqns) =>
haftmann@20176
   328
      Toplevel.theory (snd o
haftmann@31723
   329
        (if unchecked then OldPrimrec.add_primrec_unchecked else OldPrimrec.add_primrec)
wenzelm@30487
   330
          alt_name (map P.triple_swap eqns)))));
wenzelm@6359
   331
berghofe@5178
   332
end;
wenzelm@6384
   333
wenzelm@6384
   334
end;