1 (* Title: Tools/induct.ML
2 Author: Markus Wenzel, TU Muenchen
4 Proof by cases, induction, and coinduction.
7 signature INDUCT_DATA =
12 val rulify_fallback: thm list
14 val dest_def: term -> (term * term) option
15 val trivial_tac: int -> tactic
21 val vars_of: term -> term list
22 val dest_rules: Proof.context ->
23 {type_cases: (string * thm) list, pred_cases: (string * thm) list,
24 type_induct: (string * thm) list, pred_induct: (string * thm) list,
25 type_coinduct: (string * thm) list, pred_coinduct: (string * thm) list}
26 val print_rules: Proof.context -> unit
27 val lookup_casesT: Proof.context -> string -> thm option
28 val lookup_casesP: Proof.context -> string -> thm option
29 val lookup_inductT: Proof.context -> string -> thm option
30 val lookup_inductP: Proof.context -> string -> thm option
31 val lookup_coinductT: Proof.context -> string -> thm option
32 val lookup_coinductP: Proof.context -> string -> thm option
33 val find_casesT: Proof.context -> typ -> thm list
34 val find_casesP: Proof.context -> term -> thm list
35 val find_inductT: Proof.context -> typ -> thm list
36 val find_inductP: Proof.context -> term -> thm list
37 val find_coinductT: Proof.context -> typ -> thm list
38 val find_coinductP: Proof.context -> term -> thm list
39 val cases_type: string -> attribute
40 val cases_pred: string -> attribute
41 val cases_del: attribute
42 val induct_type: string -> attribute
43 val induct_pred: string -> attribute
44 val induct_del: attribute
45 val coinduct_type: string -> attribute
46 val coinduct_pred: string -> attribute
47 val coinduct_del: attribute
48 val map_simpset: (simpset -> simpset) -> Context.generic -> Context.generic
49 val induct_simp_add: attribute
50 val induct_simp_del: attribute
59 val fix_tac: Proof.context -> int -> (string * typ) list -> int -> tactic
60 val add_defs: (binding option * (term * bool)) option list -> Proof.context ->
61 (term option list * thm list) * Proof.context
62 val atomize_term: theory -> term -> term
63 val atomize_cterm: conv
64 val atomize_tac: int -> tactic
65 val inner_atomize_tac: int -> tactic
66 val rulified_term: thm -> theory * term
67 val rulify_tac: int -> tactic
68 val simplified_rule: Proof.context -> thm -> thm
69 val simplify_tac: Proof.context -> int -> tactic
70 val trivial_tac: int -> tactic
71 val rotate_tac: int -> int -> int -> tactic
72 val internalize: int -> thm -> thm
73 val guess_instance: Proof.context -> thm -> int -> thm -> thm Seq.seq
74 val cases_tac: Proof.context -> bool -> term option list list -> thm option ->
75 thm list -> int -> cases_tactic
76 val get_inductT: Proof.context -> term option list list -> thm list list
77 val induct_tac: Proof.context -> bool -> (binding option * (term * bool)) option list list ->
78 (string * typ) list list -> term option list -> thm list option ->
79 thm list -> int -> cases_tactic
80 val coinduct_tac: Proof.context -> term option list -> term option list -> thm option ->
81 thm list -> int -> cases_tactic
82 val setup: theory -> theory
85 functor Induct(Data: INDUCT_DATA): INDUCT =
88 (** variables -- ordered left-to-right, preferring right **)
91 rev (distinct (op =) (Term.fold_aterms (fn (t as Var _) => cons t | _ => I) tm []));
95 val mk_var = Net.encode_type o #2 o Term.dest_Var;
97 fun concl_var which thm = mk_var (which (vars_of (Thm.concl_of thm))) handle Empty =>
98 raise THM ("No variables in conclusion of rule", 0, [thm]);
102 fun left_var_prem thm = mk_var (hd (vars_of (hd (Thm.prems_of thm)))) handle Empty =>
103 raise THM ("No variables in major premise of rule", 0, [thm]);
105 val left_var_concl = concl_var hd;
106 val right_var_concl = concl_var List.last;
112 (** constraint simplification **)
114 (* rearrange parameters and premises to allow application of one-point-rules *)
116 fun swap_params_conv ctxt i j cv =
118 fun conv1 0 ctxt = Conv.forall_conv (cv o snd) ctxt
120 Conv.rewr_conv @{thm swap_params} then_conv
121 Conv.forall_conv (conv1 (k-1) o snd) ctxt
122 fun conv2 0 ctxt = conv1 j ctxt
123 | conv2 k ctxt = Conv.forall_conv (conv2 (k-1) o snd) ctxt
126 fun swap_prems_conv 0 = Conv.all_conv
127 | swap_prems_conv i =
128 Conv.implies_concl_conv (swap_prems_conv (i-1)) then_conv
129 Conv.rewr_conv Drule.swap_prems_eq
131 fun drop_judgment ctxt = Object_Logic.drop_judgment (ProofContext.theory_of ctxt);
135 val l = length (Logic.strip_params t);
136 val Hs = Logic.strip_assums_hyp t;
138 case Data.dest_def (drop_judgment ctxt t) of
139 SOME (Bound j, _) => SOME (i, j)
140 | SOME (_, Bound j) => SOME (i, j)
143 case get_first find (map_index I Hs) of
145 | SOME (0, 0) => NONE
146 | SOME (i, j) => SOME (i, l-j-1, j)
149 fun mk_swap_rrule ctxt ct = case find_eq ctxt (term_of ct) of
151 | SOME (i, k, j) => SOME (swap_params_conv ctxt k j (K (swap_prems_conv i)) ct);
153 val rearrange_eqs_simproc = Simplifier.simproc
154 (Thm.theory_of_thm Drule.swap_prems_eq) "rearrange_eqs" ["all t"]
155 (fn thy => fn ss => fn t =>
156 mk_swap_rrule (Simplifier.the_context ss) (cterm_of thy t))
158 (* rotate k premises to the left by j, skipping over first j premises *)
160 fun rotate_conv 0 j 0 = Conv.all_conv
161 | rotate_conv 0 j k = swap_prems_conv j then_conv rotate_conv 1 j (k-1)
162 | rotate_conv i j k = Conv.implies_concl_conv (rotate_conv (i-1) j k);
164 fun rotate_tac j 0 = K all_tac
165 | rotate_tac j k = SUBGOAL (fn (goal, i) => CONVERSION (rotate_conv
166 j (length (Logic.strip_assums_hyp goal) - j - k) k) i);
168 (* rulify operators around definition *)
170 fun rulify_defs_conv ctxt ct =
171 if exists_subterm (is_some o Data.dest_def) (term_of ct) andalso
172 not (is_some (Data.dest_def (drop_judgment ctxt (term_of ct))))
174 (Conv.forall_conv (rulify_defs_conv o snd) ctxt else_conv
175 Conv.implies_conv (Conv.try_conv (rulify_defs_conv ctxt))
176 (Conv.try_conv (rulify_defs_conv ctxt)) else_conv
177 Conv.first_conv (map Conv.rewr_conv Data.rulify) then_conv
178 Conv.try_conv (rulify_defs_conv ctxt)) ct
179 else Conv.no_conv ct;
187 type rules = (string * thm) Item_Net.T;
189 fun init_rules index : rules =
191 (fn ((s1, th1), (s2, th2)) => s1 = s2 andalso Thm.eq_thm_prop (th1, th2))
194 fun filter_rules (rs: rules) th =
195 filter (fn (_, th') => Thm.eq_thm_prop (th, th')) (Item_Net.content rs);
197 fun lookup_rule (rs: rules) = AList.lookup (op =) (Item_Net.content rs);
199 fun pretty_rules ctxt kind rs =
200 let val thms = map snd (Item_Net.content rs)
201 in Pretty.big_list kind (map (Display.pretty_thm ctxt) thms) end;
206 structure InductData = Generic_Data
208 type T = (rules * rules) * (rules * rules) * (rules * rules) * simpset;
210 ((init_rules (left_var_prem o #2), init_rules (Thm.major_prem_of o #2)),
211 (init_rules (right_var_concl o #2), init_rules (Thm.major_prem_of o #2)),
212 (init_rules (left_var_concl o #2), init_rules (Thm.concl_of o #2)),
213 empty_ss addsimprocs [rearrange_eqs_simproc] addsimps [Drule.norm_hhf_eq]);
215 fun merge (((casesT1, casesP1), (inductT1, inductP1), (coinductT1, coinductP1), simpset1),
216 ((casesT2, casesP2), (inductT2, inductP2), (coinductT2, coinductP2), simpset2)) =
217 ((Item_Net.merge (casesT1, casesT2), Item_Net.merge (casesP1, casesP2)),
218 (Item_Net.merge (inductT1, inductT2), Item_Net.merge (inductP1, inductP2)),
219 (Item_Net.merge (coinductT1, coinductT2), Item_Net.merge (coinductP1, coinductP2)),
220 merge_ss (simpset1, simpset2));
223 val get_local = InductData.get o Context.Proof;
225 fun dest_rules ctxt =
226 let val ((casesT, casesP), (inductT, inductP), (coinductT, coinductP), _) = get_local ctxt in
227 {type_cases = Item_Net.content casesT,
228 pred_cases = Item_Net.content casesP,
229 type_induct = Item_Net.content inductT,
230 pred_induct = Item_Net.content inductP,
231 type_coinduct = Item_Net.content coinductT,
232 pred_coinduct = Item_Net.content coinductP}
235 fun print_rules ctxt =
236 let val ((casesT, casesP), (inductT, inductP), (coinductT, coinductP), _) = get_local ctxt in
237 [pretty_rules ctxt "coinduct type:" coinductT,
238 pretty_rules ctxt "coinduct pred:" coinductP,
239 pretty_rules ctxt "induct type:" inductT,
240 pretty_rules ctxt "induct pred:" inductP,
241 pretty_rules ctxt "cases type:" casesT,
242 pretty_rules ctxt "cases pred:" casesP]
243 |> Pretty.chunks |> Pretty.writeln
247 Outer_Syntax.improper_command "print_induct_rules" "print induction and cases rules"
248 Keyword.diag (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_context o
249 Toplevel.keep (print_rules o Toplevel.context_of)));
254 val lookup_casesT = lookup_rule o #1 o #1 o get_local;
255 val lookup_casesP = lookup_rule o #2 o #1 o get_local;
256 val lookup_inductT = lookup_rule o #1 o #2 o get_local;
257 val lookup_inductP = lookup_rule o #2 o #2 o get_local;
258 val lookup_coinductT = lookup_rule o #1 o #3 o get_local;
259 val lookup_coinductP = lookup_rule o #2 o #3 o get_local;
262 fun find_rules which how ctxt x =
263 map snd (Item_Net.retrieve (which (get_local ctxt)) (how x));
265 val find_casesT = find_rules (#1 o #1) Net.encode_type;
266 val find_casesP = find_rules (#2 o #1) I;
267 val find_inductT = find_rules (#1 o #2) Net.encode_type;
268 val find_inductP = find_rules (#2 o #2) I;
269 val find_coinductT = find_rules (#1 o #3) Net.encode_type;
270 val find_coinductP = find_rules (#2 o #3) I;
278 fun mk_att f g name arg =
279 let val (x, thm) = g arg in (InductData.map (f (name, thm)) x, thm) end;
281 fun del_att which = Thm.declaration_attribute (fn th => InductData.map (which (pairself (fn rs =>
282 fold Item_Net.remove (filter_rules rs th) rs))));
284 fun map1 f (x, y, z, s) = (f x, y, z, s);
285 fun map2 f (x, y, z, s) = (x, f y, z, s);
286 fun map3 f (x, y, z, s) = (x, y, f z, s);
287 fun map4 f (x, y, z, s) = (x, y, z, f s);
289 fun add_casesT rule x = map1 (apfst (Item_Net.update rule)) x;
290 fun add_casesP rule x = map1 (apsnd (Item_Net.update rule)) x;
291 fun add_inductT rule x = map2 (apfst (Item_Net.update rule)) x;
292 fun add_inductP rule x = map2 (apsnd (Item_Net.update rule)) x;
293 fun add_coinductT rule x = map3 (apfst (Item_Net.update rule)) x;
294 fun add_coinductP rule x = map3 (apsnd (Item_Net.update rule)) x;
296 val consumes0 = Rule_Cases.consumes_default 0;
297 val consumes1 = Rule_Cases.consumes_default 1;
301 val cases_type = mk_att add_casesT consumes0;
302 val cases_pred = mk_att add_casesP consumes1;
303 val cases_del = del_att map1;
305 val induct_type = mk_att add_inductT consumes0;
306 val induct_pred = mk_att add_inductP consumes1;
307 val induct_del = del_att map2;
309 val coinduct_type = mk_att add_coinductT consumes0;
310 val coinduct_pred = mk_att add_coinductP consumes1;
311 val coinduct_del = del_att map3;
313 fun map_simpset f = InductData.map (map4 f);
316 Thm.declaration_attribute (fn thm => fn context =>
318 (Simplifier.with_context (Context.proof_of context) (fn ss => f (ss, [thm]))) context));
320 val induct_simp_add = induct_simp (op addsimps);
321 val induct_simp_del = induct_simp (op delsimps);
327 (** attribute syntax **)
329 val no_simpN = "no_simp";
330 val casesN = "cases";
331 val inductN = "induct";
332 val coinductN = "coinduct";
341 Scan.lift (Args.$$$ k -- Args.colon) |-- arg ||
342 Scan.lift (Args.$$$ k) >> K "";
344 fun attrib add_type add_pred del =
345 spec typeN (Args.type_name false) >> add_type ||
346 spec predN (Args.const false) >> add_pred ||
347 spec setN (Args.const false) >> add_pred ||
348 Scan.lift Args.del >> K del;
353 Attrib.setup @{binding cases} (attrib cases_type cases_pred cases_del)
354 "declaration of cases rule" #>
355 Attrib.setup @{binding induct} (attrib induct_type induct_pred induct_del)
356 "declaration of induction rule" #>
357 Attrib.setup @{binding coinduct} (attrib coinduct_type coinduct_pred coinduct_del)
358 "declaration of coinduction rule" #>
359 Attrib.setup @{binding induct_simp} (Attrib.add_del induct_simp_add induct_simp_del)
360 "declaration of rules for simplifying induction or cases rules";
370 fun align_left msg xs ys =
371 let val m = length xs and n = length ys
372 in if m < n then error msg else (take n xs ~~ ys) end;
374 fun align_right msg xs ys =
375 let val m = length xs and n = length ys
376 in if m < n then error msg else (drop (m - n) xs ~~ ys) end;
381 fun prep_inst ctxt align tune (tm, ts) =
383 val cert = Thm.cterm_of (ProofContext.theory_of ctxt);
384 fun prep_var (x, SOME t) =
387 val xT = #T (Thm.rep_cterm cx);
388 val ct = cert (tune t);
389 val tT = #T (Thm.rep_cterm ct);
391 if Type.could_unify (tT, xT) then SOME (cx, ct)
392 else error (Pretty.string_of (Pretty.block
393 [Pretty.str "Ill-typed instantiation:", Pretty.fbrk,
394 Syntax.pretty_term ctxt (Thm.term_of ct), Pretty.str " ::", Pretty.brk 1,
395 Syntax.pretty_typ ctxt tT]))
397 | prep_var (_, NONE) = NONE;
400 align "Rule has fewer variables than instantiations given" xs ts
401 |> map_filter prep_var
407 fun trace_rules _ kind [] = error ("Unable to figure out " ^ kind ^ " rule")
408 | trace_rules ctxt _ rules = Method.trace ctxt rules;
411 (* mark equality constraints in cases rule *)
413 val equal_def' = Thm.symmetric Data.equal_def;
415 fun mark_constraints n ctxt = Conv.fconv_rule
416 (Conv.prems_conv (~1) (Conv.params_conv ~1 (K (Conv.prems_conv n
417 (MetaSimplifier.rewrite false [equal_def']))) ctxt));
419 val unmark_constraints = Conv.fconv_rule
420 (MetaSimplifier.rewrite true [Data.equal_def]);
424 fun simplify_conv' ctxt =
425 Simplifier.full_rewrite (Simplifier.context ctxt (#4 (get_local ctxt)));
427 fun simplify_conv ctxt ct =
428 if exists_subterm (is_some o Data.dest_def) (term_of ct) then
429 (Conv.try_conv (rulify_defs_conv ctxt) then_conv simplify_conv' ctxt) ct
430 else Conv.all_conv ct;
432 fun gen_simplified_rule cv ctxt =
433 Conv.fconv_rule (Conv.prems_conv ~1 (cv ctxt));
435 val simplified_rule' = gen_simplified_rule simplify_conv';
436 val simplified_rule = gen_simplified_rule simplify_conv;
438 fun simplify_tac ctxt = CONVERSION (simplify_conv ctxt);
440 val trivial_tac = Data.trivial_tac;
447 rule selection scheme:
448 cases - default case split
449 `A t` cases ... - predicate/set cases
451 ... cases ... r - explicit rule
456 fun get_casesT ctxt ((SOME t :: _) :: _) = find_casesT ctxt (Term.fastype_of t)
457 | get_casesT _ _ = [];
459 fun get_casesP ctxt (fact :: _) = find_casesP ctxt (Thm.concl_of fact)
460 | get_casesP _ _ = [];
464 fun cases_tac ctxt simp insts opt_rule facts =
466 val thy = ProofContext.theory_of ctxt;
469 (if null insts then r
470 else (align_left "Rule has fewer premises than arguments given" (Thm.prems_of r) insts
471 |> maps (prep_inst ctxt align_left I)
472 |> Drule.cterm_instantiate) r) |>
473 (if simp then mark_constraints (Rule_Cases.get_constraints r) ctxt else I) |>
474 pair (Rule_Cases.get r);
478 SOME r => Seq.single (inst_rule r)
480 (get_casesP ctxt facts @ get_casesT ctxt insts @ [Data.cases_default])
481 |> tap (trace_rules ctxt casesN)
482 |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
486 |> Seq.maps (Rule_Cases.consume [] facts)
487 |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
489 (if simp then simplified_rule' ctxt #> unmark_constraints else I) rule
491 CASES (Rule_Cases.make_common (thy,
492 Thm.prop_of (Rule_Cases.internalize_params rule')) cases)
493 ((Method.insert_tac more_facts THEN' Tactic.rtac rule' THEN_ALL_NEW
494 (if simp then TRY o trivial_tac else K all_tac)) i) st
502 (** induct method **)
504 val conjunction_congs = [@{thm Pure.all_conjunction}, @{thm imp_conjunction}];
509 fun atomize_term thy =
510 MetaSimplifier.rewrite_term thy Data.atomize []
511 #> Object_Logic.drop_judgment thy;
513 val atomize_cterm = MetaSimplifier.rewrite true Data.atomize;
515 val atomize_tac = Simplifier.rewrite_goal_tac Data.atomize;
517 val inner_atomize_tac =
518 Simplifier.rewrite_goal_tac (map Thm.symmetric conjunction_congs) THEN' atomize_tac;
523 fun rulify_term thy =
524 MetaSimplifier.rewrite_term thy (Data.rulify @ conjunction_congs) [] #>
525 MetaSimplifier.rewrite_term thy Data.rulify_fallback [];
527 fun rulified_term thm =
529 val thy = Thm.theory_of_thm thm;
530 val rulify = rulify_term thy;
531 val (As, B) = Logic.strip_horn (Thm.prop_of thm);
532 in (thy, Logic.list_implies (map rulify As, rulify B)) end;
535 Simplifier.rewrite_goal_tac (Data.rulify @ conjunction_congs) THEN'
536 Simplifier.rewrite_goal_tac Data.rulify_fallback THEN'
537 Goal.conjunction_tac THEN_ALL_NEW
538 (Simplifier.rewrite_goal_tac [@{thm Pure.conjunction_imp}] THEN' Goal.norm_hhf_tac);
543 fun rule_instance ctxt inst rule =
544 Drule.cterm_instantiate (prep_inst ctxt align_left I (Thm.prop_of rule, inst)) rule;
546 fun internalize k th =
547 th |> Thm.permute_prems 0 k
548 |> Conv.fconv_rule (Conv.concl_conv (Thm.nprems_of th - k) atomize_cterm);
551 (* guess rule instantiation -- cannot handle pending goal parameters *)
555 fun dest_env thy env =
557 val cert = Thm.cterm_of thy;
558 val certT = Thm.ctyp_of thy;
559 val pairs = Vartab.dest (Envir.term_env env);
560 val types = Vartab.dest (Envir.type_env env);
561 val ts = map (cert o Envir.norm_term env o #2 o #2) pairs;
562 val xs = map2 (curry (cert o Var)) (map #1 pairs) (map (#T o Thm.rep_cterm) ts);
563 in (map (fn (xi, (S, T)) => (certT (TVar (xi, S)), certT T)) types, xs ~~ ts) end;
567 fun guess_instance ctxt rule i st =
569 val thy = ProofContext.theory_of ctxt;
570 val maxidx = Thm.maxidx_of st;
571 val goal = Thm.term_of (Thm.cprem_of st i); (*exception Subscript*)
572 val params = rev (Term.rename_wrt_term goal (Logic.strip_params goal));
574 if not (null params) then
575 (warning ("Cannot determine rule instantiation due to pending parameter(s): " ^
576 commas_quote (map (Syntax.string_of_term ctxt o Syntax.mark_boundT) params));
580 val rule' = Thm.incr_indexes (maxidx + 1) rule;
581 val concl = Logic.strip_assums_concl goal;
583 Unify.smash_unifiers thy [(Thm.concl_of rule', concl)] (Envir.empty (Thm.maxidx_of rule'))
584 |> Seq.map (fn env => Drule.instantiate (dest_env thy env) rule')
586 end handle Subscript => Seq.empty;
591 (* special renaming of rule parameters *)
593 fun special_rename_params ctxt [[SOME (Free (z, Type (T, _)))]] [thm] =
595 val x = Name.clean (ProofContext.revert_skolem ctxt z);
597 | index i (y :: ys) =
598 if x = y then x ^ string_of_int i :: index (i + 1) ys
599 else y :: index i ys;
600 fun rename_params [] = []
601 | rename_params ((y, Type (U, _)) :: ys) =
602 (if U = T then x else y) :: rename_params ys
603 | rename_params ((y, _) :: ys) = y :: rename_params ys;
606 val xs = rename_params (Logic.strip_params A);
608 (case filter (fn x' => x' = x) xs of
609 [] => xs | [_] => xs | _ => index 1 xs);
610 in Logic.list_rename_params (xs', A) end;
612 let val (As, C) = Logic.strip_horn p
613 in Logic.list_implies (map rename_asm As, C) end;
614 val cp' = cterm_fun rename_prop (Thm.cprop_of thm);
615 val thm' = Thm.equal_elim (Thm.reflexive cp') thm;
616 in [Rule_Cases.save thm thm'] end
617 | special_rename_params _ _ ths = ths;
624 fun goal_prefix k ((c as Const ("all", _)) $ Abs (a, T, B)) = c $ Abs (a, T, goal_prefix k B)
625 | goal_prefix 0 _ = Term.dummy_pattern propT
626 | goal_prefix k ((c as Const ("==>", _)) $ A $ B) = c $ A $ goal_prefix (k - 1) B
627 | goal_prefix _ _ = Term.dummy_pattern propT;
629 fun goal_params k (Const ("all", _) $ Abs (_, _, B)) = goal_params k B + 1
630 | goal_params 0 _ = 0
631 | goal_params k (Const ("==>", _) $ _ $ B) = goal_params (k - 1) B
632 | goal_params _ _ = 0;
634 fun meta_spec_tac ctxt n (x, T) = SUBGOAL (fn (goal, i) =>
636 val thy = ProofContext.theory_of ctxt;
637 val cert = Thm.cterm_of thy;
640 fun spec_rule prfx (xs, body) =
641 @{thm Pure.meta_spec}
642 |> Thm.rename_params_rule ([Name.clean (ProofContext.revert_skolem ctxt x)], 1)
643 |> Thm.lift_rule (cert prfx)
644 |> `(Thm.prop_of #> Logic.strip_assums_concl)
645 |-> (fn pred $ arg =>
646 Drule.cterm_instantiate
647 [(cert (Term.head_of pred), cert (Logic.rlist_abs (xs, body))),
648 (cert (Term.head_of arg), cert (Logic.rlist_abs (xs, v)))]);
650 fun goal_concl k xs (Const ("all", _) $ Abs (a, T, B)) = goal_concl k ((a, T) :: xs) B
651 | goal_concl 0 xs B =
652 if not (Term.exists_subterm (fn t => t aconv v) B) then NONE
653 else SOME (xs, Term.absfree (x, T, Term.incr_boundvars 1 B))
654 | goal_concl k xs (Const ("==>", _) $ _ $ B) = goal_concl (k - 1) xs B
655 | goal_concl _ _ _ = NONE;
657 (case goal_concl n [] goal of
659 (compose_tac (false, spec_rule (goal_prefix n goal) concl, 1) THEN' rtac asm_rl) i
663 fun miniscope_tac p = CONVERSION o
664 Conv.params_conv p (K (MetaSimplifier.rewrite true [Thm.symmetric Drule.norm_hhf_eq]));
668 fun fix_tac _ _ [] = K all_tac
669 | fix_tac ctxt n xs = SUBGOAL (fn (goal, i) =>
670 (EVERY' (map (meta_spec_tac ctxt n) xs) THEN'
671 (miniscope_tac (goal_params n goal) ctxt)) i);
678 fun add_defs def_insts =
680 fun add (SOME (_, (t, true))) ctxt = ((SOME t, []), ctxt)
681 | add (SOME (SOME x, (t, _))) ctxt =
682 let val ([(lhs, (_, th))], ctxt') =
683 Local_Defs.add_defs [((x, NoSyn), (Thm.empty_binding, t))] ctxt
684 in ((SOME lhs, [th]), ctxt') end
685 | add (SOME (NONE, (t as Free _, _))) ctxt = ((SOME t, []), ctxt)
686 | add (SOME (NONE, (t, _))) ctxt =
688 val ([s], _) = Name.variants ["x"] (Variable.names_of ctxt);
689 val ([(lhs, (_, th))], ctxt') =
690 Local_Defs.add_defs [((Binding.name s, NoSyn),
691 (Thm.empty_binding, t))] ctxt
692 in ((SOME lhs, [th]), ctxt') end
693 | add NONE ctxt = ((NONE, []), ctxt);
694 in fold_map add def_insts #> apfst (split_list #> apsnd flat) end;
700 rule selection scheme:
701 `A x` induct ... - predicate/set induction
702 induct x - type induction
703 ... induct ... r - explicit rule
706 fun get_inductT ctxt insts =
707 fold_rev (map_product cons) (insts |> map
708 ((fn [] => NONE | ts => List.last ts) #>
709 (fn NONE => TVar (("'a", 0), []) | SOME t => Term.fastype_of t) #>
710 find_inductT ctxt)) [[]]
711 |> filter_out (forall Rule_Cases.is_inner_rule);
713 fun get_inductP ctxt (fact :: _) = map single (find_inductP ctxt (Thm.concl_of fact))
714 | get_inductP _ _ = [];
716 fun induct_tac ctxt simp def_insts arbitrary taking opt_rule facts =
718 val thy = ProofContext.theory_of ctxt;
720 val ((insts, defs), defs_ctxt) = fold_map add_defs def_insts ctxt |>> split_list;
721 val atomized_defs = map (map (Conv.fconv_rule atomize_cterm)) defs;
723 fun inst_rule (concls, r) =
724 (if null insts then `Rule_Cases.get r
725 else (align_left "Rule has fewer conclusions than arguments given"
726 (map Logic.strip_imp_concl (Logic.dest_conjunctions (Thm.concl_of r))) insts
727 |> maps (prep_inst ctxt align_right (atomize_term thy))
728 |> Drule.cterm_instantiate) r |> pair (Rule_Cases.get r))
729 |> (fn ((cases, consumes), th) => (((cases, concls), consumes), th));
733 SOME rs => Seq.single (inst_rule (Rule_Cases.strict_mutual_rule ctxt rs))
735 (get_inductP ctxt facts @
736 map (special_rename_params defs_ctxt insts) (get_inductT ctxt insts))
737 |> map_filter (Rule_Cases.mutual_rule ctxt)
738 |> tap (trace_rules ctxt inductN o map #2)
739 |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
741 fun rule_cases ctxt rule =
742 let val rule' = (if simp then simplified_rule ctxt else I)
743 (Rule_Cases.internalize_params rule);
744 in Rule_Cases.make_nested (Thm.prop_of rule') (rulified_term rule') end;
748 |> Seq.maps (Rule_Cases.consume (flat defs) facts)
749 |> Seq.maps (fn (((cases, concls), (more_consumes, more_facts)), rule) =>
750 (PRECISE_CONJUNCTS (length concls) (ALLGOALS (fn j =>
753 val adefs = nth_list atomized_defs (j - 1);
754 val frees = fold (Term.add_frees o prop_of) adefs [];
755 val xs = nth_list arbitrary (j - 1);
756 val k = nth concls (j - 1) + more_consumes
758 Method.insert_tac (more_facts @ adefs) THEN'
760 rotate_tac k (length adefs) THEN'
762 (List.partition (member op = frees) xs |> op @)
764 fix_tac defs_ctxt k xs)
766 THEN' inner_atomize_tac) j))
767 THEN' atomize_tac) i st |> Seq.maps (fn st' =>
768 guess_instance ctxt (internalize more_consumes rule) i st'
769 |> Seq.map (rule_instance ctxt (burrow_options (Variable.polymorphic ctxt) taking))
770 |> Seq.maps (fn rule' =>
771 CASES (rule_cases ctxt rule' cases)
772 (Tactic.rtac rule' i THEN
773 PRIMITIVE (singleton (ProofContext.export defs_ctxt ctxt))) st'))))
775 ((if simp then simplify_tac ctxt THEN' (TRY o trivial_tac)
777 THEN_ALL_NEW rulify_tac)
782 (** coinduct method **)
785 rule selection scheme:
786 goal "A x" coinduct ... - predicate/set coinduction
787 coinduct x - type coinduction
788 coinduct ... r - explicit rule
793 fun get_coinductT ctxt (SOME t :: _) = find_coinductT ctxt (Term.fastype_of t)
794 | get_coinductT _ _ = [];
796 fun get_coinductP ctxt goal = find_coinductP ctxt (Logic.strip_assums_concl goal);
798 fun main_prop_of th =
799 if Rule_Cases.get_consumes th > 0 then Thm.major_prem_of th else Thm.concl_of th;
803 fun coinduct_tac ctxt inst taking opt_rule facts =
805 val thy = ProofContext.theory_of ctxt;
808 if null inst then `Rule_Cases.get r
809 else Drule.cterm_instantiate (prep_inst ctxt align_right I (main_prop_of r, inst)) r
810 |> pair (Rule_Cases.get r);
814 SOME r => Seq.single (inst_rule r)
816 (get_coinductP ctxt goal @ get_coinductT ctxt inst)
817 |> tap (trace_rules ctxt coinductN)
818 |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
820 SUBGOAL_CASES (fn (goal, i) => fn st =>
822 |> Seq.maps (Rule_Cases.consume [] facts)
823 |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
824 guess_instance ctxt rule i st
825 |> Seq.map (rule_instance ctxt (burrow_options (Variable.polymorphic ctxt) taking))
826 |> Seq.maps (fn rule' =>
827 CASES (Rule_Cases.make_common (thy,
828 Thm.prop_of (Rule_Cases.internalize_params rule')) cases)
829 (Method.insert_tac more_facts i THEN Tactic.rtac rule' i) st)))
836 (** concrete syntax **)
838 val arbitraryN = "arbitrary";
839 val takingN = "taking";
844 fun single_rule [rule] = rule
845 | single_rule _ = error "Single rule expected";
847 fun named_rule k arg get =
848 Scan.lift (Args.$$$ k -- Args.colon) |-- Scan.repeat arg :|--
849 (fn names => Scan.peek (fn context => Scan.succeed (names |> map (fn name =>
850 (case get (Context.proof_of context) name of SOME x => x
851 | NONE => error ("No rule for " ^ k ^ " " ^ quote name))))));
853 fun rule get_type get_pred =
854 named_rule typeN (Args.type_name false) get_type ||
855 named_rule predN (Args.const false) get_pred ||
856 named_rule setN (Args.const false) get_pred ||
857 Scan.lift (Args.$$$ ruleN -- Args.colon) |-- Attrib.thms;
859 val cases_rule = rule lookup_casesT lookup_casesP >> single_rule;
860 val induct_rule = rule lookup_inductT lookup_inductP;
861 val coinduct_rule = rule lookup_coinductT lookup_coinductP >> single_rule;
863 val inst = Scan.lift (Args.$$$ "_") >> K NONE || Args.term >> SOME;
865 val inst' = Scan.lift (Args.$$$ "_") >> K NONE ||
866 Args.term >> (SOME o rpair false) ||
867 Scan.lift (Args.$$$ "(") |-- (Args.term >> (SOME o rpair true)) --|
868 Scan.lift (Args.$$$ ")");
871 ((Scan.lift (Args.binding --| (Args.$$$ "\<equiv>" || Args.$$$ "==")) >> SOME)
872 -- (Args.term >> rpair false)) >> SOME ||
873 inst' >> Option.map (pair NONE);
875 val free = Args.context -- Args.term >> (fn (_, Free v) => v | (ctxt, t) =>
876 error ("Bad free variable: " ^ Syntax.string_of_term ctxt t));
878 fun unless_more_args scan = Scan.unless (Scan.lift
879 ((Args.$$$ arbitraryN || Args.$$$ takingN || Args.$$$ typeN ||
880 Args.$$$ predN || Args.$$$ setN || Args.$$$ ruleN) -- Args.colon)) scan;
882 val arbitrary = Scan.optional (Scan.lift (Args.$$$ arbitraryN -- Args.colon) |--
883 Parse.and_list1' (Scan.repeat (unless_more_args free))) [];
885 val taking = Scan.optional (Scan.lift (Args.$$$ takingN -- Args.colon) |--
886 Scan.repeat1 (unless_more_args inst)) [];
891 Method.setup @{binding cases}
892 (Args.mode no_simpN --
893 (Parse.and_list' (Scan.repeat (unless_more_args inst)) -- Scan.option cases_rule) >>
894 (fn (no_simp, (insts, opt_rule)) => fn ctxt =>
895 METHOD_CASES (fn facts => Seq.DETERM (HEADGOAL
896 (cases_tac ctxt (not no_simp) insts opt_rule facts)))))
897 "case analysis on types or predicates/sets";
900 Method.setup @{binding induct}
901 (Args.mode no_simpN -- (Parse.and_list' (Scan.repeat (unless_more_args def_inst)) --
902 (arbitrary -- taking -- Scan.option induct_rule)) >>
903 (fn (no_simp, (insts, ((arbitrary, taking), opt_rule))) => fn ctxt =>
904 RAW_METHOD_CASES (fn facts =>
906 (HEADGOAL (induct_tac ctxt (not no_simp) insts arbitrary taking opt_rule facts)))))
907 "induction on types or predicates/sets";
910 Method.setup @{binding coinduct}
911 (Scan.repeat (unless_more_args inst) -- taking -- Scan.option coinduct_rule >>
912 (fn ((insts, taking), opt_rule) => fn ctxt =>
913 RAW_METHOD_CASES (fn facts =>
914 Seq.DETERM (HEADGOAL (coinduct_tac ctxt insts taking opt_rule facts)))))
915 "coinduction on types or predicates/sets";
923 val setup = attrib_setup #> cases_setup #> induct_setup #> coinduct_setup;