src/HOL/Tools/primrec_package.ML
author berghofe
Thu Jul 30 15:56:21 1998 +0200 (1998-07-30)
changeset 5216 f0a66af5f2cb
parent 5178 9337b230ff15
child 5303 22029546d109
permissions -rw-r--r--
Equations are now stored in theory.
berghofe@5178
     1
(*  Title:      HOL/Tools/datatype_package.ML
berghofe@5178
     2
    ID:         $Id$
berghofe@5178
     3
    Author:     Stefan Berghofer
berghofe@5178
     4
    Copyright   1998  TU Muenchen
berghofe@5178
     5
berghofe@5178
     6
Package for defining functions on datatypes
berghofe@5178
     7
by primitive recursion
berghofe@5178
     8
*)
berghofe@5178
     9
berghofe@5178
    10
signature PRIMREC_PACKAGE =
berghofe@5178
    11
sig
berghofe@5216
    12
  val add_primrec_i : string option -> string list ->
berghofe@5216
    13
    term list -> theory -> theory * thm list
berghofe@5216
    14
  val add_primrec : string option -> string list ->
berghofe@5216
    15
    string list -> 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
(* FIXME: move? *)
berghofe@5178
    26
berghofe@5178
    27
fun dest_eq (Const ("Trueprop", _) $ (Const ("op =", _) $ lhs $ rhs)) = (lhs, rhs)
berghofe@5178
    28
  | dest_eq t = raise TERM ("dest_eq", [t])
berghofe@5178
    29
berghofe@5178
    30
fun dest_Type (Type x) = x
berghofe@5178
    31
  | dest_Type T = raise TYPE ("dest_Type", [T], []);
berghofe@5178
    32
berghofe@5178
    33
fun primrec_err s = error ("Primrec definition error:\n" ^ s);
berghofe@5178
    34
fun primrec_eq_err sign s eq =
berghofe@5178
    35
  primrec_err (s ^ "\nin equation\n" ^ Sign.string_of_term sign eq);
berghofe@5178
    36
berghofe@5178
    37
(* preprocessing of equations *)
berghofe@5178
    38
berghofe@5178
    39
fun process_eqn sign (eq, rec_fns) = 
berghofe@5178
    40
  let
berghofe@5178
    41
    val (lhs, rhs) = if null (term_vars eq) then
berghofe@5178
    42
        dest_eq eq handle _ => raise RecError "not a proper equation"
berghofe@5178
    43
      else raise RecError "illegal schematic variable(s)";
berghofe@5178
    44
berghofe@5178
    45
    val (recfun, args) = strip_comb lhs;
berghofe@5178
    46
    val (fname, _) = dest_Const recfun handle _ => 
berghofe@5178
    47
      raise RecError "function is not declared as constant in theory";
berghofe@5178
    48
berghofe@5178
    49
    val (ls', rest)  = take_prefix is_Free args;
berghofe@5178
    50
    val (middle, rs') = take_suffix is_Free rest;
berghofe@5178
    51
    val rpos = length ls';
berghofe@5178
    52
berghofe@5178
    53
    val (constr, cargs') = if null middle then raise RecError "constructor missing"
berghofe@5178
    54
      else strip_comb (hd middle);
berghofe@5178
    55
    val (cname, T) = dest_Const constr
berghofe@5178
    56
      handle _ => raise RecError "ill-formed constructor";
berghofe@5178
    57
    val (tname, _) = dest_Type (body_type T) handle _ =>
berghofe@5178
    58
      raise RecError "cannot determine datatype associated with function"
berghofe@5178
    59
berghofe@5178
    60
    val (ls, cargs, rs) = (map dest_Free ls', map dest_Free cargs', 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
berghofe@5178
    76
            raise RecError "constructor already occured as pattern"
berghofe@5178
    77
          else if rpos <> rpos' then
berghofe@5178
    78
            raise RecError "position of recursive argument inconsistent"
berghofe@5178
    79
          else
berghofe@5178
    80
            overwrite (rec_fns, (fname, (tname, rpos,
berghofe@5178
    81
              (cname, (ls, cargs, rs, rhs, eq))::eqns))))
berghofe@5178
    82
  end
berghofe@5178
    83
  handle RecError s => primrec_eq_err sign s eq;
berghofe@5178
    84
berghofe@5178
    85
fun process_fun sign descr rec_eqns ((i, fname), (fnames, fnss)) =
berghofe@5178
    86
  let
berghofe@5178
    87
    val (_, (tname, _, constrs)) = nth_elem (i, descr);
berghofe@5178
    88
berghofe@5178
    89
    (* substitute "fname ls x rs" by "y ls rs" for (x, (_, y)) in subs *)
berghofe@5178
    90
berghofe@5178
    91
    fun subst [] x = x
berghofe@5178
    92
      | subst subs (fs, Abs (a, T, t)) =
berghofe@5178
    93
          let val (fs', t') = subst subs (fs, t)
berghofe@5178
    94
          in (fs', Abs (a, T, t')) end
berghofe@5178
    95
      | subst subs (fs, t as (_ $ _)) =
berghofe@5178
    96
          let val (f, ts) = strip_comb t;
berghofe@5178
    97
          in
berghofe@5178
    98
            if is_Const f andalso (fst (dest_Const f)) mem (map fst rec_eqns) then
berghofe@5178
    99
              let
berghofe@5178
   100
                val (fname', _) = dest_Const f;
berghofe@5178
   101
                val (_, rpos, _) = the (assoc (rec_eqns, fname'));
berghofe@5178
   102
                val ls = take (rpos, ts);
berghofe@5178
   103
                val rest = drop (rpos, ts);
berghofe@5178
   104
                val (x, rs) = (hd rest, tl rest)
berghofe@5178
   105
                  handle _ => raise RecError ("not enough arguments\
berghofe@5178
   106
                   \ in recursive application\nof function " ^ fname' ^ " on rhs")
berghofe@5178
   107
              in 
berghofe@5178
   108
                (case assoc (subs, x) of
berghofe@5178
   109
                    None =>
berghofe@5178
   110
                      let
berghofe@5178
   111
                        val (fs', ts') = foldl_map (subst subs) (fs, ts)
berghofe@5178
   112
                      in (fs', list_comb (f, ts')) end
berghofe@5178
   113
                  | Some (i', y) =>
berghofe@5178
   114
                      let
berghofe@5178
   115
                        val (fs', ts') = foldl_map (subst subs) (fs, ls @ rs);
berghofe@5178
   116
                        val fs'' = process_fun sign descr rec_eqns ((i', fname'), fs')
berghofe@5178
   117
                      in (fs'', list_comb (y, ts'))
berghofe@5178
   118
                      end)
berghofe@5178
   119
              end
berghofe@5178
   120
            else
berghofe@5178
   121
              let
berghofe@5178
   122
                val (fs', f'::ts') = foldl_map (subst subs) (fs, f::ts)
berghofe@5178
   123
              in (fs', list_comb (f', ts')) end
berghofe@5178
   124
          end
berghofe@5178
   125
      | subst _ x = x;
berghofe@5178
   126
berghofe@5178
   127
    (* translate rec equations into function arguments suitable for rec comb *)
berghofe@5178
   128
berghofe@5178
   129
    fun trans eqns ((cname, cargs), (fnames', fnss', fns)) =
berghofe@5178
   130
      (case assoc (eqns, cname) of
berghofe@5178
   131
          None => (warning ("no equation for constructor " ^ cname ^
berghofe@5178
   132
            "\nin definition of function " ^ fname);
berghofe@5178
   133
              (fnames', fnss', (Const ("arbitrary", dummyT))::fns))
berghofe@5178
   134
        | Some (ls, cargs', rs, rhs, eq) =>
berghofe@5178
   135
            let
berghofe@5178
   136
              val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
berghofe@5178
   137
              val rargs = map fst recs;
berghofe@5178
   138
              val subs = map (rpair dummyT o fst) (rev (rename_wrt_term rhs rargs));
berghofe@5178
   139
              val ((fnames'', fnss''), rhs') = (subst (map (fn ((x, y), z) =>
berghofe@5178
   140
                (Free x, (dest_DtRec y, Free z))) (recs ~~ subs)) ((fnames', fnss'), rhs))
berghofe@5178
   141
                  handle RecError s => primrec_eq_err sign s eq
berghofe@5178
   142
            in (fnames'', fnss'', (list_abs_free (cargs' @ subs @ ls @ rs, rhs'))::fns)
berghofe@5178
   143
            end)
berghofe@5178
   144
berghofe@5178
   145
  in (case assoc (fnames, i) of
berghofe@5178
   146
      None =>
berghofe@5178
   147
        if exists (equal fname o snd) fnames then
berghofe@5178
   148
          raise RecError ("inconsistent functions for datatype " ^ tname)
berghofe@5178
   149
        else
berghofe@5178
   150
          let
berghofe@5178
   151
            val (_, _, eqns) = the (assoc (rec_eqns, fname));
berghofe@5178
   152
            val (fnames', fnss', fns) = foldr (trans eqns)
berghofe@5178
   153
              (constrs, ((i, fname)::fnames, fnss, []))
berghofe@5178
   154
          in
berghofe@5178
   155
            (fnames', (i, (fname, #1 (snd (hd eqns)), fns))::fnss')
berghofe@5178
   156
          end
berghofe@5178
   157
    | Some fname' =>
berghofe@5178
   158
        if fname = fname' then (fnames, fnss)
berghofe@5178
   159
        else raise RecError ("inconsistent functions for datatype " ^ tname))
berghofe@5178
   160
  end;
berghofe@5178
   161
berghofe@5178
   162
(* prepare functions needed for definitions *)
berghofe@5178
   163
berghofe@5178
   164
fun get_fns fns (((i, (tname, _, constrs)), rec_name), (fs, defs)) =
berghofe@5178
   165
  case assoc (fns, i) of
berghofe@5178
   166
     None =>
berghofe@5178
   167
       let
berghofe@5178
   168
         val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
berghofe@5178
   169
           replicate ((length cargs) + (length (filter is_rec_type cargs)))
berghofe@5178
   170
             dummyT ---> HOLogic.unitT)) constrs;
berghofe@5178
   171
         val _ = warning ("no function definition for datatype " ^ tname)
berghofe@5178
   172
       in
berghofe@5178
   173
         (dummy_fns @ fs, defs)
berghofe@5178
   174
       end
berghofe@5178
   175
   | Some (fname, ls, fs') => (fs' @ fs, (fname, ls, rec_name, tname)::defs);
berghofe@5178
   176
berghofe@5178
   177
(* make definition *)
berghofe@5178
   178
berghofe@5178
   179
fun make_def sign fs (fname, ls, rec_name, tname) =
berghofe@5178
   180
  let
berghofe@5178
   181
    val rhs = foldr (fn (T, t) => Abs ("", T, t)) ((map snd ls) @ [dummyT],
berghofe@5178
   182
      list_comb (Const (rec_name, dummyT),
berghofe@5178
   183
        fs @ map Bound (0 ::(length ls downto 1))));
berghofe@5178
   184
    val defpair = (Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def",
berghofe@5178
   185
      Logic.mk_equals (Const (fname, dummyT), rhs))
berghofe@5178
   186
  in
berghofe@5178
   187
    inferT_axm sign defpair
berghofe@5178
   188
  end;
berghofe@5178
   189
berghofe@5178
   190
(* find datatypes which contain all datatypes in tnames' *)
berghofe@5178
   191
berghofe@5178
   192
fun find_dts (dt_info : datatype_info Symtab.table) _ [] = []
berghofe@5178
   193
  | find_dts dt_info tnames' (tname::tnames) =
berghofe@5178
   194
      (case Symtab.lookup (dt_info, tname) of
berghofe@5178
   195
          None => primrec_err (tname ^ " is not a datatype")
berghofe@5178
   196
        | Some dt =>
berghofe@5178
   197
            if tnames' subset (map (#1 o snd) (#descr dt)) then
berghofe@5178
   198
              (tname, dt)::(find_dts dt_info tnames' tnames)
berghofe@5178
   199
            else find_dts dt_info tnames' tnames);
berghofe@5178
   200
berghofe@5216
   201
fun add_primrec_i alt_name eqn_names eqns thy =
berghofe@5178
   202
  let
berghofe@5178
   203
    val sg = sign_of thy;
berghofe@5178
   204
    val dt_info = DatatypePackage.get_datatypes thy;
berghofe@5178
   205
    val rec_eqns = foldr (process_eqn sg) (eqns, []);
berghofe@5178
   206
    val tnames = distinct (map (#1 o snd) rec_eqns);
berghofe@5178
   207
    val dts = find_dts dt_info tnames tnames;
berghofe@5178
   208
    val main_fns = map (fn (tname, {index, ...}) =>
berghofe@5178
   209
      (index, fst (the (find_first (fn f => #1 (snd f) = tname) rec_eqns)))) dts;
berghofe@5178
   210
    val {descr, rec_names, rec_rewrites, ...} = if null dts then
berghofe@5178
   211
        primrec_err ("datatypes " ^ commas tnames ^ "\nare not mutually recursive")
berghofe@5178
   212
      else snd (hd dts);
berghofe@5178
   213
    val (fnames, fnss) = foldr (process_fun sg descr rec_eqns) (main_fns, ([], []));
berghofe@5178
   214
    val (fs, defs) = foldr (get_fns fnss) (descr ~~ rec_names, ([], []));
berghofe@5178
   215
    val defs' = map (make_def sg fs) defs;
berghofe@5178
   216
    val names1 = map snd fnames;
berghofe@5178
   217
    val names2 = map fst rec_eqns;
berghofe@5216
   218
    val thy' = thy |>
berghofe@5216
   219
      Theory.add_path (if_none alt_name (space_implode "_"
berghofe@5216
   220
        (map (Sign.base_name o #1) defs))) |>
berghofe@5216
   221
      (if eq_set (names1, names2) then Theory.add_defs_i defs'
berghofe@5216
   222
       else primrec_err ("functions " ^ commas names2 ^
berghofe@5216
   223
         "\nare not mutually recursive"));
berghofe@5178
   224
    val rewrites = (map mk_meta_eq rec_rewrites) @ (map (get_axiom thy' o fst) defs');
berghofe@5178
   225
    val _ = writeln ("Proving equations for primrec function(s)\n" ^
berghofe@5178
   226
      commas names1 ^ " ...");
berghofe@5178
   227
    val char_thms = map (fn t => prove_goalw_cterm rewrites (cterm_of (sign_of thy') t)
berghofe@5178
   228
        (fn _ => [rtac refl 1])) eqns;
berghofe@5216
   229
    val tsimps = map Attribute.tthm_of char_thms;
berghofe@5216
   230
    val thy'' = thy' |>
berghofe@5216
   231
      PureThy.add_tthmss [(("simps", tsimps), [Simplifier.simp_add_global])] |>
berghofe@5216
   232
      (if null eqn_names then I
berghofe@5216
   233
       else PureThy.add_tthms (map (rpair []) (eqn_names ~~ tsimps))) |>
berghofe@5216
   234
      Theory.parent_path;
berghofe@5178
   235
  in
berghofe@5216
   236
    (thy'', char_thms)
berghofe@5178
   237
  end;
berghofe@5178
   238
berghofe@5216
   239
fun add_primrec alt_name eqn_names eqns thy =
berghofe@5216
   240
  add_primrec_i alt_name eqn_names (map (readtm (sign_of thy) propT) eqns) thy;
berghofe@5178
   241
berghofe@5178
   242
end;