src/HOL/Tools/primrec_package.ML
author wenzelm
Sun Apr 15 14:31:49 2007 +0200 (2007-04-15)
changeset 22692 1e057a3f087d
parent 22480 b20bc8029edb
child 22728 ecbbdf50df2f
permissions -rw-r--r--
proper ProofContext.infer_types;
berghofe@5719
     1
(*  Title:      HOL/Tools/primrec_package.ML
berghofe@5178
     2
    ID:         $Id$
wenzelm@11539
     3
    Author:     Stefan Berghofer, TU Muenchen and Norbert Voelker, FernUni Hagen
berghofe@5178
     4
wenzelm@6359
     5
Package for defining functions on datatypes by primitive recursion.
berghofe@5178
     6
*)
berghofe@5178
     7
berghofe@5178
     8
signature PRIMREC_PACKAGE =
berghofe@5178
     9
sig
wenzelm@6427
    10
  val quiet_mode: bool ref
wenzelm@15703
    11
  val add_primrec: string -> ((bstring * string) * Attrib.src list) list
haftmann@20176
    12
    -> theory -> thm list * theory
wenzelm@19688
    13
  val add_primrec_unchecked: string -> ((bstring * string) * Attrib.src list) list
haftmann@20176
    14
    -> theory -> thm list * theory
wenzelm@18728
    15
  val add_primrec_i: string -> ((bstring * term) * attribute list) list
haftmann@20176
    16
    -> theory -> thm list * theory
wenzelm@19636
    17
  val add_primrec_unchecked_i: string -> ((bstring * term) * attribute list) list
haftmann@20176
    18
    -> theory -> thm list * theory
wenzelm@22692
    19
  (* FIXME !? *)
haftmann@20841
    20
  val gen_primrec: ((bstring * attribute list) * thm list -> theory -> (bstring * thm list) * theory)
haftmann@20841
    21
    -> ((bstring * attribute list) * term -> theory -> (bstring * thm) * theory)
haftmann@20841
    22
    -> string -> ((bstring * attribute list) * term) list
haftmann@20841
    23
    -> theory -> thm list * theory;
berghofe@5178
    24
end;
berghofe@5178
    25
berghofe@5178
    26
structure PrimrecPackage : PRIMREC_PACKAGE =
berghofe@5178
    27
struct
berghofe@5178
    28
berghofe@5178
    29
open DatatypeAux;
berghofe@5178
    30
berghofe@5178
    31
exception RecError of string;
berghofe@5178
    32
berghofe@5178
    33
fun primrec_err s = error ("Primrec definition error:\n" ^ s);
haftmann@20176
    34
fun primrec_eq_err thy s eq =
haftmann@20176
    35
  primrec_err (s ^ "\nin\n" ^ quote (Sign.string_of_term thy eq));
wenzelm@6427
    36
wenzelm@6427
    37
wenzelm@6427
    38
(* messages *)
wenzelm@6427
    39
wenzelm@6427
    40
val quiet_mode = ref false;
wenzelm@6427
    41
fun message s = if ! quiet_mode then () else writeln s;
berghofe@5178
    42
wenzelm@6359
    43
berghofe@5178
    44
(* preprocessing of equations *)
berghofe@5178
    45
wenzelm@22692
    46
fun process_eqn thy eq rec_fns =
berghofe@5178
    47
  let
wenzelm@22692
    48
    val (lhs, rhs) =
haftmann@20176
    49
      if null (term_vars eq) then
haftmann@20176
    50
        HOLogic.dest_eq (HOLogic.dest_Trueprop eq)
haftmann@20176
    51
        handle TERM _ => raise RecError "not a proper equation"
haftmann@20176
    52
      else raise RecError "illegal schematic variable(s)";
berghofe@5178
    53
berghofe@5178
    54
    val (recfun, args) = strip_comb lhs;
wenzelm@22692
    55
    val fnameT = dest_Const recfun handle TERM _ =>
berghofe@5178
    56
      raise RecError "function is not declared as constant in theory";
berghofe@5178
    57
berghofe@5178
    58
    val (ls', rest)  = take_prefix is_Free args;
berghofe@5178
    59
    val (middle, rs') = take_suffix is_Free rest;
berghofe@5178
    60
    val rpos = length ls';
berghofe@5178
    61
berghofe@5178
    62
    val (constr, cargs') = if null middle then raise RecError "constructor missing"
berghofe@5178
    63
      else strip_comb (hd middle);
berghofe@5178
    64
    val (cname, T) = dest_Const constr
berghofe@7016
    65
      handle TERM _ => raise RecError "ill-formed constructor";
berghofe@7016
    66
    val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
berghofe@5178
    67
      raise RecError "cannot determine datatype associated with function"
berghofe@5178
    68
haftmann@20176
    69
    val (ls, cargs, rs) =
haftmann@20176
    70
      (map dest_Free ls', map dest_Free cargs', map dest_Free rs')
berghofe@7016
    71
      handle TERM _ => raise RecError "illegal argument in pattern";
berghofe@5178
    72
    val lfrees = ls @ rs @ cargs;
berghofe@5178
    73
berghofe@12474
    74
    fun check_vars _ [] = ()
berghofe@12474
    75
      | check_vars s vars = raise RecError (s ^ commas_quote (map fst vars))
berghofe@5178
    76
  in
wenzelm@22692
    77
    if length middle > 1 then
berghofe@5178
    78
      raise RecError "more than one non-variable in pattern"
berghofe@12474
    79
    else
wenzelm@18964
    80
     (check_vars "repeated variable names in pattern: " (duplicates (op =) lfrees);
berghofe@12474
    81
      check_vars "extra variables on rhs: "
berghofe@12474
    82
        (map dest_Free (term_frees rhs) \\ lfrees);
wenzelm@17184
    83
      case AList.lookup (op =) rec_fns fnameT of
skalberg@15531
    84
        NONE =>
berghofe@16765
    85
          (fnameT, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
skalberg@15531
    86
      | SOME (_, rpos', eqns) =>
wenzelm@17184
    87
          if AList.defined (op =) eqns cname then
paulson@6037
    88
            raise RecError "constructor already occurred as pattern"
berghofe@5178
    89
          else if rpos <> rpos' then
berghofe@5178
    90
            raise RecError "position of recursive argument inconsistent"
berghofe@5178
    91
          else
haftmann@17314
    92
            AList.update (op =) (fnameT, (tname, rpos, (cname, (ls, cargs, rs, rhs, eq))::eqns))
haftmann@17314
    93
              rec_fns)
berghofe@5178
    94
  end
haftmann@20176
    95
  handle RecError s => primrec_eq_err thy s eq;
berghofe@5178
    96
haftmann@21064
    97
fun process_fun thy descr rec_eqns (i, fnameT as (fname, _)) (fnameTs, fnss) =
berghofe@5178
    98
  let
skalberg@15570
    99
    val (_, (tname, _, constrs)) = List.nth (descr, i);
berghofe@5178
   100
berghofe@5178
   101
    (* substitute "fname ls x rs" by "y ls rs" for (x, (_, y)) in subs *)
berghofe@5178
   102
haftmann@21064
   103
    fun subst [] t fs = (t, fs)
haftmann@21064
   104
      | subst subs (Abs (a, T, t)) fs =
haftmann@21064
   105
          fs
haftmann@21064
   106
          |> subst subs t
haftmann@21064
   107
          |-> (fn t' => pair (Abs (a, T, t')))
haftmann@21064
   108
      | subst subs (t as (_ $ _)) fs =
haftmann@21064
   109
          let
haftmann@21064
   110
            val (f, ts) = strip_comb t;
berghofe@5178
   111
          in
berghofe@16765
   112
            if is_Const f andalso dest_Const f mem map fst rec_eqns then
berghofe@5178
   113
              let
berghofe@16765
   114
                val fnameT' as (fname', _) = dest_Const f;
wenzelm@17184
   115
                val (_, rpos, _) = the (AList.lookup (op =) rec_eqns fnameT');
skalberg@15570
   116
                val ls = Library.take (rpos, ts);
skalberg@15570
   117
                val rest = Library.drop (rpos, ts);
berghofe@7016
   118
                val (x', rs) = (hd rest, tl rest)
skalberg@15570
   119
                  handle Empty => raise RecError ("not enough arguments\
berghofe@7016
   120
                   \ in recursive application\nof function " ^ quote fname' ^ " on rhs");
berghofe@7016
   121
                val (x, xs) = strip_comb x'
haftmann@21064
   122
              in case AList.lookup (op =) subs x
haftmann@21064
   123
               of NONE =>
haftmann@21064
   124
                    fs
haftmann@21064
   125
                    |> fold_map (subst subs) ts
haftmann@21064
   126
                    |-> (fn ts' => pair (list_comb (f, ts')))
haftmann@21064
   127
                | SOME (i', y) =>
haftmann@21064
   128
                    fs
haftmann@21064
   129
                    |> fold_map (subst subs) (xs @ ls @ rs)
haftmann@21064
   130
                    ||> process_fun thy descr rec_eqns (i', fnameT')
haftmann@21064
   131
                    |-> (fn ts' => pair (list_comb (y, ts')))
berghofe@5178
   132
              end
berghofe@5178
   133
            else
haftmann@21064
   134
              fs
haftmann@21064
   135
              |> fold_map (subst subs) (f :: ts)
haftmann@21064
   136
              |-> (fn (f'::ts') => pair (list_comb (f', ts')))
berghofe@5178
   137
          end
haftmann@21064
   138
      | subst _ t fs = (t, fs);
berghofe@5178
   139
berghofe@5178
   140
    (* translate rec equations into function arguments suitable for rec comb *)
berghofe@5178
   141
haftmann@21064
   142
    fun trans eqns (cname, cargs) (fnameTs', fnss', fns) =
wenzelm@17184
   143
      (case AList.lookup (op =) eqns cname of
skalberg@15531
   144
          NONE => (warning ("No equation for constructor " ^ quote cname ^
wenzelm@6427
   145
            "\nin definition of function " ^ quote fname);
haftmann@22480
   146
              (fnameTs', fnss', (Const ("HOL.undefined", dummyT))::fns))
skalberg@15531
   147
        | SOME (ls, cargs', rs, rhs, eq) =>
berghofe@5178
   148
            let
haftmann@21064
   149
              val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
berghofe@5178
   150
              val rargs = map fst recs;
wenzelm@22692
   151
              val subs = map (rpair dummyT o fst)
haftmann@20176
   152
                (rev (rename_wrt_term rhs rargs));
wenzelm@22692
   153
              val (rhs', (fnameTs'', fnss'')) =
haftmann@20176
   154
                  (subst (map (fn ((x, y), z) =>
haftmann@20176
   155
                               (Free x, (body_index y, Free z)))
haftmann@21064
   156
                          (recs ~~ subs)) rhs (fnameTs', fnss'))
haftmann@20176
   157
                  handle RecError s => primrec_eq_err thy s eq
wenzelm@22692
   158
            in (fnameTs'', fnss'',
haftmann@20176
   159
                (list_abs_free (cargs' @ subs @ ls @ rs, rhs'))::fns)
berghofe@5178
   160
            end)
berghofe@5178
   161
wenzelm@17184
   162
  in (case AList.lookup (op =) fnameTs i of
skalberg@15531
   163
      NONE =>
berghofe@16765
   164
        if exists (equal fnameT o snd) fnameTs then
wenzelm@6427
   165
          raise RecError ("inconsistent functions for datatype " ^ quote tname)
berghofe@5178
   166
        else
berghofe@5178
   167
          let
wenzelm@17184
   168
            val (_, _, eqns) = the (AList.lookup (op =) rec_eqns fnameT);
haftmann@21064
   169
            val (fnameTs', fnss', fns) = fold_rev (trans eqns) constrs
wenzelm@22692
   170
              ((i, fnameT)::fnameTs, fnss, [])
berghofe@5178
   171
          in
berghofe@16765
   172
            (fnameTs', (i, (fname, #1 (snd (hd eqns)), fns))::fnss')
berghofe@5178
   173
          end
berghofe@16765
   174
    | SOME fnameT' =>
berghofe@16765
   175
        if fnameT = fnameT' then (fnameTs, fnss)
wenzelm@6427
   176
        else raise RecError ("inconsistent functions for datatype " ^ quote tname))
berghofe@5178
   177
  end;
berghofe@5178
   178
wenzelm@6359
   179
berghofe@5178
   180
(* prepare functions needed for definitions *)
berghofe@5178
   181
haftmann@21064
   182
fun get_fns fns ((i : int, (tname, _, constrs)), rec_name) (fs, defs) =
wenzelm@17184
   183
  case AList.lookup (op =) fns i of
skalberg@15531
   184
     NONE =>
berghofe@5178
   185
       let
haftmann@22480
   186
         val dummy_fns = map (fn (_, cargs) => Const ("HOL.undefined",
skalberg@15570
   187
           replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
berghofe@5178
   188
             dummyT ---> HOLogic.unitT)) constrs;
wenzelm@6427
   189
         val _ = warning ("No function definition for datatype " ^ quote tname)
berghofe@5178
   190
       in
berghofe@5178
   191
         (dummy_fns @ fs, defs)
berghofe@5178
   192
       end
haftmann@21064
   193
   | SOME (fname, ls, fs') => (fs' @ fs, (fname, ls, rec_name, tname) :: defs);
berghofe@5178
   194
wenzelm@6359
   195
berghofe@5178
   196
(* make definition *)
berghofe@5178
   197
haftmann@20176
   198
fun make_def thy fs (fname, ls, rec_name, tname) =
berghofe@5178
   199
  let
haftmann@21064
   200
    val rhs = fold_rev (fn T => fn t => Abs ("", T, t))
haftmann@21064
   201
                    ((map snd ls) @ [dummyT])
haftmann@20176
   202
                    (list_comb (Const (rec_name, dummyT),
haftmann@20176
   203
                                fs @ map Bound (0 ::(length ls downto 1))))
wenzelm@22692
   204
    val def_name = Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def";
wenzelm@22692
   205
    val def_prop =
wenzelm@22692
   206
      singleton (ProofContext.infer_types (ProofContext.init thy))
wenzelm@22692
   207
        (Logic.mk_equals (Const (fname, dummyT), rhs), propT) |> #1;
wenzelm@22692
   208
  in (def_name, def_prop) end;
berghofe@5178
   209
wenzelm@6359
   210
berghofe@5178
   211
(* find datatypes which contain all datatypes in tnames' *)
berghofe@5178
   212
berghofe@5178
   213
fun find_dts (dt_info : datatype_info Symtab.table) _ [] = []
berghofe@5178
   214
  | find_dts dt_info tnames' (tname::tnames) =
wenzelm@17412
   215
      (case Symtab.lookup dt_info tname of
skalberg@15531
   216
          NONE => primrec_err (quote tname ^ " is not a datatype")
skalberg@15531
   217
        | SOME dt =>
berghofe@5178
   218
            if tnames' subset (map (#1 o snd) (#descr dt)) then
berghofe@5178
   219
              (tname, dt)::(find_dts dt_info tnames' tnames)
berghofe@5178
   220
            else find_dts dt_info tnames' tnames);
berghofe@5178
   221
wenzelm@8432
   222
fun prepare_induct ({descr, induction, ...}: datatype_info) rec_eqns =
wenzelm@8432
   223
  let
wenzelm@8432
   224
    fun constrs_of (_, (_, _, cs)) =
wenzelm@8432
   225
      map (fn (cname:string, (_, cargs, _, _, _)) => (cname, map fst cargs)) cs;
wenzelm@17184
   226
    val params_of = these o AList.lookup (op =) (List.concat (map constrs_of rec_eqns));
wenzelm@8432
   227
  in
wenzelm@8432
   228
    induction
skalberg@15570
   229
    |> RuleCases.rename_params (map params_of (List.concat (map (map #1 o #3 o #2) descr)))
wenzelm@10525
   230
    |> RuleCases.save induction
wenzelm@8432
   231
  end;
wenzelm@8432
   232
haftmann@20841
   233
local
haftmann@20841
   234
haftmann@20841
   235
fun gen_primrec_i note def alt_name eqns_atts thy =
berghofe@5178
   236
  let
haftmann@20841
   237
    val (eqns, atts) = split_list eqns_atts;
berghofe@5178
   238
    val dt_info = DatatypePackage.get_datatypes thy;
haftmann@21064
   239
    val rec_eqns = fold_rev (process_eqn thy o snd) eqns [] ;
wenzelm@19046
   240
    val tnames = distinct (op =) (map (#1 o snd) rec_eqns);
berghofe@5178
   241
    val dts = find_dts dt_info tnames tnames;
wenzelm@22692
   242
    val main_fns =
haftmann@18362
   243
      map (fn (tname, {index, ...}) =>
wenzelm@22692
   244
        (index,
haftmann@18362
   245
          (fst o the o find_first (fn f => (#1 o snd) f = tname)) rec_eqns))
haftmann@18362
   246
      dts;
wenzelm@22692
   247
    val {descr, rec_names, rec_rewrites, ...} =
haftmann@18362
   248
      if null dts then
haftmann@18362
   249
        primrec_err ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
haftmann@18362
   250
      else snd (hd dts);
haftmann@20176
   251
    val (fnameTs, fnss) =
haftmann@21064
   252
      fold_rev (process_fun thy descr rec_eqns) main_fns ([], []);
haftmann@21064
   253
    val (fs, defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
haftmann@20176
   254
    val defs' = map (make_def thy fs) defs;
berghofe@16765
   255
    val nameTs1 = map snd fnameTs;
berghofe@16765
   256
    val nameTs2 = map fst rec_eqns;
haftmann@20841
   257
    val _ = if gen_eq_set (op =) (nameTs1, nameTs2) then ()
haftmann@20841
   258
            else primrec_err ("functions " ^ commas_quote (map fst nameTs2) ^
haftmann@20841
   259
              "\nare not mutually recursive");
wenzelm@8432
   260
    val primrec_name =
wenzelm@8432
   261
      if alt_name = "" then (space_implode "_" (map (Sign.base_name o #1) defs)) else alt_name;
haftmann@20841
   262
    val (defs_thms', thy') =
haftmann@20841
   263
      thy
haftmann@20841
   264
      |> Theory.add_path primrec_name
haftmann@20841
   265
      |> fold_map def (map (fn (name, t) => ((name, []), t)) defs');
haftmann@20841
   266
    val rewrites = (map mk_meta_eq rec_rewrites) @ map snd defs_thms';
berghofe@16765
   267
    val _ = message ("Proving equations for primrec function(s) " ^
berghofe@16765
   268
      commas_quote (map fst nameTs1) ^ " ...");
wenzelm@20046
   269
    val simps = map (fn (_, t) => Goal.prove_global thy' [] [] t
wenzelm@20046
   270
        (fn _ => EVERY [rewrite_goals_tac rewrites, rtac refl 1])) eqns;
haftmann@20841
   271
    val (simps', thy'') =
haftmann@20841
   272
      thy'
haftmann@20841
   273
      |> fold_map note ((map fst eqns ~~ atts) ~~ map single simps);
haftmann@20841
   274
    val simps'' = maps snd simps';
berghofe@8480
   275
  in
haftmann@20176
   276
    thy''
haftmann@20841
   277
    |> note (("simps", [Simplifier.simp_add, RecfunCodegen.add NONE]), simps'')
haftmann@20841
   278
    |> snd
haftmann@20841
   279
    |> note (("induct", []), [prepare_induct (#2 (hd dts)) rec_eqns])
haftmann@20841
   280
    |> snd
haftmann@20176
   281
    |> Theory.parent_path
haftmann@20841
   282
    |> pair simps''
berghofe@8480
   283
  end;
wenzelm@6359
   284
haftmann@20841
   285
fun gen_primrec note def alt_name eqns thy =
berghofe@7016
   286
  let
berghofe@7016
   287
    val ((names, strings), srcss) = apfst split_list (split_list eqns);
wenzelm@18728
   288
    val atts = map (map (Attrib.attribute thy)) srcss;
haftmann@20176
   289
    val eqn_ts = map (fn s => term_of (Thm.read_cterm thy (s, propT))
wenzelm@18678
   290
      handle ERROR msg => cat_error msg ("The error(s) above occurred for " ^ s)) strings;
berghofe@7016
   291
    val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop eq)))
haftmann@20176
   292
      handle TERM _ => primrec_eq_err thy "not a proper equation" eq) eqn_ts;
berghofe@21022
   293
    val (_, eqn_ts') = OldInductivePackage.unify_consts thy rec_ts eqn_ts
berghofe@7016
   294
  in
haftmann@20841
   295
    gen_primrec_i note def alt_name (names ~~ eqn_ts' ~~ atts) thy
berghofe@7016
   296
  end;
wenzelm@6359
   297
haftmann@20841
   298
fun thy_note ((name, atts), thms) =
haftmann@20841
   299
  PureThy.add_thmss [((name, thms), atts)] #-> (fn [thms] => pair (name, thms));
haftmann@20841
   300
fun thy_def false ((name, atts), t) =
haftmann@20841
   301
      PureThy.add_defs_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm))
haftmann@20841
   302
  | thy_def true ((name, atts), t) =
haftmann@20841
   303
      PureThy.add_defs_unchecked_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm));
haftmann@20841
   304
haftmann@20841
   305
in
haftmann@20841
   306
haftmann@20841
   307
val add_primrec = gen_primrec thy_note (thy_def false);
haftmann@20841
   308
val add_primrec_unchecked = gen_primrec thy_note (thy_def true);
haftmann@20841
   309
val add_primrec_i = gen_primrec_i thy_note (thy_def false);
haftmann@20841
   310
val add_primrec_unchecked_i = gen_primrec_i thy_note (thy_def true);
haftmann@20841
   311
fun gen_primrec note def alt_name specs =
haftmann@20841
   312
  gen_primrec_i note def alt_name (map (fn ((name, t), atts) => ((name, atts), t)) specs);
haftmann@20841
   313
wenzelm@22692
   314
end;
wenzelm@19688
   315
berghofe@5178
   316
wenzelm@6359
   317
(* outer syntax *)
wenzelm@6359
   318
wenzelm@17057
   319
local structure P = OuterParse and K = OuterKeyword in
wenzelm@6359
   320
wenzelm@19688
   321
val opt_unchecked_name =
wenzelm@19688
   322
  Scan.optional (P.$$$ "(" |-- P.!!!
wenzelm@19688
   323
    (((P.$$$ "unchecked" >> K true) -- Scan.optional P.name "" ||
wenzelm@19688
   324
      P.name >> pair false) --| P.$$$ ")")) (false, "");
wenzelm@19688
   325
wenzelm@6359
   326
val primrec_decl =
wenzelm@22101
   327
  opt_unchecked_name -- Scan.repeat1 (SpecParse.opt_thm_name ":" -- P.prop);
wenzelm@6359
   328
wenzelm@6359
   329
val primrecP =
wenzelm@6723
   330
  OuterSyntax.command "primrec" "define primitive recursive functions on datatypes" K.thy_decl
wenzelm@19688
   331
    (primrec_decl >> (fn ((unchecked, alt_name), eqns) =>
haftmann@20176
   332
      Toplevel.theory (snd o
wenzelm@19688
   333
        (if unchecked then add_primrec_unchecked else add_primrec) alt_name
wenzelm@19688
   334
          (map P.triple_swap eqns))));
wenzelm@6359
   335
wenzelm@6359
   336
val _ = OuterSyntax.add_parsers [primrecP];
berghofe@5178
   337
berghofe@5178
   338
end;
wenzelm@6384
   339
wenzelm@6384
   340
end;