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