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