src/HOL/Tools/primrec_package.ML
author wenzelm
Wed Mar 17 16:53:46 1999 +0100 (1999-03-17)
changeset 6394 3d9fd50fcc43
parent 6384 eed1273c9146
child 6425 9540aa1b5a9a
permissions -rw-r--r--
Theory.sign_of;
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.
wenzelm@6359
     7
wenzelm@6359
     8
TODO:
wenzelm@6359
     9
  - add_primrec(_i): improve prep of args;
wenzelm@6359
    10
  - quiet_mode (!?);
berghofe@5178
    11
*)
berghofe@5178
    12
berghofe@5178
    13
signature PRIMREC_PACKAGE =
berghofe@5178
    14
sig
wenzelm@6359
    15
  val add_primrec: string -> ((string * string) * Args.src list) list
wenzelm@6359
    16
    -> theory -> theory * thm list
wenzelm@6359
    17
  val add_primrec_i: string -> ((string * term) * theory attribute list) list
wenzelm@6359
    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@5178
    30
  primrec_err (s ^ "\nin equation\n" ^ Sign.string_of_term sign eq);
berghofe@5178
    31
wenzelm@6359
    32
berghofe@5178
    33
(* preprocessing of equations *)
berghofe@5178
    34
berghofe@5178
    35
fun process_eqn sign (eq, rec_fns) = 
berghofe@5178
    36
  let
paulson@6032
    37
    val (lhs, rhs) = 
paulson@6032
    38
	if null (term_vars eq) then
paulson@6032
    39
	    HOLogic.dest_eq (HOLogic.dest_Trueprop eq)
paulson@6032
    40
	      handle _ => raise RecError "not a proper equation"
paulson@6032
    41
	else raise RecError "illegal schematic variable(s)";
berghofe@5178
    42
berghofe@5178
    43
    val (recfun, args) = strip_comb lhs;
berghofe@5178
    44
    val (fname, _) = dest_Const recfun handle _ => 
berghofe@5178
    45
      raise RecError "function is not declared as constant in theory";
berghofe@5178
    46
berghofe@5178
    47
    val (ls', rest)  = take_prefix is_Free args;
berghofe@5178
    48
    val (middle, rs') = take_suffix is_Free rest;
berghofe@5178
    49
    val rpos = length ls';
berghofe@5178
    50
berghofe@5178
    51
    val (constr, cargs') = if null middle then raise RecError "constructor missing"
berghofe@5178
    52
      else strip_comb (hd middle);
berghofe@5178
    53
    val (cname, T) = dest_Const constr
berghofe@5178
    54
      handle _ => raise RecError "ill-formed constructor";
berghofe@5178
    55
    val (tname, _) = dest_Type (body_type T) handle _ =>
berghofe@5178
    56
      raise RecError "cannot determine datatype associated with function"
berghofe@5178
    57
paulson@6037
    58
    val (ls, cargs, rs) = (map dest_Free ls', 
paulson@6037
    59
			   map dest_Free cargs', 
paulson@6037
    60
			   map dest_Free rs')
berghofe@5178
    61
      handle _ => raise RecError "illegal argument in pattern";
berghofe@5178
    62
    val lfrees = ls @ rs @ cargs;
berghofe@5178
    63
berghofe@5178
    64
  in
berghofe@5178
    65
    if not (null (duplicates lfrees)) then 
berghofe@5178
    66
      raise RecError "repeated variable name in pattern" 
berghofe@5178
    67
    else if not ((map dest_Free (term_frees rhs)) subset lfrees) then
berghofe@5178
    68
      raise RecError "extra variables on rhs"
berghofe@5178
    69
    else if length middle > 1 then 
berghofe@5178
    70
      raise RecError "more than one non-variable in pattern"
berghofe@5178
    71
    else (case assoc (rec_fns, fname) of
berghofe@5178
    72
        None =>
berghofe@5178
    73
          (fname, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
berghofe@5178
    74
      | Some (_, rpos', eqns) =>
berghofe@5178
    75
          if is_some (assoc (eqns, cname)) then
paulson@6037
    76
            raise RecError "constructor already occurred as pattern"
berghofe@5178
    77
          else if rpos <> rpos' then
berghofe@5178
    78
            raise RecError "position of recursive argument inconsistent"
berghofe@5178
    79
          else
paulson@6037
    80
            overwrite (rec_fns, 
paulson@6037
    81
		       (fname, 
paulson@6037
    82
			(tname, rpos,
paulson@6037
    83
			 (cname, (ls, cargs, rs, rhs, eq))::eqns))))
berghofe@5178
    84
  end
berghofe@5178
    85
  handle RecError s => primrec_eq_err sign s eq;
berghofe@5178
    86
berghofe@5178
    87
fun process_fun sign descr rec_eqns ((i, fname), (fnames, fnss)) =
berghofe@5178
    88
  let
berghofe@5178
    89
    val (_, (tname, _, constrs)) = nth_elem (i, descr);
berghofe@5178
    90
berghofe@5178
    91
    (* substitute "fname ls x rs" by "y ls rs" for (x, (_, y)) in subs *)
berghofe@5178
    92
berghofe@5178
    93
    fun subst [] x = x
berghofe@5178
    94
      | subst subs (fs, Abs (a, T, t)) =
berghofe@5178
    95
          let val (fs', t') = subst subs (fs, t)
berghofe@5178
    96
          in (fs', Abs (a, T, t')) end
berghofe@5178
    97
      | subst subs (fs, t as (_ $ _)) =
berghofe@5178
    98
          let val (f, ts) = strip_comb t;
berghofe@5178
    99
          in
berghofe@5178
   100
            if is_Const f andalso (fst (dest_Const f)) mem (map fst rec_eqns) then
berghofe@5178
   101
              let
berghofe@5178
   102
                val (fname', _) = dest_Const f;
berghofe@5178
   103
                val (_, rpos, _) = the (assoc (rec_eqns, fname'));
berghofe@5178
   104
                val ls = take (rpos, ts);
berghofe@5178
   105
                val rest = drop (rpos, ts);
berghofe@5178
   106
                val (x, rs) = (hd rest, tl rest)
berghofe@5178
   107
                  handle _ => raise RecError ("not enough arguments\
berghofe@5178
   108
                   \ in recursive application\nof function " ^ fname' ^ " on rhs")
berghofe@5178
   109
              in 
berghofe@5178
   110
                (case assoc (subs, x) of
berghofe@5178
   111
                    None =>
berghofe@5178
   112
                      let
berghofe@5178
   113
                        val (fs', ts') = foldl_map (subst subs) (fs, ts)
berghofe@5178
   114
                      in (fs', list_comb (f, ts')) end
berghofe@5178
   115
                  | Some (i', y) =>
berghofe@5178
   116
                      let
berghofe@5178
   117
                        val (fs', ts') = foldl_map (subst subs) (fs, ls @ rs);
berghofe@5178
   118
                        val fs'' = process_fun sign descr rec_eqns ((i', fname'), fs')
berghofe@5178
   119
                      in (fs'', list_comb (y, ts'))
berghofe@5178
   120
                      end)
berghofe@5178
   121
              end
berghofe@5178
   122
            else
berghofe@5178
   123
              let
berghofe@5178
   124
                val (fs', f'::ts') = foldl_map (subst subs) (fs, f::ts)
berghofe@5178
   125
              in (fs', list_comb (f', ts')) end
berghofe@5178
   126
          end
berghofe@5178
   127
      | subst _ x = x;
berghofe@5178
   128
berghofe@5178
   129
    (* translate rec equations into function arguments suitable for rec comb *)
berghofe@5178
   130
berghofe@5178
   131
    fun trans eqns ((cname, cargs), (fnames', fnss', fns)) =
berghofe@5178
   132
      (case assoc (eqns, cname) of
berghofe@5178
   133
          None => (warning ("no equation for constructor " ^ cname ^
berghofe@5178
   134
            "\nin definition of function " ^ fname);
berghofe@5178
   135
              (fnames', fnss', (Const ("arbitrary", dummyT))::fns))
berghofe@5178
   136
        | Some (ls, cargs', rs, rhs, eq) =>
berghofe@5178
   137
            let
berghofe@5178
   138
              val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
berghofe@5178
   139
              val rargs = map fst recs;
paulson@6037
   140
              val subs = map (rpair dummyT o fst) 
paulson@6037
   141
		             (rev (rename_wrt_term rhs rargs));
paulson@6037
   142
              val ((fnames'', fnss''), rhs') = 
paulson@6037
   143
		  (subst (map (fn ((x, y), z) =>
paulson@6037
   144
			       (Free x, (dest_DtRec y, Free z)))
paulson@6037
   145
			  (recs ~~ subs))
paulson@6037
   146
		   ((fnames', fnss'), rhs))
berghofe@5178
   147
                  handle RecError s => primrec_eq_err sign s eq
paulson@6037
   148
            in (fnames'', fnss'', 
paulson@6037
   149
		(list_abs_free (cargs' @ subs @ ls @ rs, rhs'))::fns)
berghofe@5178
   150
            end)
berghofe@5178
   151
berghofe@5178
   152
  in (case assoc (fnames, i) of
berghofe@5178
   153
      None =>
berghofe@5178
   154
        if exists (equal fname o snd) fnames then
berghofe@5178
   155
          raise RecError ("inconsistent functions for datatype " ^ tname)
berghofe@5178
   156
        else
berghofe@5178
   157
          let
berghofe@5178
   158
            val (_, _, eqns) = the (assoc (rec_eqns, fname));
berghofe@5178
   159
            val (fnames', fnss', fns) = foldr (trans eqns)
berghofe@5178
   160
              (constrs, ((i, fname)::fnames, fnss, []))
berghofe@5178
   161
          in
berghofe@5178
   162
            (fnames', (i, (fname, #1 (snd (hd eqns)), fns))::fnss')
berghofe@5178
   163
          end
berghofe@5178
   164
    | Some fname' =>
berghofe@5178
   165
        if fname = fname' then (fnames, fnss)
berghofe@5178
   166
        else raise RecError ("inconsistent functions for datatype " ^ tname))
berghofe@5178
   167
  end;
berghofe@5178
   168
wenzelm@6359
   169
berghofe@5178
   170
(* prepare functions needed for definitions *)
berghofe@5178
   171
berghofe@5178
   172
fun get_fns fns (((i, (tname, _, constrs)), rec_name), (fs, defs)) =
berghofe@5178
   173
  case assoc (fns, i) of
berghofe@5178
   174
     None =>
berghofe@5178
   175
       let
berghofe@5178
   176
         val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
berghofe@5178
   177
           replicate ((length cargs) + (length (filter is_rec_type cargs)))
berghofe@5178
   178
             dummyT ---> HOLogic.unitT)) constrs;
berghofe@5178
   179
         val _ = warning ("no function definition for datatype " ^ tname)
berghofe@5178
   180
       in
berghofe@5178
   181
         (dummy_fns @ fs, defs)
berghofe@5178
   182
       end
berghofe@5178
   183
   | Some (fname, ls, fs') => (fs' @ fs, (fname, ls, rec_name, tname)::defs);
berghofe@5178
   184
wenzelm@6359
   185
berghofe@5178
   186
(* make definition *)
berghofe@5178
   187
berghofe@5178
   188
fun make_def sign fs (fname, ls, rec_name, tname) =
berghofe@5178
   189
  let
paulson@6037
   190
    val rhs = foldr (fn (T, t) => Abs ("", T, t)) 
paulson@6037
   191
	            ((map snd ls) @ [dummyT],
paulson@6037
   192
		     list_comb (Const (rec_name, dummyT),
paulson@6037
   193
				fs @ map Bound (0 ::(length ls downto 1))));
berghofe@5178
   194
    val defpair = (Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def",
paulson@6037
   195
		   Logic.mk_equals (Const (fname, dummyT), rhs))
wenzelm@6394
   196
  in Theory.inferT_axm sign defpair end;
berghofe@5178
   197
wenzelm@6359
   198
berghofe@5178
   199
(* find datatypes which contain all datatypes in tnames' *)
berghofe@5178
   200
berghofe@5178
   201
fun find_dts (dt_info : datatype_info Symtab.table) _ [] = []
berghofe@5178
   202
  | find_dts dt_info tnames' (tname::tnames) =
berghofe@5178
   203
      (case Symtab.lookup (dt_info, tname) of
berghofe@5178
   204
          None => primrec_err (tname ^ " is not a datatype")
berghofe@5178
   205
        | Some dt =>
berghofe@5178
   206
            if tnames' subset (map (#1 o snd) (#descr dt)) then
berghofe@5178
   207
              (tname, dt)::(find_dts dt_info tnames' tnames)
berghofe@5178
   208
            else find_dts dt_info tnames' tnames);
berghofe@5178
   209
wenzelm@6359
   210
fun add_primrec_i alt_name eqns_atts thy =
berghofe@5178
   211
  let
wenzelm@6359
   212
    val (eqns, atts) = split_list eqns_atts;
wenzelm@6394
   213
    val sg = Theory.sign_of thy;
berghofe@5178
   214
    val dt_info = DatatypePackage.get_datatypes thy;
berghofe@5719
   215
    val rec_eqns = foldr (process_eqn sg) (map snd eqns, []);
berghofe@5178
   216
    val tnames = distinct (map (#1 o snd) rec_eqns);
berghofe@5178
   217
    val dts = find_dts dt_info tnames tnames;
paulson@6037
   218
    val main_fns = 
paulson@6037
   219
	map (fn (tname, {index, ...}) =>
paulson@6037
   220
	     (index, 
paulson@6037
   221
	      fst (the (find_first (fn f => #1 (snd f) = tname) rec_eqns))))
paulson@6037
   222
	dts;
paulson@6037
   223
    val {descr, rec_names, rec_rewrites, ...} = 
paulson@6037
   224
	if null dts then
wenzelm@6359
   225
	    primrec_err ("datatypes " ^ commas_quote tnames ^ 
paulson@6037
   226
			 "\nare not mutually recursive")
paulson@6037
   227
	else snd (hd dts);
paulson@6037
   228
    val (fnames, fnss) = foldr (process_fun sg descr rec_eqns)
paulson@6037
   229
	                       (main_fns, ([], []));
berghofe@5178
   230
    val (fs, defs) = foldr (get_fns fnss) (descr ~~ rec_names, ([], []));
berghofe@5178
   231
    val defs' = map (make_def sg fs) defs;
berghofe@5178
   232
    val names1 = map snd fnames;
berghofe@5178
   233
    val names2 = map fst rec_eqns;
berghofe@5216
   234
    val thy' = thy |>
berghofe@5719
   235
      Theory.add_path (if alt_name = "" then (space_implode "_"
berghofe@5719
   236
        (map (Sign.base_name o #1) defs)) else alt_name) |>
berghofe@5216
   237
      (if eq_set (names1, names2) then Theory.add_defs_i defs'
wenzelm@6359
   238
       else primrec_err ("functions " ^ commas_quote names2 ^
berghofe@5216
   239
         "\nare not mutually recursive"));
oheimb@5553
   240
    val rewrites = (map mk_meta_eq rec_rewrites) @ (map (get_axiom thy' o fst) defs');
berghofe@5178
   241
    val _ = writeln ("Proving equations for primrec function(s)\n" ^
wenzelm@6359
   242
      commas_quote names1 ^ " ...");
wenzelm@6394
   243
    val char_thms = map (fn (_, t) => prove_goalw_cterm rewrites (cterm_of (Theory.sign_of thy') t)
berghofe@5178
   244
        (fn _ => [rtac refl 1])) eqns;
wenzelm@6092
   245
    val simps = char_thms;
wenzelm@6359
   246
    val thy'' =
wenzelm@6359
   247
      thy'
wenzelm@6359
   248
      |> PureThy.add_thmss [(("simps", simps), [Simplifier.simp_add_global])]
wenzelm@6359
   249
      |> PureThy.add_thms ((map fst eqns ~~ simps) ~~ atts)
wenzelm@6359
   250
      |> Theory.parent_path;
wenzelm@6359
   251
  in (thy'', char_thms) end;
wenzelm@6359
   252
wenzelm@6359
   253
wenzelm@6359
   254
fun read_eqn thy ((name, s), srcs) =
wenzelm@6394
   255
  ((name, readtm (Theory.sign_of thy) propT s), map (Attrib.global_attribute thy) srcs);
wenzelm@6359
   256
wenzelm@6359
   257
fun add_primrec alt_name eqns thy = add_primrec_i alt_name (map (read_eqn thy) eqns) thy;
wenzelm@6359
   258
berghofe@5178
   259
wenzelm@6359
   260
(* outer syntax *)
wenzelm@6359
   261
wenzelm@6384
   262
local open OuterParse in
wenzelm@6359
   263
wenzelm@6359
   264
val primrec_decl =
wenzelm@6359
   265
  Scan.optional ($$$ "(" |-- name --| $$$ ")") "" --
wenzelm@6359
   266
    Scan.repeat1 (opt_thm_name ":" -- term);
wenzelm@6359
   267
wenzelm@6359
   268
val primrecP =
wenzelm@6384
   269
  OuterSyntax.command "primrec" "define primitive recursive functions on datatypes"
wenzelm@6359
   270
    (primrec_decl >> (fn (alt_name, eqns) =>
wenzelm@6359
   271
      Toplevel.theory (#1 o add_primrec alt_name (map (fn ((x, y), z) => ((x, z), y)) eqns))));
wenzelm@6359
   272
wenzelm@6359
   273
val _ = OuterSyntax.add_parsers [primrecP];
berghofe@5178
   274
berghofe@5178
   275
end;
wenzelm@6384
   276
wenzelm@6384
   277
wenzelm@6384
   278
end;