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