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