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