src/HOL/Tools/primrec_package.ML
author berghofe
Fri Jul 08 11:57:15 2005 +0200 (2005-07-08)
changeset 16765 b8b1f310877f
parent 16646 666774b0d1b0
child 17057 0934ac31985f
permissions -rw-r--r--
Some changes to allow mutually recursive, overloaded functions with same name.
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);
berghofe@16765
    75
      case assoc (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) =>
skalberg@15570
    79
          if isSome (assoc (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
paulson@6037
    84
            overwrite (rec_fns, 
berghofe@16765
    85
		       (fnameT, 
paulson@6037
    86
			(tname, rpos,
paulson@6037
    87
			 (cname, (ls, cargs, rs, rhs, eq))::eqns))))
berghofe@5178
    88
  end
berghofe@5178
    89
  handle RecError s => primrec_eq_err sign s eq;
berghofe@5178
    90
berghofe@16765
    91
fun process_fun sign descr rec_eqns ((i, fnameT as (fname, _)), (fnameTs, fnss)) =
berghofe@5178
    92
  let
skalberg@15570
    93
    val (_, (tname, _, constrs)) = List.nth (descr, i);
berghofe@5178
    94
berghofe@5178
    95
    (* substitute "fname ls x rs" by "y ls rs" for (x, (_, y)) in subs *)
berghofe@5178
    96
berghofe@5178
    97
    fun subst [] x = x
berghofe@5178
    98
      | subst subs (fs, Abs (a, T, t)) =
berghofe@5178
    99
          let val (fs', t') = subst subs (fs, t)
berghofe@5178
   100
          in (fs', Abs (a, T, t')) end
berghofe@5178
   101
      | subst subs (fs, t as (_ $ _)) =
berghofe@5178
   102
          let val (f, ts) = strip_comb t;
berghofe@5178
   103
          in
berghofe@16765
   104
            if is_Const f andalso dest_Const f mem map fst rec_eqns then
berghofe@5178
   105
              let
berghofe@16765
   106
                val fnameT' as (fname', _) = dest_Const f;
berghofe@16765
   107
                val (_, rpos, _) = valOf (assoc (rec_eqns, fnameT'));
skalberg@15570
   108
                val ls = Library.take (rpos, ts);
skalberg@15570
   109
                val rest = Library.drop (rpos, ts);
berghofe@7016
   110
                val (x', rs) = (hd rest, tl rest)
skalberg@15570
   111
                  handle Empty => raise RecError ("not enough arguments\
berghofe@7016
   112
                   \ in recursive application\nof function " ^ quote fname' ^ " on rhs");
berghofe@7016
   113
                val (x, xs) = strip_comb x'
berghofe@5178
   114
              in 
berghofe@5178
   115
                (case assoc (subs, x) of
skalberg@15531
   116
                    NONE =>
berghofe@5178
   117
                      let
berghofe@5178
   118
                        val (fs', ts') = foldl_map (subst subs) (fs, ts)
berghofe@5178
   119
                      in (fs', list_comb (f, ts')) end
skalberg@15531
   120
                  | SOME (i', y) =>
berghofe@5178
   121
                      let
berghofe@7016
   122
                        val (fs', ts') = foldl_map (subst subs) (fs, xs @ ls @ rs);
berghofe@16765
   123
                        val fs'' = process_fun sign descr rec_eqns ((i', fnameT'), fs')
berghofe@5178
   124
                      in (fs'', list_comb (y, ts'))
berghofe@5178
   125
                      end)
berghofe@5178
   126
              end
berghofe@5178
   127
            else
berghofe@5178
   128
              let
berghofe@5178
   129
                val (fs', f'::ts') = foldl_map (subst subs) (fs, f::ts)
berghofe@5178
   130
              in (fs', list_comb (f', ts')) end
berghofe@5178
   131
          end
berghofe@5178
   132
      | subst _ x = x;
berghofe@5178
   133
berghofe@5178
   134
    (* translate rec equations into function arguments suitable for rec comb *)
berghofe@5178
   135
berghofe@16765
   136
    fun trans eqns ((cname, cargs), (fnameTs', fnss', fns)) =
berghofe@5178
   137
      (case assoc (eqns, cname) of
skalberg@15531
   138
          NONE => (warning ("No equation for constructor " ^ quote cname ^
wenzelm@6427
   139
            "\nin definition of function " ^ quote fname);
berghofe@16765
   140
              (fnameTs', fnss', (Const ("arbitrary", dummyT))::fns))
skalberg@15531
   141
        | SOME (ls, cargs', rs, rhs, eq) =>
berghofe@5178
   142
            let
skalberg@15570
   143
              val recs = List.filter (is_rec_type o snd) (cargs' ~~ cargs);
berghofe@5178
   144
              val rargs = map fst recs;
paulson@6037
   145
              val subs = map (rpair dummyT o fst) 
paulson@6037
   146
		             (rev (rename_wrt_term rhs rargs));
berghofe@16765
   147
              val ((fnameTs'', fnss''), rhs') = 
paulson@6037
   148
		  (subst (map (fn ((x, y), z) =>
berghofe@13641
   149
			       (Free x, (body_index y, Free z)))
paulson@6037
   150
			  (recs ~~ subs))
berghofe@16765
   151
		   ((fnameTs', fnss'), rhs))
berghofe@5178
   152
                  handle RecError s => primrec_eq_err sign s eq
berghofe@16765
   153
            in (fnameTs'', fnss'', 
paulson@6037
   154
		(list_abs_free (cargs' @ subs @ ls @ rs, rhs'))::fns)
berghofe@5178
   155
            end)
berghofe@5178
   156
berghofe@16765
   157
  in (case assoc (fnameTs, i) of
skalberg@15531
   158
      NONE =>
berghofe@16765
   159
        if exists (equal fnameT o snd) fnameTs then
wenzelm@6427
   160
          raise RecError ("inconsistent functions for datatype " ^ quote tname)
berghofe@5178
   161
        else
berghofe@5178
   162
          let
berghofe@16765
   163
            val (_, _, eqns) = valOf (assoc (rec_eqns, fnameT));
berghofe@16765
   164
            val (fnameTs', fnss', fns) = foldr (trans eqns)
berghofe@16765
   165
              ((i, fnameT)::fnameTs, fnss, []) constrs
berghofe@5178
   166
          in
berghofe@16765
   167
            (fnameTs', (i, (fname, #1 (snd (hd eqns)), fns))::fnss')
berghofe@5178
   168
          end
berghofe@16765
   169
    | SOME fnameT' =>
berghofe@16765
   170
        if fnameT = fnameT' then (fnameTs, fnss)
wenzelm@6427
   171
        else raise RecError ("inconsistent functions for datatype " ^ quote tname))
berghofe@5178
   172
  end;
berghofe@5178
   173
wenzelm@6359
   174
berghofe@5178
   175
(* prepare functions needed for definitions *)
berghofe@5178
   176
berghofe@5178
   177
fun get_fns fns (((i, (tname, _, constrs)), rec_name), (fs, defs)) =
berghofe@5178
   178
  case assoc (fns, i) of
skalberg@15531
   179
     NONE =>
berghofe@5178
   180
       let
berghofe@5178
   181
         val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
skalberg@15570
   182
           replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
berghofe@5178
   183
             dummyT ---> HOLogic.unitT)) constrs;
wenzelm@6427
   184
         val _ = warning ("No function definition for datatype " ^ quote tname)
berghofe@5178
   185
       in
berghofe@5178
   186
         (dummy_fns @ fs, defs)
berghofe@5178
   187
       end
skalberg@15531
   188
   | SOME (fname, ls, fs') => (fs' @ fs, (fname, ls, rec_name, tname)::defs);
berghofe@5178
   189
wenzelm@6359
   190
berghofe@5178
   191
(* make definition *)
berghofe@5178
   192
berghofe@5178
   193
fun make_def sign fs (fname, ls, rec_name, tname) =
berghofe@5178
   194
  let
skalberg@15574
   195
    val rhs = foldr (fn (T, t) => Abs ("", T, t)) 
skalberg@15574
   196
	            (list_comb (Const (rec_name, dummyT),
skalberg@15574
   197
				fs @ map Bound (0 ::(length ls downto 1))))
skalberg@15574
   198
		    ((map snd ls) @ [dummyT]);
berghofe@5178
   199
    val defpair = (Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def",
paulson@6037
   200
		   Logic.mk_equals (Const (fname, dummyT), rhs))
wenzelm@6394
   201
  in Theory.inferT_axm sign defpair end;
berghofe@5178
   202
wenzelm@6359
   203
berghofe@5178
   204
(* find datatypes which contain all datatypes in tnames' *)
berghofe@5178
   205
berghofe@5178
   206
fun find_dts (dt_info : datatype_info Symtab.table) _ [] = []
berghofe@5178
   207
  | find_dts dt_info tnames' (tname::tnames) =
berghofe@5178
   208
      (case Symtab.lookup (dt_info, tname) of
skalberg@15531
   209
          NONE => primrec_err (quote tname ^ " is not a datatype")
skalberg@15531
   210
        | SOME dt =>
berghofe@5178
   211
            if tnames' subset (map (#1 o snd) (#descr dt)) then
berghofe@5178
   212
              (tname, dt)::(find_dts dt_info tnames' tnames)
berghofe@5178
   213
            else find_dts dt_info tnames' tnames);
berghofe@5178
   214
wenzelm@8432
   215
fun prepare_induct ({descr, induction, ...}: datatype_info) rec_eqns =
wenzelm@8432
   216
  let
wenzelm@8432
   217
    fun constrs_of (_, (_, _, cs)) =
wenzelm@8432
   218
      map (fn (cname:string, (_, cargs, _, _, _)) => (cname, map fst cargs)) cs;
skalberg@15570
   219
    val params_of = Library.assocs (List.concat (map constrs_of rec_eqns));
wenzelm@8432
   220
  in
wenzelm@8432
   221
    induction
skalberg@15570
   222
    |> RuleCases.rename_params (map params_of (List.concat (map (map #1 o #3 o #2) descr)))
wenzelm@10525
   223
    |> RuleCases.save induction
wenzelm@8432
   224
  end;
wenzelm@8432
   225
wenzelm@6359
   226
fun add_primrec_i alt_name eqns_atts thy =
berghofe@5178
   227
  let
wenzelm@6359
   228
    val (eqns, atts) = split_list eqns_atts;
wenzelm@6394
   229
    val sg = Theory.sign_of thy;
berghofe@5178
   230
    val dt_info = DatatypePackage.get_datatypes thy;
skalberg@15574
   231
    val rec_eqns = foldr (process_eqn sg) [] (map snd eqns);
berghofe@5178
   232
    val tnames = distinct (map (#1 o snd) rec_eqns);
berghofe@5178
   233
    val dts = find_dts dt_info tnames tnames;
paulson@6037
   234
    val main_fns = 
paulson@6037
   235
	map (fn (tname, {index, ...}) =>
paulson@6037
   236
	     (index, 
skalberg@15570
   237
	      fst (valOf (find_first (fn f => #1 (snd f) = tname) rec_eqns))))
paulson@6037
   238
	dts;
paulson@6037
   239
    val {descr, rec_names, rec_rewrites, ...} = 
paulson@6037
   240
	if null dts then
wenzelm@6359
   241
	    primrec_err ("datatypes " ^ commas_quote tnames ^ 
paulson@6037
   242
			 "\nare not mutually recursive")
paulson@6037
   243
	else snd (hd dts);
berghofe@16765
   244
    val (fnameTs, fnss) = foldr (process_fun sg descr rec_eqns)
skalberg@15574
   245
	                       ([], []) main_fns;
skalberg@15574
   246
    val (fs, defs) = foldr (get_fns fnss) ([], []) (descr ~~ rec_names);
berghofe@5178
   247
    val defs' = map (make_def sg fs) defs;
berghofe@16765
   248
    val nameTs1 = map snd fnameTs;
berghofe@16765
   249
    val nameTs2 = map fst rec_eqns;
wenzelm@8432
   250
    val primrec_name =
wenzelm@8432
   251
      if alt_name = "" then (space_implode "_" (map (Sign.base_name o #1) defs)) else alt_name;
wenzelm@8432
   252
    val (thy', defs_thms') = thy |> Theory.add_path primrec_name |>
berghofe@16765
   253
      (if eq_set (nameTs1, nameTs2) then (PureThy.add_defs_i false o map Thm.no_attributes) defs'
berghofe@16765
   254
       else primrec_err ("functions " ^ commas_quote (map fst nameTs2) ^
berghofe@5216
   255
         "\nare not mutually recursive"));
berghofe@13641
   256
    val rewrites = (map mk_meta_eq rec_rewrites) @ defs_thms';
berghofe@16765
   257
    val _ = message ("Proving equations for primrec function(s) " ^
berghofe@16765
   258
      commas_quote (map fst nameTs1) ^ " ...");
berghofe@8480
   259
    val simps = map (fn (_, t) => prove_goalw_cterm rewrites (cterm_of (Theory.sign_of thy') t)
berghofe@5178
   260
        (fn _ => [rtac refl 1])) eqns;
berghofe@9575
   261
    val (thy'', simps') = PureThy.add_thms ((map fst eqns ~~ simps) ~~ atts) thy';
berghofe@9575
   262
    val thy''' = thy''
berghofe@16646
   263
      |> (#1 o PureThy.add_thmss [(("simps", simps'),
berghofe@16646
   264
           [Simplifier.simp_add_global, RecfunCodegen.add NONE])])
berghofe@9575
   265
      |> (#1 o PureThy.add_thms [(("induct", prepare_induct (#2 (hd dts)) rec_eqns), [])])
berghofe@9575
   266
      |> Theory.parent_path
berghofe@8480
   267
  in
berghofe@12448
   268
    (thy''', simps')
berghofe@8480
   269
  end;
wenzelm@6359
   270
wenzelm@6359
   271
berghofe@7016
   272
fun add_primrec alt_name eqns thy =
berghofe@7016
   273
  let
berghofe@7544
   274
    val sign = Theory.sign_of thy;
berghofe@7016
   275
    val ((names, strings), srcss) = apfst split_list (split_list eqns);
berghofe@7016
   276
    val atts = map (map (Attrib.global_attribute thy)) srcss;
berghofe@14258
   277
    val eqn_ts = map (fn s => term_of (Thm.read_cterm sign (s, propT))
berghofe@14258
   278
      handle ERROR => error ("The error(s) above occurred for " ^ s)) strings;
berghofe@7016
   279
    val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop eq)))
berghofe@7544
   280
      handle TERM _ => primrec_eq_err sign "not a proper equation" eq) eqn_ts;
berghofe@7016
   281
    val (_, eqn_ts') = InductivePackage.unify_consts (sign_of thy) rec_ts eqn_ts
berghofe@7016
   282
  in
berghofe@7016
   283
    add_primrec_i alt_name (names ~~ eqn_ts' ~~ atts) thy
berghofe@7016
   284
  end;
wenzelm@6359
   285
berghofe@5178
   286
wenzelm@6359
   287
(* outer syntax *)
wenzelm@6359
   288
wenzelm@6723
   289
local structure P = OuterParse and K = OuterSyntax.Keyword in
wenzelm@6359
   290
wenzelm@6359
   291
val primrec_decl =
wenzelm@6723
   292
  Scan.optional (P.$$$ "(" |-- P.name --| P.$$$ ")") "" --
wenzelm@12876
   293
    Scan.repeat1 (P.opt_thm_name ":" -- P.prop);
wenzelm@6359
   294
wenzelm@6359
   295
val primrecP =
wenzelm@6723
   296
  OuterSyntax.command "primrec" "define primitive recursive functions on datatypes" K.thy_decl
wenzelm@6359
   297
    (primrec_decl >> (fn (alt_name, eqns) =>
wenzelm@6723
   298
      Toplevel.theory (#1 o add_primrec alt_name (map P.triple_swap eqns))));
wenzelm@6359
   299
wenzelm@6359
   300
val _ = OuterSyntax.add_parsers [primrecP];
berghofe@5178
   301
berghofe@5178
   302
end;
wenzelm@6384
   303
wenzelm@6384
   304
wenzelm@6384
   305
end;
wenzelm@15705
   306