src/HOL/Tools/primrec_package.ML
author berghofe
Fri Jul 16 13:24:41 1999 +0200 (1999-07-16)
changeset 7016 df54b5365477
parent 6729 b6e167580a32
child 7152 44d46a112127
permissions -rw-r--r--
- Now also supports arbitrarily branching datatypes.
- Fixed bug (in some rare cases, recursive constants were
inconsistently typed in different primrec equations).
berghofe@5719
     1
(*  Title:      HOL/Tools/primrec_package.ML
berghofe@5178
     2
    ID:         $Id$
berghofe@5719
     3
    Author:     Stefan Berghofer and Norbert Voelker
berghofe@5178
     4
    Copyright   1998  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
wenzelm@6427
    11
  val quiet_mode: bool ref
wenzelm@6425
    12
  val add_primrec: string -> ((bstring * string) * Args.src list) list
wenzelm@6359
    13
    -> theory -> theory * thm list
wenzelm@6425
    14
  val add_primrec_i: string -> ((bstring * term) * theory attribute list) list
wenzelm@6359
    15
    -> theory -> theory * thm list
berghofe@5178
    16
end;
berghofe@5178
    17
berghofe@5178
    18
structure PrimrecPackage : PRIMREC_PACKAGE =
berghofe@5178
    19
struct
berghofe@5178
    20
berghofe@5178
    21
open DatatypeAux;
berghofe@5178
    22
berghofe@5178
    23
exception RecError of string;
berghofe@5178
    24
berghofe@5178
    25
fun primrec_err s = error ("Primrec definition error:\n" ^ s);
berghofe@5178
    26
fun primrec_eq_err sign s eq =
wenzelm@6427
    27
  primrec_err (s ^ "\nin equation\n" ^ quote (Sign.string_of_term sign eq));
wenzelm@6427
    28
wenzelm@6427
    29
wenzelm@6427
    30
(* messages *)
wenzelm@6427
    31
wenzelm@6427
    32
val quiet_mode = ref false;
wenzelm@6427
    33
fun message s = if ! quiet_mode then () else writeln s;
berghofe@5178
    34
wenzelm@6359
    35
berghofe@5178
    36
(* preprocessing of equations *)
berghofe@5178
    37
berghofe@5178
    38
fun process_eqn sign (eq, rec_fns) = 
berghofe@5178
    39
  let
paulson@6032
    40
    val (lhs, rhs) = 
paulson@6032
    41
	if null (term_vars eq) then
paulson@6032
    42
	    HOLogic.dest_eq (HOLogic.dest_Trueprop eq)
berghofe@7016
    43
	      handle TERM _ => raise RecError "not a proper equation"
paulson@6032
    44
	else raise RecError "illegal schematic variable(s)";
berghofe@5178
    45
berghofe@5178
    46
    val (recfun, args) = strip_comb lhs;
berghofe@7016
    47
    val (fname, _) = dest_Const recfun handle TERM _ => 
berghofe@5178
    48
      raise RecError "function is not declared as constant in theory";
berghofe@5178
    49
berghofe@5178
    50
    val (ls', rest)  = take_prefix is_Free args;
berghofe@5178
    51
    val (middle, rs') = take_suffix is_Free rest;
berghofe@5178
    52
    val rpos = length ls';
berghofe@5178
    53
berghofe@5178
    54
    val (constr, cargs') = if null middle then raise RecError "constructor missing"
berghofe@5178
    55
      else strip_comb (hd middle);
berghofe@5178
    56
    val (cname, T) = dest_Const constr
berghofe@7016
    57
      handle TERM _ => raise RecError "ill-formed constructor";
berghofe@7016
    58
    val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
berghofe@5178
    59
      raise RecError "cannot determine datatype associated with function"
berghofe@5178
    60
paulson@6037
    61
    val (ls, cargs, rs) = (map dest_Free ls', 
paulson@6037
    62
			   map dest_Free cargs', 
paulson@6037
    63
			   map dest_Free rs')
berghofe@7016
    64
      handle TERM _ => raise RecError "illegal argument in pattern";
berghofe@5178
    65
    val lfrees = ls @ rs @ cargs;
berghofe@5178
    66
berghofe@5178
    67
  in
berghofe@5178
    68
    if not (null (duplicates lfrees)) then 
berghofe@5178
    69
      raise RecError "repeated variable name in pattern" 
berghofe@5178
    70
    else if not ((map dest_Free (term_frees rhs)) subset lfrees) then
berghofe@5178
    71
      raise RecError "extra variables on rhs"
berghofe@5178
    72
    else if length middle > 1 then 
berghofe@5178
    73
      raise RecError "more than one non-variable in pattern"
berghofe@5178
    74
    else (case assoc (rec_fns, fname) of
berghofe@5178
    75
        None =>
berghofe@5178
    76
          (fname, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
berghofe@5178
    77
      | Some (_, rpos', eqns) =>
berghofe@5178
    78
          if is_some (assoc (eqns, cname)) then
paulson@6037
    79
            raise RecError "constructor already occurred as pattern"
berghofe@5178
    80
          else if rpos <> rpos' then
berghofe@5178
    81
            raise RecError "position of recursive argument inconsistent"
berghofe@5178
    82
          else
paulson@6037
    83
            overwrite (rec_fns, 
paulson@6037
    84
		       (fname, 
paulson@6037
    85
			(tname, rpos,
paulson@6037
    86
			 (cname, (ls, cargs, rs, rhs, eq))::eqns))))
berghofe@5178
    87
  end
berghofe@5178
    88
  handle RecError s => primrec_eq_err sign s eq;
berghofe@5178
    89
berghofe@5178
    90
fun process_fun sign descr rec_eqns ((i, fname), (fnames, fnss)) =
berghofe@5178
    91
  let
berghofe@5178
    92
    val (_, (tname, _, constrs)) = nth_elem (i, descr);
berghofe@5178
    93
berghofe@5178
    94
    (* substitute "fname ls x rs" by "y ls rs" for (x, (_, y)) in subs *)
berghofe@5178
    95
berghofe@5178
    96
    fun subst [] x = x
berghofe@5178
    97
      | subst subs (fs, Abs (a, T, t)) =
berghofe@5178
    98
          let val (fs', t') = subst subs (fs, t)
berghofe@5178
    99
          in (fs', Abs (a, T, t')) end
berghofe@5178
   100
      | subst subs (fs, t as (_ $ _)) =
berghofe@5178
   101
          let val (f, ts) = strip_comb t;
berghofe@5178
   102
          in
berghofe@5178
   103
            if is_Const f andalso (fst (dest_Const f)) mem (map fst rec_eqns) then
berghofe@5178
   104
              let
berghofe@5178
   105
                val (fname', _) = dest_Const f;
berghofe@5178
   106
                val (_, rpos, _) = the (assoc (rec_eqns, fname'));
berghofe@5178
   107
                val ls = take (rpos, ts);
berghofe@5178
   108
                val rest = drop (rpos, ts);
berghofe@7016
   109
                val (x', rs) = (hd rest, tl rest)
berghofe@7016
   110
                  handle LIST _ => raise RecError ("not enough arguments\
berghofe@7016
   111
                   \ in recursive application\nof function " ^ quote fname' ^ " on rhs");
berghofe@7016
   112
                val (x, xs) = strip_comb x'
berghofe@5178
   113
              in 
berghofe@5178
   114
                (case assoc (subs, x) of
berghofe@5178
   115
                    None =>
berghofe@5178
   116
                      let
berghofe@5178
   117
                        val (fs', ts') = foldl_map (subst subs) (fs, ts)
berghofe@5178
   118
                      in (fs', list_comb (f, ts')) end
berghofe@5178
   119
                  | Some (i', y) =>
berghofe@5178
   120
                      let
berghofe@7016
   121
                        val (fs', ts') = foldl_map (subst subs) (fs, xs @ ls @ rs);
berghofe@5178
   122
                        val fs'' = process_fun sign descr rec_eqns ((i', fname'), fs')
berghofe@5178
   123
                      in (fs'', list_comb (y, ts'))
berghofe@5178
   124
                      end)
berghofe@5178
   125
              end
berghofe@5178
   126
            else
berghofe@5178
   127
              let
berghofe@5178
   128
                val (fs', f'::ts') = foldl_map (subst subs) (fs, f::ts)
berghofe@5178
   129
              in (fs', list_comb (f', ts')) end
berghofe@5178
   130
          end
berghofe@5178
   131
      | subst _ x = x;
berghofe@5178
   132
berghofe@5178
   133
    (* translate rec equations into function arguments suitable for rec comb *)
berghofe@5178
   134
berghofe@5178
   135
    fun trans eqns ((cname, cargs), (fnames', fnss', fns)) =
berghofe@5178
   136
      (case assoc (eqns, cname) of
wenzelm@6427
   137
          None => (warning ("no equation for constructor " ^ quote cname ^
wenzelm@6427
   138
            "\nin definition of function " ^ quote fname);
berghofe@5178
   139
              (fnames', fnss', (Const ("arbitrary", dummyT))::fns))
berghofe@5178
   140
        | Some (ls, cargs', rs, rhs, eq) =>
berghofe@5178
   141
            let
berghofe@7016
   142
              fun rec_index (DtRec k) = k
berghofe@7016
   143
                | rec_index (DtType ("fun", [_, DtRec k])) = k;
berghofe@7016
   144
berghofe@5178
   145
              val recs = 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));
paulson@6037
   149
              val ((fnames'', fnss''), rhs') = 
paulson@6037
   150
		  (subst (map (fn ((x, y), z) =>
berghofe@7016
   151
			       (Free x, (rec_index y, Free z)))
paulson@6037
   152
			  (recs ~~ subs))
paulson@6037
   153
		   ((fnames', fnss'), rhs))
berghofe@5178
   154
                  handle RecError s => primrec_eq_err sign s eq
paulson@6037
   155
            in (fnames'', fnss'', 
paulson@6037
   156
		(list_abs_free (cargs' @ subs @ ls @ rs, rhs'))::fns)
berghofe@5178
   157
            end)
berghofe@5178
   158
berghofe@5178
   159
  in (case assoc (fnames, i) of
berghofe@5178
   160
      None =>
berghofe@5178
   161
        if exists (equal fname o snd) fnames then
wenzelm@6427
   162
          raise RecError ("inconsistent functions for datatype " ^ quote tname)
berghofe@5178
   163
        else
berghofe@5178
   164
          let
berghofe@5178
   165
            val (_, _, eqns) = the (assoc (rec_eqns, fname));
berghofe@5178
   166
            val (fnames', fnss', fns) = foldr (trans eqns)
berghofe@5178
   167
              (constrs, ((i, fname)::fnames, fnss, []))
berghofe@5178
   168
          in
berghofe@5178
   169
            (fnames', (i, (fname, #1 (snd (hd eqns)), fns))::fnss')
berghofe@5178
   170
          end
berghofe@5178
   171
    | Some fname' =>
berghofe@5178
   172
        if fname = fname' then (fnames, 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)) =
berghofe@5178
   180
  case assoc (fns, i) of
berghofe@5178
   181
     None =>
berghofe@5178
   182
       let
berghofe@5178
   183
         val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
berghofe@5178
   184
           replicate ((length cargs) + (length (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
berghofe@5178
   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
paulson@6037
   197
    val rhs = foldr (fn (T, t) => Abs ("", T, t)) 
paulson@6037
   198
	            ((map snd ls) @ [dummyT],
paulson@6037
   199
		     list_comb (Const (rec_name, dummyT),
paulson@6037
   200
				fs @ map Bound (0 ::(length ls downto 1))));
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) =
berghofe@5178
   210
      (case Symtab.lookup (dt_info, tname) of
wenzelm@6427
   211
          None => primrec_err (quote tname ^ " is not a datatype")
berghofe@5178
   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@6359
   217
fun add_primrec_i alt_name eqns_atts thy =
berghofe@5178
   218
  let
wenzelm@6359
   219
    val (eqns, atts) = split_list eqns_atts;
wenzelm@6394
   220
    val sg = Theory.sign_of thy;
berghofe@5178
   221
    val dt_info = DatatypePackage.get_datatypes thy;
berghofe@5719
   222
    val rec_eqns = foldr (process_eqn sg) (map snd eqns, []);
berghofe@5178
   223
    val tnames = distinct (map (#1 o snd) rec_eqns);
berghofe@5178
   224
    val dts = find_dts dt_info tnames tnames;
paulson@6037
   225
    val main_fns = 
paulson@6037
   226
	map (fn (tname, {index, ...}) =>
paulson@6037
   227
	     (index, 
paulson@6037
   228
	      fst (the (find_first (fn f => #1 (snd f) = tname) rec_eqns))))
paulson@6037
   229
	dts;
paulson@6037
   230
    val {descr, rec_names, rec_rewrites, ...} = 
paulson@6037
   231
	if null dts then
wenzelm@6359
   232
	    primrec_err ("datatypes " ^ commas_quote tnames ^ 
paulson@6037
   233
			 "\nare not mutually recursive")
paulson@6037
   234
	else snd (hd dts);
paulson@6037
   235
    val (fnames, fnss) = foldr (process_fun sg descr rec_eqns)
paulson@6037
   236
	                       (main_fns, ([], []));
berghofe@5178
   237
    val (fs, defs) = foldr (get_fns fnss) (descr ~~ rec_names, ([], []));
berghofe@5178
   238
    val defs' = map (make_def sg fs) defs;
berghofe@5178
   239
    val names1 = map snd fnames;
berghofe@5178
   240
    val names2 = map fst rec_eqns;
berghofe@5216
   241
    val thy' = thy |>
berghofe@5719
   242
      Theory.add_path (if alt_name = "" then (space_implode "_"
berghofe@5719
   243
        (map (Sign.base_name o #1) defs)) else alt_name) |>
berghofe@5216
   244
      (if eq_set (names1, names2) then Theory.add_defs_i defs'
wenzelm@6359
   245
       else primrec_err ("functions " ^ commas_quote names2 ^
berghofe@5216
   246
         "\nare not mutually recursive"));
berghofe@7016
   247
    val rewrites = o_def :: (map mk_meta_eq rec_rewrites) @ (map (get_axiom thy' o fst) defs');
wenzelm@6427
   248
    val _ = message ("Proving equations for primrec function(s) " ^ commas_quote names1 ^ " ...");
wenzelm@6394
   249
    val char_thms = map (fn (_, t) => prove_goalw_cterm rewrites (cterm_of (Theory.sign_of thy') t)
berghofe@5178
   250
        (fn _ => [rtac refl 1])) eqns;
wenzelm@6092
   251
    val simps = char_thms;
wenzelm@6359
   252
    val thy'' =
wenzelm@6359
   253
      thy'
wenzelm@6359
   254
      |> PureThy.add_thmss [(("simps", simps), [Simplifier.simp_add_global])]
wenzelm@6359
   255
      |> PureThy.add_thms ((map fst eqns ~~ simps) ~~ atts)
wenzelm@6359
   256
      |> Theory.parent_path;
wenzelm@6359
   257
  in (thy'', char_thms) end;
wenzelm@6359
   258
wenzelm@6359
   259
berghofe@7016
   260
fun add_primrec alt_name eqns thy =
berghofe@7016
   261
  let
berghofe@7016
   262
    val ((names, strings), srcss) = apfst split_list (split_list eqns);
berghofe@7016
   263
    val atts = map (map (Attrib.global_attribute thy)) srcss;
berghofe@7016
   264
    val eqn_ts = map (readtm (Theory.sign_of thy) propT) strings;
berghofe@7016
   265
    val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop eq)))
berghofe@7016
   266
      handle TERM _ => raise RecError "not a proper equation") eqn_ts;
berghofe@7016
   267
    val (_, eqn_ts') = InductivePackage.unify_consts (sign_of thy) rec_ts eqn_ts
berghofe@7016
   268
  in
berghofe@7016
   269
    add_primrec_i alt_name (names ~~ eqn_ts' ~~ atts) thy
berghofe@7016
   270
  end;
wenzelm@6359
   271
berghofe@5178
   272
wenzelm@6359
   273
(* outer syntax *)
wenzelm@6359
   274
wenzelm@6723
   275
local structure P = OuterParse and K = OuterSyntax.Keyword in
wenzelm@6359
   276
wenzelm@6359
   277
val primrec_decl =
wenzelm@6723
   278
  Scan.optional (P.$$$ "(" |-- P.name --| P.$$$ ")") "" --
wenzelm@6729
   279
    Scan.repeat1 (P.opt_thm_name ":" -- P.term --| P.marg_comment);
wenzelm@6359
   280
wenzelm@6359
   281
val primrecP =
wenzelm@6723
   282
  OuterSyntax.command "primrec" "define primitive recursive functions on datatypes" K.thy_decl
wenzelm@6359
   283
    (primrec_decl >> (fn (alt_name, eqns) =>
wenzelm@6723
   284
      Toplevel.theory (#1 o add_primrec alt_name (map P.triple_swap eqns))));
wenzelm@6359
   285
wenzelm@6359
   286
val _ = OuterSyntax.add_parsers [primrecP];
berghofe@5178
   287
berghofe@5178
   288
end;
wenzelm@6384
   289
wenzelm@6384
   290
wenzelm@6384
   291
end;