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