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