src/HOL/Tools/primrec_package.ML
author paulson
Thu May 25 15:14:39 2000 +0200 (2000-05-25)
changeset 8973 ac448cd43452
parent 8480 50266d517b0c
child 9315 f793f05024f6
permissions -rw-r--r--
improved error msgs, listing variable names
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
wenzelm@6359
     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
wenzelm@6427
    11
  val quiet_mode: bool ref
berghofe@8480
    12
  val print_primrecs: theory -> unit
berghofe@8480
    13
  val get_primrec: theory -> string -> (string * thm list) list option
wenzelm@6425
    14
  val add_primrec: string -> ((bstring * string) * Args.src list) list
wenzelm@6359
    15
    -> theory -> theory * thm list
wenzelm@6425
    16
  val add_primrec_i: string -> ((bstring * term) * theory attribute list) list
wenzelm@6359
    17
    -> theory -> theory * thm list
berghofe@8480
    18
  val setup: (theory -> theory) list
berghofe@5178
    19
end;
berghofe@5178
    20
berghofe@5178
    21
structure PrimrecPackage : PRIMREC_PACKAGE =
berghofe@5178
    22
struct
berghofe@5178
    23
berghofe@5178
    24
open DatatypeAux;
berghofe@5178
    25
berghofe@5178
    26
exception RecError of string;
berghofe@5178
    27
berghofe@5178
    28
fun primrec_err s = error ("Primrec definition error:\n" ^ s);
berghofe@5178
    29
fun primrec_eq_err sign s eq =
berghofe@7544
    30
  primrec_err (s ^ "\nin\n" ^ quote (Sign.string_of_term sign eq));
wenzelm@6427
    31
wenzelm@6427
    32
wenzelm@6427
    33
(* messages *)
wenzelm@6427
    34
wenzelm@6427
    35
val quiet_mode = ref false;
wenzelm@6427
    36
fun message s = if ! quiet_mode then () else writeln s;
berghofe@5178
    37
wenzelm@6359
    38
berghofe@8480
    39
(** theory data **)
berghofe@8480
    40
berghofe@8480
    41
(* data kind 'HOL/primrec' *)
berghofe@8480
    42
berghofe@8480
    43
structure PrimrecArgs =
berghofe@8480
    44
struct
berghofe@8480
    45
  val name = "HOL/primrec";
berghofe@8480
    46
  type T = (string * thm list) list Symtab.table;
berghofe@8480
    47
berghofe@8480
    48
  val empty = Symtab.empty;
berghofe@8480
    49
  val copy = I;
berghofe@8480
    50
  val prep_ext = I;
berghofe@8480
    51
  val merge: T * T -> T = Symtab.merge (K true);
berghofe@8480
    52
berghofe@8480
    53
  fun print sg tab =
berghofe@8480
    54
    Pretty.writeln (Pretty.strs ("primrecs:" ::
berghofe@8480
    55
      map #1 (Sign.cond_extern_table sg Sign.constK tab)));
berghofe@8480
    56
end;
berghofe@8480
    57
berghofe@8480
    58
structure PrimrecData = TheoryDataFun(PrimrecArgs);
berghofe@8480
    59
val print_primrecs = PrimrecData.print;
berghofe@8480
    60
berghofe@8480
    61
berghofe@8480
    62
(* get and put data *)
berghofe@8480
    63
berghofe@8480
    64
fun get_primrec thy name = Symtab.lookup (PrimrecData.get thy, name);
berghofe@8480
    65
berghofe@8480
    66
fun put_primrec name info thy =
berghofe@8480
    67
  let val tab = PrimrecData.get thy
berghofe@8480
    68
  in 
berghofe@8480
    69
    PrimrecData.put (case Symtab.lookup (tab, name) of
berghofe@8480
    70
       None => Symtab.update_new ((name, [info]), tab)
berghofe@8480
    71
     | Some infos => Symtab.update ((name, info::infos), tab)) thy end;
berghofe@8480
    72
berghofe@8480
    73
berghofe@5178
    74
(* preprocessing of equations *)
berghofe@5178
    75
berghofe@5178
    76
fun process_eqn sign (eq, rec_fns) = 
berghofe@5178
    77
  let
paulson@6032
    78
    val (lhs, rhs) = 
paulson@6032
    79
	if null (term_vars eq) then
paulson@6032
    80
	    HOLogic.dest_eq (HOLogic.dest_Trueprop eq)
berghofe@7016
    81
	      handle TERM _ => raise RecError "not a proper equation"
paulson@6032
    82
	else raise RecError "illegal schematic variable(s)";
berghofe@5178
    83
berghofe@5178
    84
    val (recfun, args) = strip_comb lhs;
berghofe@7016
    85
    val (fname, _) = dest_Const recfun handle TERM _ => 
berghofe@5178
    86
      raise RecError "function is not declared as constant in theory";
berghofe@5178
    87
berghofe@5178
    88
    val (ls', rest)  = take_prefix is_Free args;
berghofe@5178
    89
    val (middle, rs') = take_suffix is_Free rest;
berghofe@5178
    90
    val rpos = length ls';
berghofe@5178
    91
berghofe@5178
    92
    val (constr, cargs') = if null middle then raise RecError "constructor missing"
berghofe@5178
    93
      else strip_comb (hd middle);
berghofe@5178
    94
    val (cname, T) = dest_Const constr
berghofe@7016
    95
      handle TERM _ => raise RecError "ill-formed constructor";
berghofe@7016
    96
    val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
berghofe@5178
    97
      raise RecError "cannot determine datatype associated with function"
berghofe@5178
    98
paulson@6037
    99
    val (ls, cargs, rs) = (map dest_Free ls', 
paulson@6037
   100
			   map dest_Free cargs', 
paulson@6037
   101
			   map dest_Free rs')
berghofe@7016
   102
      handle TERM _ => raise RecError "illegal argument in pattern";
berghofe@5178
   103
    val lfrees = ls @ rs @ cargs;
berghofe@5178
   104
paulson@8973
   105
    val _ = case duplicates lfrees of
paulson@8973
   106
	       [] => ()
paulson@8973
   107
	     | vars => raise RecError("repeated variable names in pattern: " ^ 
paulson@8973
   108
				      commas_quote (map #1 vars))
paulson@8973
   109
 
paulson@8973
   110
    val _ =  case (map dest_Free (term_frees rhs)) \\ lfrees of
paulson@8973
   111
		[] => ()
paulson@8973
   112
	      | vars => raise RecError 
paulson@8973
   113
		      ("extra variables on rhs: " ^ 
paulson@8973
   114
		       commas_quote (map #1 vars))
berghofe@5178
   115
  in
paulson@8973
   116
    if length middle > 1 then 
berghofe@5178
   117
      raise RecError "more than one non-variable in pattern"
berghofe@5178
   118
    else (case assoc (rec_fns, fname) of
berghofe@5178
   119
        None =>
berghofe@5178
   120
          (fname, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
berghofe@5178
   121
      | Some (_, rpos', eqns) =>
berghofe@5178
   122
          if is_some (assoc (eqns, cname)) then
paulson@6037
   123
            raise RecError "constructor already occurred as pattern"
berghofe@5178
   124
          else if rpos <> rpos' then
berghofe@5178
   125
            raise RecError "position of recursive argument inconsistent"
berghofe@5178
   126
          else
paulson@6037
   127
            overwrite (rec_fns, 
paulson@6037
   128
		       (fname, 
paulson@6037
   129
			(tname, rpos,
paulson@6037
   130
			 (cname, (ls, cargs, rs, rhs, eq))::eqns))))
berghofe@5178
   131
  end
berghofe@5178
   132
  handle RecError s => primrec_eq_err sign s eq;
berghofe@5178
   133
berghofe@5178
   134
fun process_fun sign descr rec_eqns ((i, fname), (fnames, fnss)) =
berghofe@5178
   135
  let
berghofe@5178
   136
    val (_, (tname, _, constrs)) = nth_elem (i, descr);
berghofe@5178
   137
berghofe@5178
   138
    (* substitute "fname ls x rs" by "y ls rs" for (x, (_, y)) in subs *)
berghofe@5178
   139
berghofe@5178
   140
    fun subst [] x = x
berghofe@5178
   141
      | subst subs (fs, Abs (a, T, t)) =
berghofe@5178
   142
          let val (fs', t') = subst subs (fs, t)
berghofe@5178
   143
          in (fs', Abs (a, T, t')) end
berghofe@5178
   144
      | subst subs (fs, t as (_ $ _)) =
berghofe@5178
   145
          let val (f, ts) = strip_comb t;
berghofe@5178
   146
          in
berghofe@5178
   147
            if is_Const f andalso (fst (dest_Const f)) mem (map fst rec_eqns) then
berghofe@5178
   148
              let
berghofe@5178
   149
                val (fname', _) = dest_Const f;
berghofe@5178
   150
                val (_, rpos, _) = the (assoc (rec_eqns, fname'));
berghofe@5178
   151
                val ls = take (rpos, ts);
berghofe@5178
   152
                val rest = drop (rpos, ts);
berghofe@7016
   153
                val (x', rs) = (hd rest, tl rest)
berghofe@7016
   154
                  handle LIST _ => raise RecError ("not enough arguments\
berghofe@7016
   155
                   \ in recursive application\nof function " ^ quote fname' ^ " on rhs");
berghofe@7016
   156
                val (x, xs) = strip_comb x'
berghofe@5178
   157
              in 
berghofe@5178
   158
                (case assoc (subs, x) of
berghofe@5178
   159
                    None =>
berghofe@5178
   160
                      let
berghofe@5178
   161
                        val (fs', ts') = foldl_map (subst subs) (fs, ts)
berghofe@5178
   162
                      in (fs', list_comb (f, ts')) end
berghofe@5178
   163
                  | Some (i', y) =>
berghofe@5178
   164
                      let
berghofe@7016
   165
                        val (fs', ts') = foldl_map (subst subs) (fs, xs @ ls @ rs);
berghofe@5178
   166
                        val fs'' = process_fun sign descr rec_eqns ((i', fname'), fs')
berghofe@5178
   167
                      in (fs'', list_comb (y, ts'))
berghofe@5178
   168
                      end)
berghofe@5178
   169
              end
berghofe@5178
   170
            else
berghofe@5178
   171
              let
berghofe@5178
   172
                val (fs', f'::ts') = foldl_map (subst subs) (fs, f::ts)
berghofe@5178
   173
              in (fs', list_comb (f', ts')) end
berghofe@5178
   174
          end
berghofe@5178
   175
      | subst _ x = x;
berghofe@5178
   176
berghofe@5178
   177
    (* translate rec equations into function arguments suitable for rec comb *)
berghofe@5178
   178
berghofe@5178
   179
    fun trans eqns ((cname, cargs), (fnames', fnss', fns)) =
berghofe@5178
   180
      (case assoc (eqns, cname) of
wenzelm@6427
   181
          None => (warning ("no equation for constructor " ^ quote cname ^
wenzelm@6427
   182
            "\nin definition of function " ^ quote fname);
berghofe@5178
   183
              (fnames', fnss', (Const ("arbitrary", dummyT))::fns))
berghofe@5178
   184
        | Some (ls, cargs', rs, rhs, eq) =>
berghofe@5178
   185
            let
berghofe@7016
   186
              fun rec_index (DtRec k) = k
berghofe@7016
   187
                | rec_index (DtType ("fun", [_, DtRec k])) = k;
berghofe@7016
   188
berghofe@5178
   189
              val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
berghofe@5178
   190
              val rargs = map fst recs;
paulson@6037
   191
              val subs = map (rpair dummyT o fst) 
paulson@6037
   192
		             (rev (rename_wrt_term rhs rargs));
paulson@6037
   193
              val ((fnames'', fnss''), rhs') = 
paulson@6037
   194
		  (subst (map (fn ((x, y), z) =>
berghofe@7016
   195
			       (Free x, (rec_index y, Free z)))
paulson@6037
   196
			  (recs ~~ subs))
paulson@6037
   197
		   ((fnames', fnss'), rhs))
berghofe@5178
   198
                  handle RecError s => primrec_eq_err sign s eq
paulson@6037
   199
            in (fnames'', fnss'', 
paulson@6037
   200
		(list_abs_free (cargs' @ subs @ ls @ rs, rhs'))::fns)
berghofe@5178
   201
            end)
berghofe@5178
   202
berghofe@5178
   203
  in (case assoc (fnames, i) of
berghofe@5178
   204
      None =>
berghofe@5178
   205
        if exists (equal fname o snd) fnames then
wenzelm@6427
   206
          raise RecError ("inconsistent functions for datatype " ^ quote tname)
berghofe@5178
   207
        else
berghofe@5178
   208
          let
berghofe@5178
   209
            val (_, _, eqns) = the (assoc (rec_eqns, fname));
berghofe@5178
   210
            val (fnames', fnss', fns) = foldr (trans eqns)
berghofe@5178
   211
              (constrs, ((i, fname)::fnames, fnss, []))
berghofe@5178
   212
          in
berghofe@5178
   213
            (fnames', (i, (fname, #1 (snd (hd eqns)), fns))::fnss')
berghofe@5178
   214
          end
berghofe@5178
   215
    | Some fname' =>
berghofe@5178
   216
        if fname = fname' then (fnames, fnss)
wenzelm@6427
   217
        else raise RecError ("inconsistent functions for datatype " ^ quote tname))
berghofe@5178
   218
  end;
berghofe@5178
   219
wenzelm@6359
   220
berghofe@5178
   221
(* prepare functions needed for definitions *)
berghofe@5178
   222
berghofe@5178
   223
fun get_fns fns (((i, (tname, _, constrs)), rec_name), (fs, defs)) =
berghofe@5178
   224
  case assoc (fns, i) of
berghofe@5178
   225
     None =>
berghofe@5178
   226
       let
berghofe@5178
   227
         val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
berghofe@5178
   228
           replicate ((length cargs) + (length (filter is_rec_type cargs)))
berghofe@5178
   229
             dummyT ---> HOLogic.unitT)) constrs;
wenzelm@6427
   230
         val _ = warning ("No function definition for datatype " ^ quote tname)
berghofe@5178
   231
       in
berghofe@5178
   232
         (dummy_fns @ fs, defs)
berghofe@5178
   233
       end
berghofe@5178
   234
   | Some (fname, ls, fs') => (fs' @ fs, (fname, ls, rec_name, tname)::defs);
berghofe@5178
   235
wenzelm@6359
   236
berghofe@5178
   237
(* make definition *)
berghofe@5178
   238
berghofe@5178
   239
fun make_def sign fs (fname, ls, rec_name, tname) =
berghofe@5178
   240
  let
paulson@6037
   241
    val rhs = foldr (fn (T, t) => Abs ("", T, t)) 
paulson@6037
   242
	            ((map snd ls) @ [dummyT],
paulson@6037
   243
		     list_comb (Const (rec_name, dummyT),
paulson@6037
   244
				fs @ map Bound (0 ::(length ls downto 1))));
berghofe@5178
   245
    val defpair = (Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def",
paulson@6037
   246
		   Logic.mk_equals (Const (fname, dummyT), rhs))
wenzelm@6394
   247
  in Theory.inferT_axm sign defpair end;
berghofe@5178
   248
wenzelm@6359
   249
berghofe@5178
   250
(* find datatypes which contain all datatypes in tnames' *)
berghofe@5178
   251
berghofe@5178
   252
fun find_dts (dt_info : datatype_info Symtab.table) _ [] = []
berghofe@5178
   253
  | find_dts dt_info tnames' (tname::tnames) =
berghofe@5178
   254
      (case Symtab.lookup (dt_info, tname) of
wenzelm@6427
   255
          None => primrec_err (quote tname ^ " is not a datatype")
berghofe@5178
   256
        | Some dt =>
berghofe@5178
   257
            if tnames' subset (map (#1 o snd) (#descr dt)) then
berghofe@5178
   258
              (tname, dt)::(find_dts dt_info tnames' tnames)
berghofe@5178
   259
            else find_dts dt_info tnames' tnames);
berghofe@5178
   260
wenzelm@8432
   261
fun prepare_induct ({descr, induction, ...}: datatype_info) rec_eqns =
wenzelm@8432
   262
  let
wenzelm@8432
   263
    fun constrs_of (_, (_, _, cs)) =
wenzelm@8432
   264
      map (fn (cname:string, (_, cargs, _, _, _)) => (cname, map fst cargs)) cs;
wenzelm@8432
   265
    val params_of = Library.assocs (flat (map constrs_of rec_eqns));
wenzelm@8432
   266
  in
wenzelm@8432
   267
    induction
wenzelm@8432
   268
    |> RuleCases.rename_params (map params_of (flat (map (map #1 o #3 o #2) descr)))
wenzelm@8432
   269
    |> RuleCases.name (RuleCases.get induction)
wenzelm@8432
   270
  end;
wenzelm@8432
   271
wenzelm@6359
   272
fun add_primrec_i alt_name eqns_atts thy =
berghofe@5178
   273
  let
wenzelm@6359
   274
    val (eqns, atts) = split_list eqns_atts;
wenzelm@6394
   275
    val sg = Theory.sign_of thy;
berghofe@5178
   276
    val dt_info = DatatypePackage.get_datatypes thy;
berghofe@5719
   277
    val rec_eqns = foldr (process_eqn sg) (map snd eqns, []);
berghofe@5178
   278
    val tnames = distinct (map (#1 o snd) rec_eqns);
berghofe@5178
   279
    val dts = find_dts dt_info tnames tnames;
paulson@6037
   280
    val main_fns = 
paulson@6037
   281
	map (fn (tname, {index, ...}) =>
paulson@6037
   282
	     (index, 
paulson@6037
   283
	      fst (the (find_first (fn f => #1 (snd f) = tname) rec_eqns))))
paulson@6037
   284
	dts;
paulson@6037
   285
    val {descr, rec_names, rec_rewrites, ...} = 
paulson@6037
   286
	if null dts then
wenzelm@6359
   287
	    primrec_err ("datatypes " ^ commas_quote tnames ^ 
paulson@6037
   288
			 "\nare not mutually recursive")
paulson@6037
   289
	else snd (hd dts);
paulson@6037
   290
    val (fnames, fnss) = foldr (process_fun sg descr rec_eqns)
paulson@6037
   291
	                       (main_fns, ([], []));
berghofe@5178
   292
    val (fs, defs) = foldr (get_fns fnss) (descr ~~ rec_names, ([], []));
berghofe@5178
   293
    val defs' = map (make_def sg fs) defs;
berghofe@5178
   294
    val names1 = map snd fnames;
berghofe@5178
   295
    val names2 = map fst rec_eqns;
wenzelm@8432
   296
    val primrec_name =
wenzelm@8432
   297
      if alt_name = "" then (space_implode "_" (map (Sign.base_name o #1) defs)) else alt_name;
wenzelm@8432
   298
    val (thy', defs_thms') = thy |> Theory.add_path primrec_name |>
wenzelm@7904
   299
      (if eq_set (names1, names2) then (PureThy.add_defs_i o map Thm.no_attributes) defs'
wenzelm@6359
   300
       else primrec_err ("functions " ^ commas_quote names2 ^
berghofe@5216
   301
         "\nare not mutually recursive"));
wenzelm@8432
   302
    val rewrites = o_def :: (map mk_meta_eq rec_rewrites) @ defs_thms';
wenzelm@6427
   303
    val _ = message ("Proving equations for primrec function(s) " ^ commas_quote names1 ^ " ...");
berghofe@8480
   304
    val simps = map (fn (_, t) => prove_goalw_cterm rewrites (cterm_of (Theory.sign_of thy') t)
berghofe@5178
   305
        (fn _ => [rtac refl 1])) eqns;
berghofe@8480
   306
    val (thy'', [simps']) = thy'
berghofe@8480
   307
      |> PureThy.add_thmss [(("simps", simps), [Simplifier.simp_add_global])]
berghofe@8480
   308
      |>> (#1 o PureThy.add_thms ((map fst eqns ~~ simps) ~~ atts))
berghofe@8480
   309
      |>> (#1 o PureThy.add_thms [(("induct", prepare_induct (#2 (hd dts)) rec_eqns), [])])
berghofe@8480
   310
      |>> Theory.parent_path
berghofe@8480
   311
  in
berghofe@8480
   312
    (foldl (fn (thy, (fname, _, _, tname)) =>
berghofe@8480
   313
       put_primrec fname (tname, simps') thy) (thy'', defs), simps')
berghofe@8480
   314
  end;
wenzelm@6359
   315
wenzelm@6359
   316
berghofe@7016
   317
fun add_primrec alt_name eqns thy =
berghofe@7016
   318
  let
berghofe@7544
   319
    val sign = Theory.sign_of thy;
berghofe@7016
   320
    val ((names, strings), srcss) = apfst split_list (split_list eqns);
berghofe@7016
   321
    val atts = map (map (Attrib.global_attribute thy)) srcss;
berghofe@7722
   322
    val eqn_ts = map (term_of o Thm.read_cterm sign o rpair propT) strings;
berghofe@7016
   323
    val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop eq)))
berghofe@7544
   324
      handle TERM _ => primrec_eq_err sign "not a proper equation" eq) eqn_ts;
berghofe@7016
   325
    val (_, eqn_ts') = InductivePackage.unify_consts (sign_of thy) rec_ts eqn_ts
berghofe@7016
   326
  in
berghofe@7016
   327
    add_primrec_i alt_name (names ~~ eqn_ts' ~~ atts) thy
berghofe@7016
   328
  end;
wenzelm@6359
   329
berghofe@5178
   330
berghofe@8480
   331
(** package setup **)
berghofe@8480
   332
berghofe@8480
   333
val setup = [PrimrecData.init];
berghofe@8480
   334
wenzelm@6359
   335
(* outer syntax *)
wenzelm@6359
   336
wenzelm@6723
   337
local structure P = OuterParse and K = OuterSyntax.Keyword in
wenzelm@6359
   338
wenzelm@6359
   339
val primrec_decl =
wenzelm@6723
   340
  Scan.optional (P.$$$ "(" |-- P.name --| P.$$$ ")") "" --
wenzelm@7152
   341
    Scan.repeat1 (P.opt_thm_name ":" -- P.prop --| P.marg_comment);
wenzelm@6359
   342
wenzelm@6359
   343
val primrecP =
wenzelm@6723
   344
  OuterSyntax.command "primrec" "define primitive recursive functions on datatypes" K.thy_decl
wenzelm@6359
   345
    (primrec_decl >> (fn (alt_name, eqns) =>
wenzelm@6723
   346
      Toplevel.theory (#1 o add_primrec alt_name (map P.triple_swap eqns))));
wenzelm@6359
   347
wenzelm@6359
   348
val _ = OuterSyntax.add_parsers [primrecP];
berghofe@5178
   349
berghofe@5178
   350
end;
wenzelm@6384
   351
wenzelm@6384
   352
wenzelm@6384
   353
end;