src/Tools/induct.ML
author wenzelm
Tue Sep 02 14:10:45 2008 +0200 (2008-09-02)
changeset 28083 103d9282a946
parent 27865 27a8ad9612a3
child 28375 c879d88d038a
permissions -rw-r--r--
explicit type Name.binding for higher-specification elements;
     1 (*  Title:      Tools/induct.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 Proof by cases, induction, and coinduction.
     6 *)
     7 
     8 signature INDUCT_DATA =
     9 sig
    10   val cases_default: thm
    11   val atomize: thm list
    12   val rulify: thm list
    13   val rulify_fallback: thm list
    14 end;
    15 
    16 signature INDUCT =
    17 sig
    18   (*rule declarations*)
    19   val vars_of: term -> term list
    20   val dest_rules: Proof.context ->
    21     {type_cases: (string * thm) list, pred_cases: (string * thm) list,
    22       type_induct: (string * thm) list, pred_induct: (string * thm) list,
    23       type_coinduct: (string * thm) list, pred_coinduct: (string * thm) list}
    24   val print_rules: Proof.context -> unit
    25   val lookup_casesT: Proof.context -> string -> thm option
    26   val lookup_casesP: Proof.context -> string -> thm option
    27   val lookup_inductT: Proof.context -> string -> thm option
    28   val lookup_inductP: Proof.context -> string -> thm option
    29   val lookup_coinductT: Proof.context -> string -> thm option
    30   val lookup_coinductP: Proof.context -> string -> thm option
    31   val find_casesT: Proof.context -> typ -> thm list
    32   val find_casesP: Proof.context -> term -> thm list
    33   val find_inductT: Proof.context -> typ -> thm list
    34   val find_inductP: Proof.context -> term -> thm list
    35   val find_coinductT: Proof.context -> typ -> thm list
    36   val find_coinductP: Proof.context -> term -> thm list
    37   val cases_type: string -> attribute
    38   val cases_pred: string -> attribute
    39   val cases_del: attribute
    40   val induct_type: string -> attribute
    41   val induct_pred: string -> attribute
    42   val induct_del: attribute
    43   val coinduct_type: string -> attribute
    44   val coinduct_pred: string -> attribute
    45   val coinduct_del: attribute
    46   val casesN: string
    47   val inductN: string
    48   val coinductN: string
    49   val typeN: string
    50   val predN: string
    51   val setN: string
    52   (*proof methods*)
    53   val fix_tac: Proof.context -> int -> (string * typ) list -> int -> tactic
    54   val add_defs: (Name.binding option * term) option list -> Proof.context ->
    55     (term option list * thm list) * Proof.context
    56   val atomize_term: theory -> term -> term
    57   val atomize_tac: int -> tactic
    58   val inner_atomize_tac: int -> tactic
    59   val rulified_term: thm -> theory * term
    60   val rulify_tac: int -> tactic
    61   val internalize: int -> thm -> thm
    62   val guess_instance: Proof.context -> thm -> int -> thm -> thm Seq.seq
    63   val cases_tac: Proof.context -> term option list list -> thm option ->
    64     thm list -> int -> cases_tactic
    65   val get_inductT: Proof.context -> term option list list -> thm list list
    66   val induct_tac: Proof.context -> (Name.binding option * term) option list list ->
    67     (string * typ) list list -> term option list -> thm list option ->
    68     thm list -> int -> cases_tactic
    69   val coinduct_tac: Proof.context -> term option list -> term option list -> thm option ->
    70     thm list -> int -> cases_tactic
    71   val setup: theory -> theory
    72 end;
    73 
    74 functor InductFun(Data: INDUCT_DATA): INDUCT =
    75 struct
    76 
    77 
    78 (** misc utils **)
    79 
    80 (* encode_type -- for indexing purposes *)
    81 
    82 fun encode_type (Type (c, Ts)) = Term.list_comb (Const (c, dummyT), map encode_type Ts)
    83   | encode_type (TFree (a, _)) = Free (a, dummyT)
    84   | encode_type (TVar (a, _)) = Var (a, dummyT);
    85 
    86 
    87 (* variables -- ordered left-to-right, preferring right *)
    88 
    89 fun vars_of tm =
    90   rev (distinct (op =) (Term.fold_aterms (fn (t as Var _) => cons t | _ => I) tm []));
    91 
    92 local
    93 
    94 val mk_var = encode_type o #2 o Term.dest_Var;
    95 
    96 fun concl_var which thm = mk_var (which (vars_of (Thm.concl_of thm))) handle Empty =>
    97   raise THM ("No variables in conclusion of rule", 0, [thm]);
    98 
    99 in
   100 
   101 fun left_var_prem thm = mk_var (hd (vars_of (hd (Thm.prems_of thm)))) handle Empty =>
   102   raise THM ("No variables in major premise of rule", 0, [thm]);
   103 
   104 val left_var_concl = concl_var hd;
   105 val right_var_concl = concl_var List.last;
   106 
   107 end;
   108 
   109 
   110 
   111 (** induct data **)
   112 
   113 (* rules *)
   114 
   115 type rules = (string * thm) NetRules.T;
   116 
   117 val init_rules =
   118   NetRules.init (fn ((s1: string, th1), (s2, th2)) => s1 = s2 andalso
   119     Thm.eq_thm_prop (th1, th2));
   120 
   121 fun filter_rules (rs: rules) th =
   122   filter (fn (_, th') => Thm.eq_thm_prop (th, th')) (NetRules.rules rs);
   123 
   124 fun lookup_rule (rs: rules) = AList.lookup (op =) (NetRules.rules rs);
   125 
   126 fun pretty_rules ctxt kind rs =
   127   let val thms = map snd (NetRules.rules rs)
   128   in Pretty.big_list kind (map (ProofContext.pretty_thm ctxt) thms) end;
   129 
   130 
   131 (* context data *)
   132 
   133 structure InductData = GenericDataFun
   134 (
   135   type T = (rules * rules) * (rules * rules) * (rules * rules);
   136   val empty =
   137     ((init_rules (left_var_prem o #2), init_rules (Thm.major_prem_of o #2)),
   138      (init_rules (right_var_concl o #2), init_rules (Thm.major_prem_of o #2)),
   139      (init_rules (left_var_concl o #2), init_rules (Thm.concl_of o #2)));
   140   val extend = I;
   141   fun merge _ (((casesT1, casesP1), (inductT1, inductP1), (coinductT1, coinductP1)),
   142       ((casesT2, casesP2), (inductT2, inductP2), (coinductT2, coinductP2))) =
   143     ((NetRules.merge (casesT1, casesT2), NetRules.merge (casesP1, casesP2)),
   144       (NetRules.merge (inductT1, inductT2), NetRules.merge (inductP1, inductP2)),
   145       (NetRules.merge (coinductT1, coinductT2), NetRules.merge (coinductP1, coinductP2)));
   146 );
   147 
   148 val get_local = InductData.get o Context.Proof;
   149 
   150 fun dest_rules ctxt =
   151   let val ((casesT, casesP), (inductT, inductP), (coinductT, coinductP)) = get_local ctxt in
   152     {type_cases = NetRules.rules casesT,
   153      pred_cases = NetRules.rules casesP,
   154      type_induct = NetRules.rules inductT,
   155      pred_induct = NetRules.rules inductP,
   156      type_coinduct = NetRules.rules coinductT,
   157      pred_coinduct = NetRules.rules coinductP}
   158   end;
   159 
   160 fun print_rules ctxt =
   161   let val ((casesT, casesP), (inductT, inductP), (coinductT, coinductP)) = get_local ctxt in
   162    [pretty_rules ctxt "coinduct type:" coinductT,
   163     pretty_rules ctxt "coinduct pred:" coinductP,
   164     pretty_rules ctxt "induct type:" inductT,
   165     pretty_rules ctxt "induct pred:" inductP,
   166     pretty_rules ctxt "cases type:" casesT,
   167     pretty_rules ctxt "cases pred:" casesP]
   168     |> Pretty.chunks |> Pretty.writeln
   169   end;
   170 
   171 val _ =
   172   OuterSyntax.improper_command "print_induct_rules" "print induction and cases rules"
   173     OuterKeyword.diag (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_context o
   174       Toplevel.keep (print_rules o Toplevel.context_of)));
   175 
   176 
   177 (* access rules *)
   178 
   179 val lookup_casesT = lookup_rule o #1 o #1 o get_local;
   180 val lookup_casesP = lookup_rule o #2 o #1 o get_local;
   181 val lookup_inductT = lookup_rule o #1 o #2 o get_local;
   182 val lookup_inductP = lookup_rule o #2 o #2 o get_local;
   183 val lookup_coinductT = lookup_rule o #1 o #3 o get_local;
   184 val lookup_coinductP = lookup_rule o #2 o #3 o get_local;
   185 
   186 
   187 fun find_rules which how ctxt x =
   188   map snd (NetRules.retrieve (which (get_local ctxt)) (how x));
   189 
   190 val find_casesT = find_rules (#1 o #1) encode_type;
   191 val find_casesP = find_rules (#2 o #1) I;
   192 val find_inductT = find_rules (#1 o #2) encode_type;
   193 val find_inductP = find_rules (#2 o #2) I;
   194 val find_coinductT = find_rules (#1 o #3) encode_type;
   195 val find_coinductP = find_rules (#2 o #3) I;
   196 
   197 
   198 
   199 (** attributes **)
   200 
   201 local
   202 
   203 fun mk_att f g name arg =
   204   let val (x, thm) = g arg in (InductData.map (f (name, thm)) x, thm) end;
   205 
   206 fun del_att which = Thm.declaration_attribute (fn th => InductData.map (which (pairself (fn rs =>
   207   fold NetRules.delete (filter_rules rs th) rs))));
   208 
   209 fun map1 f (x, y, z) = (f x, y, z);
   210 fun map2 f (x, y, z) = (x, f y, z);
   211 fun map3 f (x, y, z) = (x, y, f z);
   212 
   213 fun add_casesT rule x = map1 (apfst (NetRules.insert rule)) x;
   214 fun add_casesP rule x = map1 (apsnd (NetRules.insert rule)) x;
   215 fun add_inductT rule x = map2 (apfst (NetRules.insert rule)) x;
   216 fun add_inductP rule x = map2 (apsnd (NetRules.insert rule)) x;
   217 fun add_coinductT rule x = map3 (apfst (NetRules.insert rule)) x;
   218 fun add_coinductP rule x = map3 (apsnd (NetRules.insert rule)) x;
   219 
   220 val consumes0 = RuleCases.consumes_default 0;
   221 val consumes1 = RuleCases.consumes_default 1;
   222 
   223 in
   224 
   225 val cases_type = mk_att add_casesT consumes0;
   226 val cases_pred = mk_att add_casesP consumes1;
   227 val cases_del = del_att map1;
   228 
   229 val induct_type = mk_att add_inductT consumes0;
   230 val induct_pred = mk_att add_inductP consumes1;
   231 val induct_del = del_att map2;
   232 
   233 val coinduct_type = mk_att add_coinductT consumes0;
   234 val coinduct_pred = mk_att add_coinductP consumes1;
   235 val coinduct_del = del_att map3;
   236 
   237 end;
   238 
   239 
   240 
   241 (** attribute syntax **)
   242 
   243 val casesN = "cases";
   244 val inductN = "induct";
   245 val coinductN = "coinduct";
   246 
   247 val typeN = "type";
   248 val predN = "pred";
   249 val setN = "set";
   250 
   251 local
   252 
   253 fun spec k arg =
   254   Scan.lift (Args.$$$ k -- Args.colon) |-- arg ||
   255   Scan.lift (Args.$$$ k) >> K "";
   256 
   257 fun attrib add_type add_pred del = Attrib.syntax
   258  (spec typeN Args.tyname >> add_type ||
   259   spec predN Args.const >> add_pred ||
   260   spec setN Args.const >> add_pred ||
   261   Scan.lift Args.del >> K del);
   262 
   263 val cases_att = attrib cases_type cases_pred cases_del;
   264 val induct_att = attrib induct_type induct_pred induct_del;
   265 val coinduct_att = attrib coinduct_type coinduct_pred coinduct_del;
   266 
   267 in
   268 
   269 val attrib_setup = Attrib.add_attributes
   270  [(casesN, cases_att, "declaration of cases rule"),
   271   (inductN, induct_att, "declaration of induction rule"),
   272   (coinductN, coinduct_att, "declaration of coinduction rule")];
   273 
   274 end;
   275 
   276 
   277 
   278 (** method utils **)
   279 
   280 (* alignment *)
   281 
   282 fun align_left msg xs ys =
   283   let val m = length xs and n = length ys
   284   in if m < n then error msg else (Library.take (n, xs) ~~ ys) end;
   285 
   286 fun align_right msg xs ys =
   287   let val m = length xs and n = length ys
   288   in if m < n then error msg else (Library.drop (m - n, xs) ~~ ys) end;
   289 
   290 
   291 (* prep_inst *)
   292 
   293 fun prep_inst thy align tune (tm, ts) =
   294   let
   295     val cert = Thm.cterm_of thy;
   296     fun prep_var (x, SOME t) =
   297           let
   298             val cx = cert x;
   299             val xT = #T (Thm.rep_cterm cx);
   300             val ct = cert (tune t);
   301             val tT = Thm.ctyp_of_term ct;
   302           in
   303             if Type.could_unify (Thm.typ_of tT, xT) then SOME (cx, ct)
   304             else error (Pretty.string_of (Pretty.block
   305              [Pretty.str "Ill-typed instantiation:", Pretty.fbrk,
   306               Display.pretty_cterm ct, Pretty.str " ::", Pretty.brk 1,
   307               Display.pretty_ctyp (#T (Thm.crep_cterm ct))]))
   308           end
   309       | prep_var (_, NONE) = NONE;
   310     val xs = vars_of tm;
   311   in
   312     align "Rule has fewer variables than instantiations given" xs ts
   313     |> map_filter prep_var
   314   end;
   315 
   316 
   317 (* trace_rules *)
   318 
   319 fun trace_rules _ kind [] = error ("Unable to figure out " ^ kind ^ " rule")
   320   | trace_rules ctxt _ rules = Method.trace ctxt rules;
   321 
   322 
   323 
   324 (** cases method **)
   325 
   326 (*
   327   rule selection scheme:
   328           cases         - default case split
   329     `A t` cases ...     - predicate/set cases
   330           cases t       - type cases
   331     ...   cases ... r   - explicit rule
   332 *)
   333 
   334 local
   335 
   336 fun get_casesT ctxt ((SOME t :: _) :: _) = find_casesT ctxt (Term.fastype_of t)
   337   | get_casesT _ _ = [];
   338 
   339 fun get_casesP ctxt (fact :: _) = find_casesP ctxt (Thm.concl_of fact)
   340   | get_casesP _ _ = [];
   341 
   342 in
   343 
   344 fun cases_tac ctxt insts opt_rule facts =
   345   let
   346     val thy = ProofContext.theory_of ctxt;
   347     val cert = Thm.cterm_of thy;
   348 
   349     fun inst_rule r =
   350       if null insts then `RuleCases.get r
   351       else (align_left "Rule has fewer premises than arguments given" (Thm.prems_of r) insts
   352         |> maps (prep_inst thy align_left I)
   353         |> Drule.cterm_instantiate) r |> pair (RuleCases.get r);
   354 
   355     val ruleq =
   356       (case opt_rule of
   357         SOME r => Seq.single (inst_rule r)
   358       | NONE =>
   359           (get_casesP ctxt facts @ get_casesT ctxt insts @ [Data.cases_default])
   360           |> tap (trace_rules ctxt casesN)
   361           |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
   362   in
   363     fn i => fn st =>
   364       ruleq
   365       |> Seq.maps (RuleCases.consume [] facts)
   366       |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
   367         CASES (RuleCases.make_common false (thy, Thm.prop_of rule) cases)
   368           (Method.insert_tac more_facts i THEN Tactic.rtac rule i) st)
   369   end;
   370 
   371 end;
   372 
   373 
   374 
   375 (** induct method **)
   376 
   377 val conjunction_congs = [@{thm Pure.all_conjunction}, @{thm imp_conjunction}];
   378 
   379 
   380 (* atomize *)
   381 
   382 fun atomize_term thy =
   383   MetaSimplifier.rewrite_term thy Data.atomize []
   384   #> ObjectLogic.drop_judgment thy;
   385 
   386 val atomize_cterm = MetaSimplifier.rewrite true Data.atomize;
   387 
   388 val atomize_tac = Simplifier.rewrite_goal_tac Data.atomize;
   389 
   390 val inner_atomize_tac =
   391   Simplifier.rewrite_goal_tac (map Thm.symmetric conjunction_congs) THEN' atomize_tac;
   392 
   393 
   394 (* rulify *)
   395 
   396 fun rulify_term thy =
   397   MetaSimplifier.rewrite_term thy (Data.rulify @ conjunction_congs) [] #>
   398   MetaSimplifier.rewrite_term thy Data.rulify_fallback [];
   399 
   400 fun rulified_term thm =
   401   let
   402     val thy = Thm.theory_of_thm thm;
   403     val rulify = rulify_term thy;
   404     val (As, B) = Logic.strip_horn (Thm.prop_of thm);
   405   in (thy, Logic.list_implies (map rulify As, rulify B)) end;
   406 
   407 val rulify_tac =
   408   Simplifier.rewrite_goal_tac (Data.rulify @ conjunction_congs) THEN'
   409   Simplifier.rewrite_goal_tac Data.rulify_fallback THEN'
   410   Goal.conjunction_tac THEN_ALL_NEW
   411   (Simplifier.rewrite_goal_tac [@{thm Pure.conjunction_imp}] THEN' Goal.norm_hhf_tac);
   412 
   413 
   414 (* prepare rule *)
   415 
   416 fun rule_instance thy inst rule =
   417   Drule.cterm_instantiate (prep_inst thy align_left I (Thm.prop_of rule, inst)) rule;
   418 
   419 fun internalize k th =
   420   th |> Thm.permute_prems 0 k
   421   |> Conv.fconv_rule (Conv.concl_conv (Thm.nprems_of th - k) atomize_cterm);
   422 
   423 
   424 (* guess rule instantiation -- cannot handle pending goal parameters *)
   425 
   426 local
   427 
   428 fun dest_env thy (env as Envir.Envir {iTs, ...}) =
   429   let
   430     val cert = Thm.cterm_of thy;
   431     val certT = Thm.ctyp_of thy;
   432     val pairs = Envir.alist_of env;
   433     val ts = map (cert o Envir.norm_term env o #2 o #2) pairs;
   434     val xs = map2 (curry (cert o Var)) (map #1 pairs) (map (#T o Thm.rep_cterm) ts);
   435   in (map (fn (xi, (S, T)) => (certT (TVar (xi, S)), certT T)) (Vartab.dest iTs), xs ~~ ts) end;
   436 
   437 in
   438 
   439 fun guess_instance ctxt rule i st =
   440   let
   441     val thy = ProofContext.theory_of ctxt;
   442     val maxidx = Thm.maxidx_of st;
   443     val goal = Thm.term_of (Thm.cprem_of st i);  (*exception Subscript*)
   444     val params = rev (rename_wrt_term goal (Logic.strip_params goal));
   445   in
   446     if not (null params) then
   447       (warning ("Cannot determine rule instantiation due to pending parameter(s): " ^
   448         commas_quote (map (Syntax.string_of_term ctxt o Syntax.mark_boundT) params));
   449       Seq.single rule)
   450     else
   451       let
   452         val rule' = Thm.incr_indexes (maxidx + 1) rule;
   453         val concl = Logic.strip_assums_concl goal;
   454       in
   455         Unify.smash_unifiers thy [(Thm.concl_of rule', concl)]
   456           (Envir.empty (#maxidx (Thm.rep_thm rule')))
   457         |> Seq.map (fn env => Drule.instantiate (dest_env thy env) rule')
   458       end
   459   end handle Subscript => Seq.empty;
   460 
   461 end;
   462 
   463 
   464 (* special renaming of rule parameters *)
   465 
   466 fun special_rename_params ctxt [[SOME (Free (z, Type (T, _)))]] [thm] =
   467       let
   468         val x = Name.clean (ProofContext.revert_skolem ctxt z);
   469         fun index i [] = []
   470           | index i (y :: ys) =
   471               if x = y then x ^ string_of_int i :: index (i + 1) ys
   472               else y :: index i ys;
   473         fun rename_params [] = []
   474           | rename_params ((y, Type (U, _)) :: ys) =
   475               (if U = T then x else y) :: rename_params ys
   476           | rename_params ((y, _) :: ys) = y :: rename_params ys;
   477         fun rename_asm A =
   478           let
   479             val xs = rename_params (Logic.strip_params A);
   480             val xs' =
   481               (case List.filter (equal x) xs of
   482                 [] => xs | [_] => xs | _ => index 1 xs);
   483           in Logic.list_rename_params (xs', A) end;
   484         fun rename_prop p =
   485           let val (As, C) = Logic.strip_horn p
   486           in Logic.list_implies (map rename_asm As, C) end;
   487         val cp' = cterm_fun rename_prop (Thm.cprop_of thm);
   488         val thm' = Thm.equal_elim (Thm.reflexive cp') thm;
   489       in [RuleCases.save thm thm'] end
   490   | special_rename_params _ _ ths = ths;
   491 
   492 
   493 (* fix_tac *)
   494 
   495 local
   496 
   497 fun goal_prefix k ((c as Const ("all", _)) $ Abs (a, T, B)) = c $ Abs (a, T, goal_prefix k B)
   498   | goal_prefix 0 _ = Term.dummy_pattern propT
   499   | goal_prefix k ((c as Const ("==>", _)) $ A $ B) = c $ A $ goal_prefix (k - 1) B
   500   | goal_prefix _ _ = Term.dummy_pattern propT;
   501 
   502 fun goal_params k (Const ("all", _) $ Abs (_, _, B)) = goal_params k B + 1
   503   | goal_params 0 _ = 0
   504   | goal_params k (Const ("==>", _) $ _ $ B) = goal_params (k - 1) B
   505   | goal_params _ _ = 0;
   506 
   507 fun meta_spec_tac ctxt n (x, T) = SUBGOAL (fn (goal, i) =>
   508   let
   509     val thy = ProofContext.theory_of ctxt;
   510     val cert = Thm.cterm_of thy;
   511     val certT = Thm.ctyp_of thy;
   512 
   513     val v = Free (x, T);
   514     fun spec_rule prfx (xs, body) =
   515       @{thm Pure.meta_spec}
   516       |> Thm.rename_params_rule ([Name.clean (ProofContext.revert_skolem ctxt x)], 1)
   517       |> Thm.lift_rule (cert prfx)
   518       |> `(Thm.prop_of #> Logic.strip_assums_concl)
   519       |-> (fn pred $ arg =>
   520         Drule.cterm_instantiate
   521           [(cert (Term.head_of pred), cert (Logic.rlist_abs (xs, body))),
   522            (cert (Term.head_of arg), cert (Logic.rlist_abs (xs, v)))]);
   523 
   524     fun goal_concl k xs (Const ("all", _) $ Abs (a, T, B)) = goal_concl k ((a, T) :: xs) B
   525       | goal_concl 0 xs B =
   526           if not (Term.exists_subterm (fn t => t aconv v) B) then NONE
   527           else SOME (xs, Term.absfree (x, T, Term.incr_boundvars 1 B))
   528       | goal_concl k xs (Const ("==>", _) $ _ $ B) = goal_concl (k - 1) xs B
   529       | goal_concl _ _ _ = NONE;
   530   in
   531     (case goal_concl n [] goal of
   532       SOME concl =>
   533         (compose_tac (false, spec_rule (goal_prefix n goal) concl, 1) THEN' rtac asm_rl) i
   534     | NONE => all_tac)
   535   end);
   536 
   537 fun miniscope_tac p = CONVERSION o
   538   Conv.params_conv p (K (MetaSimplifier.rewrite true [Thm.symmetric Drule.norm_hhf_eq]));
   539 
   540 in
   541 
   542 fun fix_tac _ _ [] = K all_tac
   543   | fix_tac ctxt n xs = SUBGOAL (fn (goal, i) =>
   544      (EVERY' (map (meta_spec_tac ctxt n) xs) THEN'
   545       (miniscope_tac (goal_params n goal) ctxt)) i);
   546 
   547 end;
   548 
   549 
   550 (* add_defs *)
   551 
   552 fun add_defs def_insts =
   553   let
   554     fun add (SOME (SOME x, t)) ctxt =
   555           let val ([(lhs, (_, th))], ctxt') =
   556             LocalDefs.add_defs [((x, NoSyn), ((Name.no_binding, []), t))] ctxt
   557           in ((SOME lhs, [th]), ctxt') end
   558       | add (SOME (NONE, t)) ctxt = ((SOME t, []), ctxt)
   559       | add NONE ctxt = ((NONE, []), ctxt);
   560   in fold_map add def_insts #> apfst (split_list #> apsnd flat) end;
   561 
   562 
   563 (* induct_tac *)
   564 
   565 (*
   566   rule selection scheme:
   567     `A x` induct ...     - predicate/set induction
   568           induct x       - type induction
   569     ...   induct ... r   - explicit rule
   570 *)
   571 
   572 fun get_inductT ctxt insts =
   573   fold_rev multiply (insts |> map
   574       ((fn [] => NONE | ts => List.last ts) #>
   575         (fn NONE => TVar (("'a", 0), []) | SOME t => Term.fastype_of t) #>
   576         find_inductT ctxt)) [[]]
   577   |> filter_out (forall Thm.is_internal);
   578 
   579 fun get_inductP ctxt (fact :: _) = map single (find_inductP ctxt (Thm.concl_of fact))
   580   | get_inductP _ _ = [];
   581 
   582 fun induct_tac ctxt def_insts arbitrary taking opt_rule facts =
   583   let
   584     val thy = ProofContext.theory_of ctxt;
   585     val cert = Thm.cterm_of thy;
   586 
   587     val ((insts, defs), defs_ctxt) = fold_map add_defs def_insts ctxt |>> split_list;
   588     val atomized_defs = map (map (Conv.fconv_rule ObjectLogic.atomize)) defs;
   589 
   590     fun inst_rule (concls, r) =
   591       (if null insts then `RuleCases.get r
   592        else (align_left "Rule has fewer conclusions than arguments given"
   593           (map Logic.strip_imp_concl (Logic.dest_conjunctions (Thm.concl_of r))) insts
   594         |> maps (prep_inst thy align_right (atomize_term thy))
   595         |> Drule.cterm_instantiate) r |> pair (RuleCases.get r))
   596       |> (fn ((cases, consumes), th) => (((cases, concls), consumes), th));
   597 
   598     val ruleq =
   599       (case opt_rule of
   600         SOME rs => Seq.single (inst_rule (RuleCases.strict_mutual_rule ctxt rs))
   601       | NONE =>
   602           (get_inductP ctxt facts @
   603             map (special_rename_params defs_ctxt insts) (get_inductT ctxt insts))
   604           |> map_filter (RuleCases.mutual_rule ctxt)
   605           |> tap (trace_rules ctxt inductN o map #2)
   606           |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
   607 
   608     fun rule_cases rule =
   609       RuleCases.make_nested false (Thm.prop_of rule) (rulified_term rule);
   610   in
   611     (fn i => fn st =>
   612       ruleq
   613       |> Seq.maps (RuleCases.consume (flat defs) facts)
   614       |> Seq.maps (fn (((cases, concls), (more_consumes, more_facts)), rule) =>
   615         (PRECISE_CONJUNCTS (length concls) (ALLGOALS (fn j =>
   616           (CONJUNCTS (ALLGOALS
   617             (Method.insert_tac (more_facts @ nth_list atomized_defs (j - 1))
   618               THEN' fix_tac defs_ctxt
   619                 (nth concls (j - 1) + more_consumes)
   620                 (nth_list arbitrary (j - 1))))
   621           THEN' inner_atomize_tac) j))
   622         THEN' atomize_tac) i st |> Seq.maps (fn st' =>
   623             guess_instance ctxt (internalize more_consumes rule) i st'
   624             |> Seq.map (rule_instance thy (burrow_options (Variable.polymorphic ctxt) taking))
   625             |> Seq.maps (fn rule' =>
   626               CASES (rule_cases rule' cases)
   627                 (Tactic.rtac rule' i THEN
   628                   PRIMITIVE (singleton (ProofContext.export defs_ctxt ctxt))) st'))))
   629     THEN_ALL_NEW_CASES rulify_tac
   630   end;
   631 
   632 
   633 
   634 (** coinduct method **)
   635 
   636 (*
   637   rule selection scheme:
   638     goal "A x" coinduct ...   - predicate/set coinduction
   639                coinduct x     - type coinduction
   640                coinduct ... r - explicit rule
   641 *)
   642 
   643 local
   644 
   645 fun get_coinductT ctxt (SOME t :: _) = find_coinductT ctxt (Term.fastype_of t)
   646   | get_coinductT _ _ = [];
   647 
   648 fun get_coinductP ctxt goal = find_coinductP ctxt (Logic.strip_assums_concl goal);
   649 
   650 fun main_prop_of th =
   651   if RuleCases.get_consumes th > 0 then Thm.major_prem_of th else Thm.concl_of th;
   652 
   653 in
   654 
   655 fun coinduct_tac ctxt inst taking opt_rule facts =
   656   let
   657     val thy = ProofContext.theory_of ctxt;
   658     val cert = Thm.cterm_of thy;
   659 
   660     fun inst_rule r =
   661       if null inst then `RuleCases.get r
   662       else Drule.cterm_instantiate (prep_inst thy align_right I (main_prop_of r, inst)) r
   663         |> pair (RuleCases.get r);
   664 
   665     fun ruleq goal =
   666       (case opt_rule of
   667         SOME r => Seq.single (inst_rule r)
   668       | NONE =>
   669           (get_coinductP ctxt goal @ get_coinductT ctxt inst)
   670           |> tap (trace_rules ctxt coinductN)
   671           |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
   672   in
   673     SUBGOAL_CASES (fn (goal, i) => fn st =>
   674       ruleq goal
   675       |> Seq.maps (RuleCases.consume [] facts)
   676       |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
   677         guess_instance ctxt rule i st
   678         |> Seq.map (rule_instance thy (burrow_options (Variable.polymorphic ctxt) taking))
   679         |> Seq.maps (fn rule' =>
   680           CASES (RuleCases.make_common false (thy, Thm.prop_of rule') cases)
   681             (Method.insert_tac more_facts i THEN Tactic.rtac rule' i) st)))
   682   end;
   683 
   684 end;
   685 
   686 
   687 
   688 (** concrete syntax **)
   689 
   690 structure P = OuterParse;
   691 
   692 val arbitraryN = "arbitrary";
   693 val takingN = "taking";
   694 val ruleN = "rule";
   695 
   696 local
   697 
   698 fun single_rule [rule] = rule
   699   | single_rule _ = error "Single rule expected";
   700 
   701 fun named_rule k arg get =
   702   Scan.lift (Args.$$$ k -- Args.colon) |-- Scan.repeat arg :|--
   703     (fn names => Scan.peek (fn context => Scan.succeed (names |> map (fn name =>
   704       (case get (Context.proof_of context) name of SOME x => x
   705       | NONE => error ("No rule for " ^ k ^ " " ^ quote name))))));
   706 
   707 fun rule get_type get_pred =
   708   named_rule typeN Args.tyname get_type ||
   709   named_rule predN Args.const get_pred ||
   710   named_rule setN Args.const get_pred ||
   711   Scan.lift (Args.$$$ ruleN -- Args.colon) |-- Attrib.thms;
   712 
   713 val cases_rule = rule lookup_casesT lookup_casesP >> single_rule;
   714 val induct_rule = rule lookup_inductT lookup_inductP;
   715 val coinduct_rule = rule lookup_coinductT lookup_coinductP >> single_rule;
   716 
   717 val inst = Scan.lift (Args.$$$ "_") >> K NONE || Args.term >> SOME;
   718 
   719 val def_inst =
   720   ((Scan.lift (Args.binding --| (Args.$$$ "\<equiv>" || Args.$$$ "==")) >> SOME)
   721       -- Args.term) >> SOME ||
   722     inst >> Option.map (pair NONE);
   723 
   724 val free = Args.context -- Args.term >> (fn (_, Free v) => v | (ctxt, t) =>
   725   error ("Bad free variable: " ^ Syntax.string_of_term ctxt t));
   726 
   727 fun unless_more_args scan = Scan.unless (Scan.lift
   728   ((Args.$$$ arbitraryN || Args.$$$ takingN || Args.$$$ typeN ||
   729     Args.$$$ predN || Args.$$$ setN || Args.$$$ ruleN) -- Args.colon)) scan;
   730 
   731 val arbitrary = Scan.optional (Scan.lift (Args.$$$ arbitraryN -- Args.colon) |--
   732   P.and_list1' (Scan.repeat (unless_more_args free))) [];
   733 
   734 val taking = Scan.optional (Scan.lift (Args.$$$ takingN -- Args.colon) |--
   735   Scan.repeat1 (unless_more_args inst)) [];
   736 
   737 in
   738 
   739 fun cases_meth src =
   740   Method.syntax (P.and_list' (Scan.repeat (unless_more_args inst)) -- Scan.option cases_rule) src
   741   #> (fn ((insts, opt_rule), ctxt) =>
   742     Method.METHOD_CASES (fn facts =>
   743       Seq.DETERM (HEADGOAL (cases_tac ctxt insts opt_rule facts))));
   744 
   745 fun induct_meth src =
   746   Method.syntax (P.and_list' (Scan.repeat (unless_more_args def_inst)) --
   747     (arbitrary -- taking -- Scan.option induct_rule)) src
   748   #> (fn ((insts, ((arbitrary, taking), opt_rule)), ctxt) =>
   749     Method.RAW_METHOD_CASES (fn facts =>
   750       Seq.DETERM (HEADGOAL (induct_tac ctxt insts arbitrary taking opt_rule facts))));
   751 
   752 fun coinduct_meth src =
   753   Method.syntax (Scan.repeat (unless_more_args inst) -- taking -- Scan.option coinduct_rule) src
   754   #> (fn (((insts, taking), opt_rule), ctxt) =>
   755     Method.RAW_METHOD_CASES (fn facts =>
   756       Seq.DETERM (HEADGOAL (coinduct_tac ctxt insts taking opt_rule facts))));
   757 
   758 end;
   759 
   760 
   761 
   762 (** theory setup **)
   763 
   764 val setup =
   765   attrib_setup #>
   766   Method.add_methods
   767     [(casesN, cases_meth, "case analysis on types or predicates/sets"),
   768      (inductN, induct_meth, "induction on types or predicates/sets"),
   769      (coinductN, coinduct_meth, "coinduction on types or predicates/sets")];
   770 
   771 end;