src/HOL/Tools/primrec_package.ML
author wenzelm
Sat Jan 14 22:25:34 2006 +0100 (2006-01-14)
changeset 18688 abf0f018b5ec
parent 18678 dd0c569fa43d
child 18728 6790126ab5f6
permissions -rw-r--r--
generic attributes;
berghofe@5719
     1
(*  Title:      HOL/Tools/primrec_package.ML
berghofe@5178
     2
    ID:         $Id$
wenzelm@11539
     3
    Author:     Stefan Berghofer, TU Muenchen and Norbert Voelker, FernUni Hagen
berghofe@5178
     4
wenzelm@6359
     5
Package for defining functions on datatypes by primitive recursion.
berghofe@5178
     6
*)
berghofe@5178
     7
berghofe@5178
     8
signature PRIMREC_PACKAGE =
berghofe@5178
     9
sig
wenzelm@6427
    10
  val quiet_mode: bool ref
wenzelm@15703
    11
  val add_primrec: string -> ((bstring * string) * Attrib.src list) list
wenzelm@6359
    12
    -> theory -> theory * thm list
wenzelm@6425
    13
  val add_primrec_i: string -> ((bstring * term) * theory attribute list) list
wenzelm@6359
    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@7544
    26
  primrec_err (s ^ "\nin\n" ^ quote (Sign.string_of_term sign eq));
wenzelm@6427
    27
wenzelm@6427
    28
wenzelm@6427
    29
(* messages *)
wenzelm@6427
    30
wenzelm@6427
    31
val quiet_mode = ref false;
wenzelm@6427
    32
fun message s = if ! quiet_mode then () else writeln s;
berghofe@5178
    33
wenzelm@6359
    34
berghofe@5178
    35
(* preprocessing of equations *)
berghofe@5178
    36
berghofe@5178
    37
fun process_eqn sign (eq, rec_fns) = 
berghofe@5178
    38
  let
paulson@6032
    39
    val (lhs, rhs) = 
paulson@6032
    40
	if null (term_vars eq) then
paulson@6032
    41
	    HOLogic.dest_eq (HOLogic.dest_Trueprop eq)
berghofe@7016
    42
	      handle TERM _ => raise RecError "not a proper equation"
paulson@6032
    43
	else raise RecError "illegal schematic variable(s)";
berghofe@5178
    44
berghofe@5178
    45
    val (recfun, args) = strip_comb lhs;
berghofe@16765
    46
    val fnameT = dest_Const recfun handle TERM _ => 
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@7016
    56
      handle TERM _ => raise RecError "ill-formed constructor";
berghofe@7016
    57
    val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
berghofe@5178
    58
      raise RecError "cannot determine datatype associated with function"
berghofe@5178
    59
paulson@6037
    60
    val (ls, cargs, rs) = (map dest_Free ls', 
paulson@6037
    61
			   map dest_Free cargs', 
paulson@6037
    62
			   map dest_Free rs')
berghofe@7016
    63
      handle TERM _ => raise RecError "illegal argument in pattern";
berghofe@5178
    64
    val lfrees = ls @ rs @ cargs;
berghofe@5178
    65
berghofe@12474
    66
    fun check_vars _ [] = ()
berghofe@12474
    67
      | check_vars s vars = raise RecError (s ^ commas_quote (map fst vars))
berghofe@5178
    68
  in
paulson@8973
    69
    if length middle > 1 then 
berghofe@5178
    70
      raise RecError "more than one non-variable in pattern"
berghofe@12474
    71
    else
berghofe@12474
    72
     (check_vars "repeated variable names in pattern: " (duplicates lfrees);
berghofe@12474
    73
      check_vars "extra variables on rhs: "
berghofe@12474
    74
        (map dest_Free (term_frees rhs) \\ lfrees);
wenzelm@17184
    75
      case AList.lookup (op =) rec_fns fnameT of
skalberg@15531
    76
        NONE =>
berghofe@16765
    77
          (fnameT, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
skalberg@15531
    78
      | SOME (_, rpos', eqns) =>
wenzelm@17184
    79
          if AList.defined (op =) eqns cname then
paulson@6037
    80
            raise RecError "constructor already occurred as pattern"
berghofe@5178
    81
          else if rpos <> rpos' then
berghofe@5178
    82
            raise RecError "position of recursive argument inconsistent"
berghofe@5178
    83
          else
haftmann@17314
    84
            AList.update (op =) (fnameT, (tname, rpos, (cname, (ls, cargs, rs, rhs, eq))::eqns))
haftmann@17314
    85
              rec_fns)
berghofe@5178
    86
  end
berghofe@5178
    87
  handle RecError s => primrec_eq_err sign s eq;
berghofe@5178
    88
berghofe@16765
    89
fun process_fun sign descr rec_eqns ((i, fnameT as (fname, _)), (fnameTs, fnss)) =
berghofe@5178
    90
  let
skalberg@15570
    91
    val (_, (tname, _, constrs)) = List.nth (descr, i);
berghofe@5178
    92
berghofe@5178
    93
    (* substitute "fname ls x rs" by "y ls rs" for (x, (_, y)) in subs *)
berghofe@5178
    94
berghofe@5178
    95
    fun subst [] x = x
berghofe@5178
    96
      | subst subs (fs, Abs (a, T, t)) =
berghofe@5178
    97
          let val (fs', t') = subst subs (fs, t)
berghofe@5178
    98
          in (fs', Abs (a, T, t')) end
berghofe@5178
    99
      | subst subs (fs, t as (_ $ _)) =
berghofe@5178
   100
          let val (f, ts) = strip_comb t;
berghofe@5178
   101
          in
berghofe@16765
   102
            if is_Const f andalso dest_Const f mem map fst rec_eqns then
berghofe@5178
   103
              let
berghofe@16765
   104
                val fnameT' as (fname', _) = dest_Const f;
wenzelm@17184
   105
                val (_, rpos, _) = the (AList.lookup (op =) rec_eqns fnameT');
skalberg@15570
   106
                val ls = Library.take (rpos, ts);
skalberg@15570
   107
                val rest = Library.drop (rpos, ts);
berghofe@7016
   108
                val (x', rs) = (hd rest, tl rest)
skalberg@15570
   109
                  handle Empty => raise RecError ("not enough arguments\
berghofe@7016
   110
                   \ in recursive application\nof function " ^ quote fname' ^ " on rhs");
berghofe@7016
   111
                val (x, xs) = strip_comb x'
berghofe@5178
   112
              in 
wenzelm@17184
   113
                (case AList.lookup (op =) subs x of
skalberg@15531
   114
                    NONE =>
berghofe@5178
   115
                      let
berghofe@5178
   116
                        val (fs', ts') = foldl_map (subst subs) (fs, ts)
berghofe@5178
   117
                      in (fs', list_comb (f, ts')) end
skalberg@15531
   118
                  | SOME (i', y) =>
berghofe@5178
   119
                      let
berghofe@7016
   120
                        val (fs', ts') = foldl_map (subst subs) (fs, xs @ ls @ rs);
berghofe@16765
   121
                        val fs'' = process_fun sign descr rec_eqns ((i', fnameT'), fs')
berghofe@5178
   122
                      in (fs'', list_comb (y, ts'))
berghofe@5178
   123
                      end)
berghofe@5178
   124
              end
berghofe@5178
   125
            else
berghofe@5178
   126
              let
berghofe@5178
   127
                val (fs', f'::ts') = foldl_map (subst subs) (fs, f::ts)
berghofe@5178
   128
              in (fs', list_comb (f', ts')) end
berghofe@5178
   129
          end
berghofe@5178
   130
      | subst _ x = x;
berghofe@5178
   131
berghofe@5178
   132
    (* translate rec equations into function arguments suitable for rec comb *)
berghofe@5178
   133
berghofe@16765
   134
    fun trans eqns ((cname, cargs), (fnameTs', fnss', fns)) =
wenzelm@17184
   135
      (case AList.lookup (op =) eqns cname of
skalberg@15531
   136
          NONE => (warning ("No equation for constructor " ^ quote cname ^
wenzelm@6427
   137
            "\nin definition of function " ^ quote fname);
berghofe@16765
   138
              (fnameTs', fnss', (Const ("arbitrary", dummyT))::fns))
skalberg@15531
   139
        | SOME (ls, cargs', rs, rhs, eq) =>
berghofe@5178
   140
            let
skalberg@15570
   141
              val recs = List.filter (is_rec_type o snd) (cargs' ~~ cargs);
berghofe@5178
   142
              val rargs = map fst recs;
paulson@6037
   143
              val subs = map (rpair dummyT o fst) 
paulson@6037
   144
		             (rev (rename_wrt_term rhs rargs));
berghofe@16765
   145
              val ((fnameTs'', fnss''), rhs') = 
paulson@6037
   146
		  (subst (map (fn ((x, y), z) =>
berghofe@13641
   147
			       (Free x, (body_index y, Free z)))
paulson@6037
   148
			  (recs ~~ subs))
berghofe@16765
   149
		   ((fnameTs', fnss'), rhs))
berghofe@5178
   150
                  handle RecError s => primrec_eq_err sign s eq
berghofe@16765
   151
            in (fnameTs'', fnss'', 
paulson@6037
   152
		(list_abs_free (cargs' @ subs @ ls @ rs, rhs'))::fns)
berghofe@5178
   153
            end)
berghofe@5178
   154
wenzelm@17184
   155
  in (case AList.lookup (op =) fnameTs i of
skalberg@15531
   156
      NONE =>
berghofe@16765
   157
        if exists (equal fnameT o snd) fnameTs then
wenzelm@6427
   158
          raise RecError ("inconsistent functions for datatype " ^ quote tname)
berghofe@5178
   159
        else
berghofe@5178
   160
          let
wenzelm@17184
   161
            val (_, _, eqns) = the (AList.lookup (op =) rec_eqns fnameT);
berghofe@16765
   162
            val (fnameTs', fnss', fns) = foldr (trans eqns)
berghofe@16765
   163
              ((i, fnameT)::fnameTs, fnss, []) constrs
berghofe@5178
   164
          in
berghofe@16765
   165
            (fnameTs', (i, (fname, #1 (snd (hd eqns)), fns))::fnss')
berghofe@5178
   166
          end
berghofe@16765
   167
    | SOME fnameT' =>
berghofe@16765
   168
        if fnameT = fnameT' then (fnameTs, fnss)
wenzelm@6427
   169
        else raise RecError ("inconsistent functions for datatype " ^ quote tname))
berghofe@5178
   170
  end;
berghofe@5178
   171
wenzelm@6359
   172
berghofe@5178
   173
(* prepare functions needed for definitions *)
berghofe@5178
   174
berghofe@5178
   175
fun get_fns fns (((i, (tname, _, constrs)), rec_name), (fs, defs)) =
wenzelm@17184
   176
  case AList.lookup (op =) fns i of
skalberg@15531
   177
     NONE =>
berghofe@5178
   178
       let
berghofe@5178
   179
         val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
skalberg@15570
   180
           replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
berghofe@5178
   181
             dummyT ---> HOLogic.unitT)) constrs;
wenzelm@6427
   182
         val _ = warning ("No function definition for datatype " ^ quote tname)
berghofe@5178
   183
       in
berghofe@5178
   184
         (dummy_fns @ fs, defs)
berghofe@5178
   185
       end
skalberg@15531
   186
   | SOME (fname, ls, fs') => (fs' @ fs, (fname, ls, rec_name, tname)::defs);
berghofe@5178
   187
wenzelm@6359
   188
berghofe@5178
   189
(* make definition *)
berghofe@5178
   190
berghofe@5178
   191
fun make_def sign fs (fname, ls, rec_name, tname) =
berghofe@5178
   192
  let
skalberg@15574
   193
    val rhs = foldr (fn (T, t) => Abs ("", T, t)) 
skalberg@15574
   194
	            (list_comb (Const (rec_name, dummyT),
skalberg@15574
   195
				fs @ map Bound (0 ::(length ls downto 1))))
skalberg@15574
   196
		    ((map snd ls) @ [dummyT]);
berghofe@5178
   197
    val defpair = (Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def",
paulson@6037
   198
		   Logic.mk_equals (Const (fname, dummyT), rhs))
wenzelm@6394
   199
  in Theory.inferT_axm sign defpair end;
berghofe@5178
   200
wenzelm@6359
   201
berghofe@5178
   202
(* find datatypes which contain all datatypes in tnames' *)
berghofe@5178
   203
berghofe@5178
   204
fun find_dts (dt_info : datatype_info Symtab.table) _ [] = []
berghofe@5178
   205
  | find_dts dt_info tnames' (tname::tnames) =
wenzelm@17412
   206
      (case Symtab.lookup dt_info tname of
skalberg@15531
   207
          NONE => primrec_err (quote tname ^ " is not a datatype")
skalberg@15531
   208
        | SOME dt =>
berghofe@5178
   209
            if tnames' subset (map (#1 o snd) (#descr dt)) then
berghofe@5178
   210
              (tname, dt)::(find_dts dt_info tnames' tnames)
berghofe@5178
   211
            else find_dts dt_info tnames' tnames);
berghofe@5178
   212
wenzelm@8432
   213
fun prepare_induct ({descr, induction, ...}: datatype_info) rec_eqns =
wenzelm@8432
   214
  let
wenzelm@8432
   215
    fun constrs_of (_, (_, _, cs)) =
wenzelm@8432
   216
      map (fn (cname:string, (_, cargs, _, _, _)) => (cname, map fst cargs)) cs;
wenzelm@17184
   217
    val params_of = these o AList.lookup (op =) (List.concat (map constrs_of rec_eqns));
wenzelm@8432
   218
  in
wenzelm@8432
   219
    induction
skalberg@15570
   220
    |> RuleCases.rename_params (map params_of (List.concat (map (map #1 o #3 o #2) descr)))
wenzelm@10525
   221
    |> RuleCases.save induction
wenzelm@8432
   222
  end;
wenzelm@8432
   223
wenzelm@6359
   224
fun add_primrec_i alt_name eqns_atts thy =
berghofe@5178
   225
  let
wenzelm@6359
   226
    val (eqns, atts) = split_list eqns_atts;
wenzelm@6394
   227
    val sg = Theory.sign_of thy;
berghofe@5178
   228
    val dt_info = DatatypePackage.get_datatypes thy;
skalberg@15574
   229
    val rec_eqns = foldr (process_eqn sg) [] (map snd eqns);
berghofe@5178
   230
    val tnames = distinct (map (#1 o snd) rec_eqns);
berghofe@5178
   231
    val dts = find_dts dt_info tnames tnames;
paulson@6037
   232
    val main_fns = 
haftmann@18362
   233
      map (fn (tname, {index, ...}) =>
haftmann@18362
   234
        (index, 
haftmann@18362
   235
          (fst o the o find_first (fn f => (#1 o snd) f = tname)) rec_eqns))
haftmann@18362
   236
      dts;
paulson@6037
   237
    val {descr, rec_names, rec_rewrites, ...} = 
haftmann@18362
   238
      if null dts then
haftmann@18362
   239
        primrec_err ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
haftmann@18362
   240
      else snd (hd dts);
berghofe@16765
   241
    val (fnameTs, fnss) = foldr (process_fun sg descr rec_eqns)
skalberg@15574
   242
	                       ([], []) main_fns;
skalberg@15574
   243
    val (fs, defs) = foldr (get_fns fnss) ([], []) (descr ~~ rec_names);
berghofe@5178
   244
    val defs' = map (make_def sg fs) defs;
berghofe@16765
   245
    val nameTs1 = map snd fnameTs;
berghofe@16765
   246
    val nameTs2 = map fst rec_eqns;
wenzelm@8432
   247
    val primrec_name =
wenzelm@8432
   248
      if alt_name = "" then (space_implode "_" (map (Sign.base_name o #1) defs)) else alt_name;
haftmann@18358
   249
    val (defs_thms', thy') = thy |> Theory.add_path primrec_name |>
berghofe@16765
   250
      (if eq_set (nameTs1, nameTs2) then (PureThy.add_defs_i false o map Thm.no_attributes) defs'
berghofe@16765
   251
       else primrec_err ("functions " ^ commas_quote (map fst nameTs2) ^
berghofe@5216
   252
         "\nare not mutually recursive"));
berghofe@13641
   253
    val rewrites = (map mk_meta_eq rec_rewrites) @ defs_thms';
berghofe@16765
   254
    val _ = message ("Proving equations for primrec function(s) " ^
berghofe@16765
   255
      commas_quote (map fst nameTs1) ^ " ...");
wenzelm@17985
   256
    val simps = map (fn (_, t) => standard (Goal.prove thy' [] [] t
wenzelm@17985
   257
        (fn _ => EVERY [rewrite_goals_tac rewrites, rtac refl 1]))) eqns;
haftmann@18377
   258
    val (simps', thy'') = PureThy.add_thms ((map fst eqns ~~ simps) ~~ atts) thy';
berghofe@9575
   259
    val thy''' = thy''
haftmann@18377
   260
      |> (snd o PureThy.add_thmss [(("simps", simps'),
wenzelm@18688
   261
           [Attrib.theory Simplifier.simp_add, RecfunCodegen.add NONE])])
haftmann@18377
   262
      |> (snd o PureThy.add_thms [(("induct", prepare_induct (#2 (hd dts)) rec_eqns), [])])
berghofe@9575
   263
      |> Theory.parent_path
berghofe@8480
   264
  in
berghofe@12448
   265
    (thy''', simps')
berghofe@8480
   266
  end;
wenzelm@6359
   267
wenzelm@6359
   268
berghofe@7016
   269
fun add_primrec alt_name eqns thy =
berghofe@7016
   270
  let
berghofe@7544
   271
    val sign = Theory.sign_of thy;
berghofe@7016
   272
    val ((names, strings), srcss) = apfst split_list (split_list eqns);
berghofe@7016
   273
    val atts = map (map (Attrib.global_attribute thy)) srcss;
berghofe@14258
   274
    val eqn_ts = map (fn s => term_of (Thm.read_cterm sign (s, propT))
wenzelm@18678
   275
      handle ERROR msg => cat_error msg ("The error(s) above occurred for " ^ s)) strings;
berghofe@7016
   276
    val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop eq)))
berghofe@7544
   277
      handle TERM _ => primrec_eq_err sign "not a proper equation" eq) eqn_ts;
berghofe@7016
   278
    val (_, eqn_ts') = InductivePackage.unify_consts (sign_of thy) rec_ts eqn_ts
berghofe@7016
   279
  in
berghofe@7016
   280
    add_primrec_i alt_name (names ~~ eqn_ts' ~~ atts) thy
berghofe@7016
   281
  end;
wenzelm@6359
   282
berghofe@5178
   283
wenzelm@6359
   284
(* outer syntax *)
wenzelm@6359
   285
wenzelm@17057
   286
local structure P = OuterParse and K = OuterKeyword in
wenzelm@6359
   287
wenzelm@6359
   288
val primrec_decl =
wenzelm@6723
   289
  Scan.optional (P.$$$ "(" |-- P.name --| P.$$$ ")") "" --
wenzelm@12876
   290
    Scan.repeat1 (P.opt_thm_name ":" -- P.prop);
wenzelm@6359
   291
wenzelm@6359
   292
val primrecP =
wenzelm@6723
   293
  OuterSyntax.command "primrec" "define primitive recursive functions on datatypes" K.thy_decl
wenzelm@6359
   294
    (primrec_decl >> (fn (alt_name, eqns) =>
wenzelm@6723
   295
      Toplevel.theory (#1 o add_primrec alt_name (map P.triple_swap eqns))));
wenzelm@6359
   296
wenzelm@6359
   297
val _ = OuterSyntax.add_parsers [primrecP];
berghofe@5178
   298
berghofe@5178
   299
end;
wenzelm@6384
   300
wenzelm@6384
   301
wenzelm@6384
   302
end;
wenzelm@15705
   303