src/HOL/Tools/old_primrec_package.ML
author wenzelm
Wed Dec 31 19:54:03 2008 +0100 (2008-12-31)
changeset 29276 94b1ffec9201
parent 29266 4a478f9d2847
child 29290 8fb767245822
permissions -rw-r--r--
qualified Term.rename_wrt_term;
haftmann@28308
     1
(*  Title:      HOL/Tools/old_primrec_package.ML
wenzelm@29266
     2
    Author:     Norbert Voelker, FernUni Hagen
wenzelm@29266
     3
    Author:     Stefan Berghofer, TU Muenchen
haftmann@25557
     4
haftmann@25557
     5
Package for defining functions on datatypes by primitive recursion.
haftmann@25557
     6
*)
haftmann@25557
     7
haftmann@25557
     8
signature OLD_PRIMREC_PACKAGE =
haftmann@25557
     9
sig
haftmann@25557
    10
  val unify_consts: theory -> term list -> term list -> term list * term list
haftmann@25557
    11
  val add_primrec: string -> ((bstring * string) * Attrib.src list) list
haftmann@25557
    12
    -> theory -> thm list * theory
haftmann@25557
    13
  val add_primrec_unchecked: string -> ((bstring * string) * Attrib.src list) list
haftmann@25557
    14
    -> theory -> thm list * theory
haftmann@25557
    15
  val add_primrec_i: string -> ((bstring * term) * attribute list) list
haftmann@25557
    16
    -> theory -> thm list * theory
haftmann@25557
    17
  val add_primrec_unchecked_i: string -> ((bstring * term) * attribute list) list
haftmann@25557
    18
    -> theory -> thm list * theory
haftmann@25557
    19
end;
haftmann@25557
    20
haftmann@25557
    21
structure OldPrimrecPackage : OLD_PRIMREC_PACKAGE =
haftmann@25557
    22
struct
haftmann@25557
    23
haftmann@25557
    24
open DatatypeAux;
haftmann@25557
    25
haftmann@25557
    26
exception RecError of string;
haftmann@25557
    27
haftmann@25557
    28
fun primrec_err s = error ("Primrec definition error:\n" ^ s);
haftmann@25557
    29
fun primrec_eq_err thy s eq =
wenzelm@26939
    30
  primrec_err (s ^ "\nin\n" ^ quote (Syntax.string_of_term_global thy eq));
haftmann@25557
    31
haftmann@25557
    32
haftmann@25557
    33
(*the following code ensures that each recursive set always has the
haftmann@25557
    34
  same type in all introduction rules*)
haftmann@25557
    35
fun unify_consts thy cs intr_ts =
haftmann@25557
    36
  (let
haftmann@25557
    37
    val add_term_consts_2 = fold_aterms (fn Const c => insert (op =) c | _ => I);
haftmann@25557
    38
    fun varify (t, (i, ts)) =
haftmann@25557
    39
      let val t' = map_types (Logic.incr_tvar (i + 1)) (snd (Type.varify [] t))
haftmann@25557
    40
      in (maxidx_of_term t', t'::ts) end;
haftmann@25557
    41
    val (i, cs') = foldr varify (~1, []) cs;
haftmann@25557
    42
    val (i', intr_ts') = foldr varify (i, []) intr_ts;
haftmann@25557
    43
    val rec_consts = fold add_term_consts_2 cs' [];
haftmann@25557
    44
    val intr_consts = fold add_term_consts_2 intr_ts' [];
haftmann@25557
    45
    fun unify (cname, cT) =
haftmann@25557
    46
      let val consts = map snd (filter (fn (c, _) => c = cname) intr_consts)
haftmann@25557
    47
      in fold (Sign.typ_unify thy) ((replicate (length consts) cT) ~~ consts) end;
haftmann@25557
    48
    val (env, _) = fold unify rec_consts (Vartab.empty, i');
haftmann@25557
    49
    val subst = Type.freeze o map_types (Envir.norm_type env)
haftmann@25557
    50
haftmann@25557
    51
  in (map subst cs', map subst intr_ts')
haftmann@25557
    52
  end) handle Type.TUNIFY =>
haftmann@25557
    53
    (warning "Occurrences of recursive constant have non-unifiable types"; (cs, intr_ts));
haftmann@25557
    54
haftmann@25557
    55
haftmann@25557
    56
(* preprocessing of equations *)
haftmann@25557
    57
haftmann@25557
    58
fun process_eqn thy eq rec_fns =
haftmann@25557
    59
  let
haftmann@25557
    60
    val (lhs, rhs) =
wenzelm@29266
    61
      if null (Term.add_vars eq []) then
haftmann@25557
    62
        HOLogic.dest_eq (HOLogic.dest_Trueprop eq)
haftmann@25557
    63
        handle TERM _ => raise RecError "not a proper equation"
haftmann@25557
    64
      else raise RecError "illegal schematic variable(s)";
haftmann@25557
    65
haftmann@25557
    66
    val (recfun, args) = strip_comb lhs;
haftmann@25557
    67
    val fnameT = dest_Const recfun handle TERM _ =>
haftmann@25557
    68
      raise RecError "function is not declared as constant in theory";
haftmann@25557
    69
haftmann@25557
    70
    val (ls', rest)  = take_prefix is_Free args;
haftmann@25557
    71
    val (middle, rs') = take_suffix is_Free rest;
haftmann@25557
    72
    val rpos = length ls';
haftmann@25557
    73
haftmann@25557
    74
    val (constr, cargs') = if null middle then raise RecError "constructor missing"
haftmann@25557
    75
      else strip_comb (hd middle);
haftmann@25557
    76
    val (cname, T) = dest_Const constr
haftmann@25557
    77
      handle TERM _ => raise RecError "ill-formed constructor";
haftmann@25557
    78
    val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
haftmann@25557
    79
      raise RecError "cannot determine datatype associated with function"
haftmann@25557
    80
haftmann@25557
    81
    val (ls, cargs, rs) =
haftmann@25557
    82
      (map dest_Free ls', map dest_Free cargs', map dest_Free rs')
haftmann@25557
    83
      handle TERM _ => raise RecError "illegal argument in pattern";
haftmann@25557
    84
    val lfrees = ls @ rs @ cargs;
haftmann@25557
    85
haftmann@25557
    86
    fun check_vars _ [] = ()
haftmann@25557
    87
      | check_vars s vars = raise RecError (s ^ commas_quote (map fst vars))
haftmann@25557
    88
  in
haftmann@25557
    89
    if length middle > 1 then
haftmann@25557
    90
      raise RecError "more than one non-variable in pattern"
haftmann@25557
    91
    else
haftmann@25557
    92
     (check_vars "repeated variable names in pattern: " (duplicates (op =) lfrees);
haftmann@25557
    93
      check_vars "extra variables on rhs: "
wenzelm@29266
    94
        (map dest_Free (OldTerm.term_frees rhs) \\ lfrees);
haftmann@25557
    95
      case AList.lookup (op =) rec_fns fnameT of
haftmann@25557
    96
        NONE =>
haftmann@25557
    97
          (fnameT, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
haftmann@25557
    98
      | SOME (_, rpos', eqns) =>
haftmann@25557
    99
          if AList.defined (op =) eqns cname then
haftmann@25557
   100
            raise RecError "constructor already occurred as pattern"
haftmann@25557
   101
          else if rpos <> rpos' then
haftmann@25557
   102
            raise RecError "position of recursive argument inconsistent"
haftmann@25557
   103
          else
haftmann@25557
   104
            AList.update (op =) (fnameT, (tname, rpos, (cname, (ls, cargs, rs, rhs, eq))::eqns))
haftmann@25557
   105
              rec_fns)
haftmann@25557
   106
  end
haftmann@25557
   107
  handle RecError s => primrec_eq_err thy s eq;
haftmann@25557
   108
haftmann@25557
   109
fun process_fun thy descr rec_eqns (i, fnameT as (fname, _)) (fnameTs, fnss) =
haftmann@25557
   110
  let
haftmann@25557
   111
    val (_, (tname, _, constrs)) = List.nth (descr, i);
haftmann@25557
   112
haftmann@25557
   113
    (* substitute "fname ls x rs" by "y ls rs" for (x, (_, y)) in subs *)
haftmann@25557
   114
haftmann@25557
   115
    fun subst [] t fs = (t, fs)
haftmann@25557
   116
      | subst subs (Abs (a, T, t)) fs =
haftmann@25557
   117
          fs
haftmann@25557
   118
          |> subst subs t
haftmann@25557
   119
          |-> (fn t' => pair (Abs (a, T, t')))
haftmann@25557
   120
      | subst subs (t as (_ $ _)) fs =
haftmann@25557
   121
          let
haftmann@25557
   122
            val (f, ts) = strip_comb t;
haftmann@25557
   123
          in
haftmann@25557
   124
            if is_Const f andalso dest_Const f mem map fst rec_eqns then
haftmann@25557
   125
              let
haftmann@25557
   126
                val fnameT' as (fname', _) = dest_Const f;
haftmann@25557
   127
                val (_, rpos, _) = the (AList.lookup (op =) rec_eqns fnameT');
haftmann@25557
   128
                val ls = Library.take (rpos, ts);
haftmann@25557
   129
                val rest = Library.drop (rpos, ts);
haftmann@25557
   130
                val (x', rs) = (hd rest, tl rest)
haftmann@25557
   131
                  handle Empty => raise RecError ("not enough arguments\
haftmann@25557
   132
                   \ in recursive application\nof function " ^ quote fname' ^ " on rhs");
haftmann@25557
   133
                val (x, xs) = strip_comb x'
haftmann@25557
   134
              in case AList.lookup (op =) subs x
haftmann@25557
   135
               of NONE =>
haftmann@25557
   136
                    fs
haftmann@25557
   137
                    |> fold_map (subst subs) ts
haftmann@25557
   138
                    |-> (fn ts' => pair (list_comb (f, ts')))
haftmann@25557
   139
                | SOME (i', y) =>
haftmann@25557
   140
                    fs
haftmann@25557
   141
                    |> fold_map (subst subs) (xs @ ls @ rs)
haftmann@25557
   142
                    ||> process_fun thy descr rec_eqns (i', fnameT')
haftmann@25557
   143
                    |-> (fn ts' => pair (list_comb (y, ts')))
haftmann@25557
   144
              end
haftmann@25557
   145
            else
haftmann@25557
   146
              fs
haftmann@25557
   147
              |> fold_map (subst subs) (f :: ts)
haftmann@25557
   148
              |-> (fn (f'::ts') => pair (list_comb (f', ts')))
haftmann@25557
   149
          end
haftmann@25557
   150
      | subst _ t fs = (t, fs);
haftmann@25557
   151
haftmann@25557
   152
    (* translate rec equations into function arguments suitable for rec comb *)
haftmann@25557
   153
haftmann@25557
   154
    fun trans eqns (cname, cargs) (fnameTs', fnss', fns) =
haftmann@25557
   155
      (case AList.lookup (op =) eqns cname of
haftmann@25557
   156
          NONE => (warning ("No equation for constructor " ^ quote cname ^
haftmann@25557
   157
            "\nin definition of function " ^ quote fname);
haftmann@25557
   158
              (fnameTs', fnss', (Const ("HOL.undefined", dummyT))::fns))
haftmann@25557
   159
        | SOME (ls, cargs', rs, rhs, eq) =>
haftmann@25557
   160
            let
haftmann@25557
   161
              val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
haftmann@25557
   162
              val rargs = map fst recs;
haftmann@25557
   163
              val subs = map (rpair dummyT o fst)
wenzelm@29276
   164
                (rev (Term.rename_wrt_term rhs rargs));
haftmann@25557
   165
              val (rhs', (fnameTs'', fnss'')) =
haftmann@25557
   166
                  (subst (map (fn ((x, y), z) =>
haftmann@25557
   167
                               (Free x, (body_index y, Free z)))
haftmann@25557
   168
                          (recs ~~ subs)) rhs (fnameTs', fnss'))
haftmann@25557
   169
                  handle RecError s => primrec_eq_err thy s eq
haftmann@25557
   170
            in (fnameTs'', fnss'',
haftmann@25557
   171
                (list_abs_free (cargs' @ subs @ ls @ rs, rhs'))::fns)
haftmann@25557
   172
            end)
haftmann@25557
   173
haftmann@25557
   174
  in (case AList.lookup (op =) fnameTs i of
haftmann@25557
   175
      NONE =>
haftmann@25557
   176
        if exists (equal fnameT o snd) fnameTs then
haftmann@25557
   177
          raise RecError ("inconsistent functions for datatype " ^ quote tname)
haftmann@25557
   178
        else
haftmann@25557
   179
          let
haftmann@25557
   180
            val (_, _, eqns) = the (AList.lookup (op =) rec_eqns fnameT);
haftmann@25557
   181
            val (fnameTs', fnss', fns) = fold_rev (trans eqns) constrs
haftmann@25557
   182
              ((i, fnameT)::fnameTs, fnss, [])
haftmann@25557
   183
          in
haftmann@25557
   184
            (fnameTs', (i, (fname, #1 (snd (hd eqns)), fns))::fnss')
haftmann@25557
   185
          end
haftmann@25557
   186
    | SOME fnameT' =>
haftmann@25557
   187
        if fnameT = fnameT' then (fnameTs, fnss)
haftmann@25557
   188
        else raise RecError ("inconsistent functions for datatype " ^ quote tname))
haftmann@25557
   189
  end;
haftmann@25557
   190
haftmann@25557
   191
haftmann@25557
   192
(* prepare functions needed for definitions *)
haftmann@25557
   193
haftmann@25557
   194
fun get_fns fns ((i : int, (tname, _, constrs)), rec_name) (fs, defs) =
haftmann@25557
   195
  case AList.lookup (op =) fns i of
haftmann@25557
   196
     NONE =>
haftmann@25557
   197
       let
haftmann@25557
   198
         val dummy_fns = map (fn (_, cargs) => Const ("HOL.undefined",
haftmann@25557
   199
           replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
haftmann@25557
   200
             dummyT ---> HOLogic.unitT)) constrs;
haftmann@25557
   201
         val _ = warning ("No function definition for datatype " ^ quote tname)
haftmann@25557
   202
       in
haftmann@25557
   203
         (dummy_fns @ fs, defs)
haftmann@25557
   204
       end
haftmann@25557
   205
   | SOME (fname, ls, fs') => (fs' @ fs, (fname, ls, rec_name, tname) :: defs);
haftmann@25557
   206
haftmann@25557
   207
haftmann@25557
   208
(* make definition *)
haftmann@25557
   209
haftmann@25557
   210
fun make_def thy fs (fname, ls, rec_name, tname) =
haftmann@25557
   211
  let
haftmann@25557
   212
    val rhs = fold_rev (fn T => fn t => Abs ("", T, t))
haftmann@25557
   213
                    ((map snd ls) @ [dummyT])
haftmann@25557
   214
                    (list_comb (Const (rec_name, dummyT),
haftmann@25557
   215
                                fs @ map Bound (0 ::(length ls downto 1))))
haftmann@25557
   216
    val def_name = Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def";
haftmann@25557
   217
    val def_prop =
haftmann@25557
   218
      singleton (Syntax.check_terms (ProofContext.init thy))
haftmann@25557
   219
        (Logic.mk_equals (Const (fname, dummyT), rhs));
haftmann@25557
   220
  in (def_name, def_prop) end;
haftmann@25557
   221
haftmann@25557
   222
haftmann@25557
   223
(* find datatypes which contain all datatypes in tnames' *)
haftmann@25557
   224
haftmann@25557
   225
fun find_dts (dt_info : datatype_info Symtab.table) _ [] = []
haftmann@25557
   226
  | find_dts dt_info tnames' (tname::tnames) =
haftmann@25557
   227
      (case Symtab.lookup dt_info tname of
haftmann@25557
   228
          NONE => primrec_err (quote tname ^ " is not a datatype")
haftmann@25557
   229
        | SOME dt =>
haftmann@25557
   230
            if tnames' subset (map (#1 o snd) (#descr dt)) then
haftmann@25557
   231
              (tname, dt)::(find_dts dt_info tnames' tnames)
haftmann@25557
   232
            else find_dts dt_info tnames' tnames);
haftmann@25557
   233
haftmann@25557
   234
fun prepare_induct ({descr, induction, ...}: datatype_info) rec_eqns =
haftmann@25557
   235
  let
haftmann@25557
   236
    fun constrs_of (_, (_, _, cs)) =
haftmann@25557
   237
      map (fn (cname:string, (_, cargs, _, _, _)) => (cname, map fst cargs)) cs;
haftmann@25557
   238
    val params_of = these o AList.lookup (op =) (List.concat (map constrs_of rec_eqns));
haftmann@25557
   239
  in
haftmann@25557
   240
    induction
haftmann@25557
   241
    |> RuleCases.rename_params (map params_of (List.concat (map (map #1 o #3 o #2) descr)))
haftmann@25557
   242
    |> RuleCases.save induction
haftmann@25557
   243
  end;
haftmann@25557
   244
haftmann@25557
   245
local
haftmann@25557
   246
haftmann@25557
   247
fun gen_primrec_i note def alt_name eqns_atts thy =
haftmann@25557
   248
  let
haftmann@25557
   249
    val (eqns, atts) = split_list eqns_atts;
haftmann@25557
   250
    val dt_info = DatatypePackage.get_datatypes thy;
haftmann@25557
   251
    val rec_eqns = fold_rev (process_eqn thy o snd) eqns [] ;
haftmann@25557
   252
    val tnames = distinct (op =) (map (#1 o snd) rec_eqns);
haftmann@25557
   253
    val dts = find_dts dt_info tnames tnames;
haftmann@25557
   254
    val main_fns =
haftmann@25557
   255
      map (fn (tname, {index, ...}) =>
haftmann@25557
   256
        (index,
haftmann@25557
   257
          (fst o the o find_first (fn f => (#1 o snd) f = tname)) rec_eqns))
haftmann@25557
   258
      dts;
haftmann@25557
   259
    val {descr, rec_names, rec_rewrites, ...} =
haftmann@25557
   260
      if null dts then
haftmann@25557
   261
        primrec_err ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
haftmann@25557
   262
      else snd (hd dts);
haftmann@25557
   263
    val (fnameTs, fnss) =
haftmann@25557
   264
      fold_rev (process_fun thy descr rec_eqns) main_fns ([], []);
haftmann@25557
   265
    val (fs, defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
haftmann@25557
   266
    val defs' = map (make_def thy fs) defs;
haftmann@25557
   267
    val nameTs1 = map snd fnameTs;
haftmann@25557
   268
    val nameTs2 = map fst rec_eqns;
haftmann@25557
   269
    val _ = if gen_eq_set (op =) (nameTs1, nameTs2) then ()
haftmann@25557
   270
            else primrec_err ("functions " ^ commas_quote (map fst nameTs2) ^
haftmann@25557
   271
              "\nare not mutually recursive");
haftmann@25557
   272
    val primrec_name =
haftmann@25557
   273
      if alt_name = "" then (space_implode "_" (map (Sign.base_name o #1) defs)) else alt_name;
haftmann@25557
   274
    val (defs_thms', thy') =
haftmann@25557
   275
      thy
haftmann@25557
   276
      |> Sign.add_path primrec_name
haftmann@25557
   277
      |> fold_map def (map (fn (name, t) => ((name, []), t)) defs');
haftmann@25557
   278
    val rewrites = (map mk_meta_eq rec_rewrites) @ map snd defs_thms';
haftmann@25557
   279
    val simps = map (fn (_, t) => Goal.prove_global thy' [] [] t
haftmann@25557
   280
        (fn _ => EVERY [rewrite_goals_tac rewrites, rtac refl 1])) eqns;
haftmann@25557
   281
    val (simps', thy'') =
haftmann@25557
   282
      thy'
haftmann@25557
   283
      |> fold_map note ((map fst eqns ~~ atts) ~~ map single simps);
haftmann@25557
   284
    val simps'' = maps snd simps';
haftmann@25557
   285
  in
haftmann@25557
   286
    thy''
haftmann@28703
   287
    |> note (("simps", [Simplifier.simp_add, Code.add_default_eqn_attribute]), simps'')
haftmann@25557
   288
    |> snd
haftmann@25557
   289
    |> note (("induct", []), [prepare_induct (#2 (hd dts)) rec_eqns])
haftmann@25557
   290
    |> snd
haftmann@25557
   291
    |> Sign.parent_path
haftmann@25557
   292
    |> pair simps''
haftmann@25557
   293
  end;
haftmann@25557
   294
haftmann@25557
   295
fun gen_primrec note def alt_name eqns thy =
haftmann@25557
   296
  let
haftmann@25557
   297
    val ((names, strings), srcss) = apfst split_list (split_list eqns);
haftmann@25557
   298
    val atts = map (map (Attrib.attribute thy)) srcss;
haftmann@25557
   299
    val eqn_ts = map (fn s => Syntax.read_prop_global thy s
haftmann@25557
   300
      handle ERROR msg => cat_error msg ("The error(s) above occurred for " ^ s)) strings;
haftmann@25557
   301
    val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop eq)))
haftmann@25557
   302
      handle TERM _ => primrec_eq_err thy "not a proper equation" eq) eqn_ts;
haftmann@25557
   303
    val (_, eqn_ts') = unify_consts thy rec_ts eqn_ts
haftmann@25557
   304
  in
haftmann@25557
   305
    gen_primrec_i note def alt_name (names ~~ eqn_ts' ~~ atts) thy
haftmann@25557
   306
  end;
haftmann@25557
   307
haftmann@25557
   308
fun thy_note ((name, atts), thms) =
haftmann@25557
   309
  PureThy.add_thmss [((name, thms), atts)] #-> (fn [thms] => pair (name, thms));
haftmann@25557
   310
fun thy_def false ((name, atts), t) =
haftmann@27691
   311
      PureThy.add_defs false [((name, t), atts)] #-> (fn [thm] => pair (name, thm))
haftmann@25557
   312
  | thy_def true ((name, atts), t) =
haftmann@27691
   313
      PureThy.add_defs_unchecked false [((name, t), atts)] #-> (fn [thm] => pair (name, thm));
haftmann@25557
   314
haftmann@25557
   315
in
haftmann@25557
   316
haftmann@25557
   317
val add_primrec = gen_primrec thy_note (thy_def false);
haftmann@25557
   318
val add_primrec_unchecked = gen_primrec thy_note (thy_def true);
haftmann@25557
   319
val add_primrec_i = gen_primrec_i thy_note (thy_def false);
haftmann@25557
   320
val add_primrec_unchecked_i = gen_primrec_i thy_note (thy_def true);
haftmann@25557
   321
fun gen_primrec note def alt_name specs =
haftmann@25557
   322
  gen_primrec_i note def alt_name (map (fn ((name, t), atts) => ((name, atts), t)) specs);
haftmann@25557
   323
haftmann@25557
   324
end;
haftmann@25557
   325
haftmann@25557
   326
haftmann@25557
   327
(* see primrecr_package.ML (* outer syntax *)
haftmann@25557
   328
haftmann@25557
   329
local structure P = OuterParse and K = OuterKeyword in
haftmann@25557
   330
haftmann@25557
   331
val opt_unchecked_name =
haftmann@25557
   332
  Scan.optional (P.$$$ "(" |-- P.!!!
haftmann@25557
   333
    (((P.$$$ "unchecked" >> K true) -- Scan.optional P.name "" ||
haftmann@25557
   334
      P.name >> pair false) --| P.$$$ ")")) (false, "");
haftmann@25557
   335
haftmann@25557
   336
val primrec_decl =
haftmann@25557
   337
  opt_unchecked_name -- Scan.repeat1 (SpecParse.opt_thm_name ":" -- P.prop);
haftmann@25557
   338
haftmann@25557
   339
val _ =
haftmann@25557
   340
  OuterSyntax.command "primrec" "define primitive recursive functions on datatypes" K.thy_decl
haftmann@25557
   341
    (primrec_decl >> (fn ((unchecked, alt_name), eqns) =>
haftmann@25557
   342
      Toplevel.theory (snd o
haftmann@25557
   343
        (if unchecked then add_primrec_unchecked else add_primrec) alt_name
haftmann@25557
   344
          (map P.triple_swap eqns))));
haftmann@25557
   345
haftmann@25557
   346
end;*)
haftmann@25557
   347
haftmann@25557
   348
end;