src/Tools/induct.ML
author wenzelm
Thu Apr 18 17:07:01 2013 +0200 (2013-04-18)
changeset 51717 9e7d1c139569
parent 51658 21c10672633b
child 52684 8d749ebd9ab8
permissions -rw-r--r--
simplifier uses proper Proof.context instead of historic type simpset;
     1 (*  Title:      Tools/induct.ML
     2     Author:     Markus Wenzel, TU Muenchen
     3 
     4 Proof by cases, induction, and coinduction.
     5 *)
     6 
     7 signature INDUCT_ARGS =
     8 sig
     9   val cases_default: thm
    10   val atomize: thm list
    11   val rulify: thm list
    12   val rulify_fallback: thm list
    13   val equal_def: thm
    14   val dest_def: term -> (term * term) option
    15   val trivial_tac: int -> tactic
    16 end;
    17 
    18 signature INDUCT =
    19 sig
    20   (*rule declarations*)
    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: (Proof.context -> Proof.context) -> Context.generic -> Context.generic
    49   val induct_simp_add: attribute
    50   val induct_simp_del: attribute
    51   val no_simpN: string
    52   val casesN: string
    53   val inductN: string
    54   val coinductN: string
    55   val typeN: string
    56   val predN: string
    57   val setN: string
    58   (*proof methods*)
    59   val arbitrary_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   type case_data = (((string * string list) * string list) list * int) (* FIXME -> rule_cases.ML *)
    78   val gen_induct_tac: (theory -> case_data * thm -> case_data * thm) ->
    79     Proof.context -> bool -> (binding option * (term * bool)) option list list ->
    80     (string * typ) list list -> term option list -> thm list option ->
    81     thm list -> int -> cases_tactic
    82   val induct_tac: Proof.context -> bool -> (binding option * (term * bool)) option list list ->
    83     (string * typ) list list -> term option list -> thm list option ->
    84     thm list -> int -> cases_tactic
    85   val coinduct_tac: Proof.context -> term option list -> term option list -> thm option ->
    86     thm list -> int -> cases_tactic
    87   val gen_induct_setup: binding ->
    88    (Proof.context -> bool -> (binding option * (term * bool)) option list list ->
    89     (string * typ) list list -> term option list -> thm list option ->
    90     thm list -> int -> cases_tactic) ->
    91    theory -> theory
    92   val setup: theory -> theory
    93 end;
    94 
    95 functor Induct(Induct_Args: INDUCT_ARGS): INDUCT =
    96 struct
    97 
    98 (** variables -- ordered left-to-right, preferring right **)
    99 
   100 fun vars_of tm =
   101   rev (distinct (op =) (Term.fold_aterms (fn t as Var _ => cons t | _ => I) tm []));
   102 
   103 local
   104 
   105 val mk_var = Net.encode_type o #2 o Term.dest_Var;
   106 
   107 fun concl_var which thm = mk_var (which (vars_of (Thm.concl_of thm))) handle List.Empty =>
   108   raise THM ("No variables in conclusion of rule", 0, [thm]);
   109 
   110 in
   111 
   112 fun left_var_prem thm = mk_var (hd (vars_of (hd (Thm.prems_of thm)))) handle List.Empty =>
   113   raise THM ("No variables in major premise of rule", 0, [thm]);
   114 
   115 val left_var_concl = concl_var hd;
   116 val right_var_concl = concl_var List.last;
   117 
   118 end;
   119 
   120 
   121 
   122 (** constraint simplification **)
   123 
   124 (* rearrange parameters and premises to allow application of one-point-rules *)
   125 
   126 fun swap_params_conv ctxt i j cv =
   127   let
   128     fun conv1 0 ctxt = Conv.forall_conv (cv o snd) ctxt
   129       | conv1 k ctxt =
   130           Conv.rewr_conv @{thm swap_params} then_conv
   131           Conv.forall_conv (conv1 (k - 1) o snd) ctxt
   132     fun conv2 0 ctxt = conv1 j ctxt
   133       | conv2 k ctxt = Conv.forall_conv (conv2 (k - 1) o snd) ctxt
   134   in conv2 i ctxt end;
   135 
   136 fun swap_prems_conv 0 = Conv.all_conv
   137   | swap_prems_conv i =
   138       Conv.implies_concl_conv (swap_prems_conv (i - 1)) then_conv
   139       Conv.rewr_conv Drule.swap_prems_eq
   140 
   141 fun drop_judgment ctxt = Object_Logic.drop_judgment (Proof_Context.theory_of ctxt);
   142 
   143 fun find_eq ctxt t =
   144   let
   145     val l = length (Logic.strip_params t);
   146     val Hs = Logic.strip_assums_hyp t;
   147     fun find (i, t) =
   148       (case Induct_Args.dest_def (drop_judgment ctxt t) of
   149         SOME (Bound j, _) => SOME (i, j)
   150       | SOME (_, Bound j) => SOME (i, j)
   151       | _ => NONE);
   152   in
   153     (case get_first find (map_index I Hs) of
   154       NONE => NONE
   155     | SOME (0, 0) => NONE
   156     | SOME (i, j) => SOME (i, l - j - 1, j))
   157   end;
   158 
   159 fun mk_swap_rrule ctxt ct =
   160   (case find_eq ctxt (term_of ct) of
   161     NONE => NONE
   162   | SOME (i, k, j) => SOME (swap_params_conv ctxt k j (K (swap_prems_conv i)) ct));
   163 
   164 val rearrange_eqs_simproc =
   165   Simplifier.simproc_global
   166     (Thm.theory_of_thm Drule.swap_prems_eq) "rearrange_eqs" ["all t"]
   167     (fn ctxt => fn t => mk_swap_rrule ctxt (cterm_of (Proof_Context.theory_of ctxt) t));
   168 
   169 
   170 (* rotate k premises to the left by j, skipping over first j premises *)
   171 
   172 fun rotate_conv 0 j 0 = Conv.all_conv
   173   | rotate_conv 0 j k = swap_prems_conv j then_conv rotate_conv 1 j (k - 1)
   174   | rotate_conv i j k = Conv.implies_concl_conv (rotate_conv (i - 1) j k);
   175 
   176 fun rotate_tac j 0 = K all_tac
   177   | rotate_tac j k = SUBGOAL (fn (goal, i) =>
   178       CONVERSION (rotate_conv
   179         j (length (Logic.strip_assums_hyp goal) - j - k) k) i);
   180 
   181 
   182 (* rulify operators around definition *)
   183 
   184 fun rulify_defs_conv ctxt ct =
   185   if exists_subterm (is_some o Induct_Args.dest_def) (term_of ct) andalso
   186     not (is_some (Induct_Args.dest_def (drop_judgment ctxt (term_of ct))))
   187   then
   188     (Conv.forall_conv (rulify_defs_conv o snd) ctxt else_conv
   189      Conv.implies_conv (Conv.try_conv (rulify_defs_conv ctxt))
   190        (Conv.try_conv (rulify_defs_conv ctxt)) else_conv
   191      Conv.first_conv (map Conv.rewr_conv Induct_Args.rulify) then_conv
   192        Conv.try_conv (rulify_defs_conv ctxt)) ct
   193   else Conv.no_conv ct;
   194 
   195 
   196 
   197 (** induct data **)
   198 
   199 (* rules *)
   200 
   201 type rules = (string * thm) Item_Net.T;
   202 
   203 fun init_rules index : rules =
   204   Item_Net.init
   205     (fn ((s1, th1), (s2, th2)) => s1 = s2 andalso Thm.eq_thm_prop (th1, th2))
   206     (single o index);
   207 
   208 fun filter_rules (rs: rules) th =
   209   filter (fn (_, th') => Thm.eq_thm_prop (th, th')) (Item_Net.content rs);
   210 
   211 fun lookup_rule (rs: rules) = AList.lookup (op =) (Item_Net.content rs);
   212 
   213 fun pretty_rules ctxt kind rs =
   214   let val thms = map snd (Item_Net.content rs)
   215   in Pretty.big_list kind (map (Display.pretty_thm_item ctxt) thms) end;
   216 
   217 
   218 (* context data *)
   219 
   220 structure Data = Generic_Data
   221 (
   222   type T = (rules * rules) * (rules * rules) * (rules * rules) * simpset;
   223   val empty =
   224     ((init_rules (left_var_prem o #2), init_rules (Thm.major_prem_of o #2)),
   225      (init_rules (right_var_concl o #2), init_rules (Thm.major_prem_of o #2)),
   226      (init_rules (left_var_concl o #2), init_rules (Thm.concl_of o #2)),
   227      simpset_of (empty_simpset @{context}
   228       addsimprocs [rearrange_eqs_simproc] addsimps [Drule.norm_hhf_eq]));
   229   val extend = I;
   230   fun merge (((casesT1, casesP1), (inductT1, inductP1), (coinductT1, coinductP1), simpset1),
   231       ((casesT2, casesP2), (inductT2, inductP2), (coinductT2, coinductP2), simpset2)) =
   232     ((Item_Net.merge (casesT1, casesT2), Item_Net.merge (casesP1, casesP2)),
   233      (Item_Net.merge (inductT1, inductT2), Item_Net.merge (inductP1, inductP2)),
   234      (Item_Net.merge (coinductT1, coinductT2), Item_Net.merge (coinductP1, coinductP2)),
   235      merge_ss (simpset1, simpset2));
   236 );
   237 
   238 val get_local = Data.get o Context.Proof;
   239 
   240 fun dest_rules ctxt =
   241   let val ((casesT, casesP), (inductT, inductP), (coinductT, coinductP), _) = get_local ctxt in
   242     {type_cases = Item_Net.content casesT,
   243      pred_cases = Item_Net.content casesP,
   244      type_induct = Item_Net.content inductT,
   245      pred_induct = Item_Net.content inductP,
   246      type_coinduct = Item_Net.content coinductT,
   247      pred_coinduct = Item_Net.content coinductP}
   248   end;
   249 
   250 fun print_rules ctxt =
   251   let val ((casesT, casesP), (inductT, inductP), (coinductT, coinductP), _) = get_local ctxt in
   252    [pretty_rules ctxt "coinduct type:" coinductT,
   253     pretty_rules ctxt "coinduct pred:" coinductP,
   254     pretty_rules ctxt "induct type:" inductT,
   255     pretty_rules ctxt "induct pred:" inductP,
   256     pretty_rules ctxt "cases type:" casesT,
   257     pretty_rules ctxt "cases pred:" casesP]
   258     |> Pretty.chunks |> Pretty.writeln
   259   end;
   260 
   261 val _ =
   262   Outer_Syntax.improper_command @{command_spec "print_induct_rules"}
   263     "print induction and cases rules"
   264     (Scan.succeed (Toplevel.unknown_context o
   265       Toplevel.keep (print_rules o Toplevel.context_of)));
   266 
   267 
   268 (* access rules *)
   269 
   270 val lookup_casesT = lookup_rule o #1 o #1 o get_local;
   271 val lookup_casesP = lookup_rule o #2 o #1 o get_local;
   272 val lookup_inductT = lookup_rule o #1 o #2 o get_local;
   273 val lookup_inductP = lookup_rule o #2 o #2 o get_local;
   274 val lookup_coinductT = lookup_rule o #1 o #3 o get_local;
   275 val lookup_coinductP = lookup_rule o #2 o #3 o get_local;
   276 
   277 
   278 fun find_rules which how ctxt x =
   279   map snd (Item_Net.retrieve (which (get_local ctxt)) (how x));
   280 
   281 val find_casesT = find_rules (#1 o #1) Net.encode_type;
   282 val find_casesP = find_rules (#2 o #1) I;
   283 val find_inductT = find_rules (#1 o #2) Net.encode_type;
   284 val find_inductP = find_rules (#2 o #2) I;
   285 val find_coinductT = find_rules (#1 o #3) Net.encode_type;
   286 val find_coinductP = find_rules (#2 o #3) I;
   287 
   288 
   289 
   290 (** attributes **)
   291 
   292 local
   293 
   294 fun mk_att f g name =
   295   Thm.mixed_attribute (fn (context, thm) =>
   296     let
   297       val thm' = g thm;
   298       val context' = Data.map (f (name, thm')) context;
   299     in (context', thm') end);
   300 
   301 fun del_att which =
   302   Thm.declaration_attribute (fn th => Data.map (which (pairself (fn rs =>
   303     fold Item_Net.remove (filter_rules rs th) rs))));
   304 
   305 fun map1 f (x, y, z, s) = (f x, y, z, s);
   306 fun map2 f (x, y, z, s) = (x, f y, z, s);
   307 fun map3 f (x, y, z, s) = (x, y, f z, s);
   308 fun map4 f (x, y, z, s) = (x, y, z, f s);
   309 
   310 fun add_casesT rule x = map1 (apfst (Item_Net.update rule)) x;
   311 fun add_casesP rule x = map1 (apsnd (Item_Net.update rule)) x;
   312 fun add_inductT rule x = map2 (apfst (Item_Net.update rule)) x;
   313 fun add_inductP rule x = map2 (apsnd (Item_Net.update rule)) x;
   314 fun add_coinductT rule x = map3 (apfst (Item_Net.update rule)) x;
   315 fun add_coinductP rule x = map3 (apsnd (Item_Net.update rule)) x;
   316 
   317 val consumes0 = Rule_Cases.default_consumes 0;
   318 val consumes1 = Rule_Cases.default_consumes 1;
   319 
   320 in
   321 
   322 val cases_type = mk_att add_casesT consumes0;
   323 val cases_pred = mk_att add_casesP consumes1;
   324 val cases_del = del_att map1;
   325 
   326 val induct_type = mk_att add_inductT consumes0;
   327 val induct_pred = mk_att add_inductP consumes1;
   328 val induct_del = del_att map2;
   329 
   330 val coinduct_type = mk_att add_coinductT consumes0;
   331 val coinduct_pred = mk_att add_coinductP consumes1;
   332 val coinduct_del = del_att map3;
   333 
   334 fun map_simpset f context =
   335   context |> (Data.map o map4 o Simplifier.simpset_map (Context.proof_of context)) f;
   336 
   337 fun induct_simp f =
   338   Thm.declaration_attribute (fn thm => map_simpset (fn ctxt => f (ctxt, [thm])));
   339 
   340 val induct_simp_add = induct_simp (op addsimps);
   341 val induct_simp_del = induct_simp (op delsimps);
   342 
   343 end;
   344 
   345 
   346 
   347 (** attribute syntax **)
   348 
   349 val no_simpN = "no_simp";
   350 val casesN = "cases";
   351 val inductN = "induct";
   352 val coinductN = "coinduct";
   353 
   354 val typeN = "type";
   355 val predN = "pred";
   356 val setN = "set";
   357 
   358 local
   359 
   360 fun spec k arg =
   361   Scan.lift (Args.$$$ k -- Args.colon) |-- arg ||
   362   Scan.lift (Args.$$$ k) >> K "";
   363 
   364 fun attrib add_type add_pred del =
   365   spec typeN (Args.type_name false) >> add_type ||
   366   spec predN (Args.const false) >> add_pred ||
   367   spec setN (Args.const false) >> add_pred ||
   368   Scan.lift Args.del >> K del;
   369 
   370 in
   371 
   372 val attrib_setup =
   373   Attrib.setup @{binding cases} (attrib cases_type cases_pred cases_del)
   374     "declaration of cases rule" #>
   375   Attrib.setup @{binding induct} (attrib induct_type induct_pred induct_del)
   376     "declaration of induction rule" #>
   377   Attrib.setup @{binding coinduct} (attrib coinduct_type coinduct_pred coinduct_del)
   378     "declaration of coinduction rule" #>
   379   Attrib.setup @{binding induct_simp} (Attrib.add_del induct_simp_add induct_simp_del)
   380     "declaration of rules for simplifying induction or cases rules";
   381 
   382 end;
   383 
   384 
   385 
   386 (** method utils **)
   387 
   388 (* alignment *)
   389 
   390 fun align_left msg xs ys =
   391   let val m = length xs and n = length ys
   392   in if m < n then error msg else (take n xs ~~ ys) end;
   393 
   394 fun align_right msg xs ys =
   395   let val m = length xs and n = length ys
   396   in if m < n then error msg else (drop (m - n) xs ~~ ys) end;
   397 
   398 
   399 (* prep_inst *)
   400 
   401 fun prep_inst ctxt align tune (tm, ts) =
   402   let
   403     val cert = Thm.cterm_of (Proof_Context.theory_of ctxt);
   404     fun prep_var (x, SOME t) =
   405           let
   406             val cx = cert x;
   407             val xT = #T (Thm.rep_cterm cx);
   408             val ct = cert (tune t);
   409             val tT = #T (Thm.rep_cterm ct);
   410           in
   411             if Type.could_unify (tT, xT) then SOME (cx, ct)
   412             else error (Pretty.string_of (Pretty.block
   413              [Pretty.str "Ill-typed instantiation:", Pretty.fbrk,
   414               Syntax.pretty_term ctxt (Thm.term_of ct), Pretty.str " ::", Pretty.brk 1,
   415               Syntax.pretty_typ ctxt tT]))
   416           end
   417       | prep_var (_, NONE) = NONE;
   418     val xs = vars_of tm;
   419   in
   420     align "Rule has fewer variables than instantiations given" xs ts
   421     |> map_filter prep_var
   422   end;
   423 
   424 
   425 (* trace_rules *)
   426 
   427 fun trace_rules _ kind [] = error ("Unable to figure out " ^ kind ^ " rule")
   428   | trace_rules ctxt _ rules = Method.trace ctxt rules;
   429 
   430 
   431 (* mark equality constraints in cases rule *)
   432 
   433 val equal_def' = Thm.symmetric Induct_Args.equal_def;
   434 
   435 fun mark_constraints n ctxt = Conv.fconv_rule
   436   (Conv.prems_conv ~1 (Conv.params_conv ~1 (K (Conv.prems_conv n
   437      (Raw_Simplifier.rewrite false [equal_def']))) ctxt));
   438 
   439 val unmark_constraints = Conv.fconv_rule
   440   (Raw_Simplifier.rewrite true [Induct_Args.equal_def]);
   441 
   442 
   443 (* simplify *)
   444 
   445 fun simplify_conv' ctxt =
   446   Simplifier.full_rewrite (put_simpset (#4 (get_local ctxt)) ctxt);
   447 
   448 fun simplify_conv ctxt ct =
   449   if exists_subterm (is_some o Induct_Args.dest_def) (term_of ct) then
   450     (Conv.try_conv (rulify_defs_conv ctxt) then_conv simplify_conv' ctxt) ct
   451   else Conv.all_conv ct;
   452 
   453 fun gen_simplified_rule cv ctxt =
   454   Conv.fconv_rule (Conv.prems_conv ~1 (cv ctxt));
   455 
   456 val simplified_rule' = gen_simplified_rule simplify_conv';
   457 val simplified_rule = gen_simplified_rule simplify_conv;
   458 
   459 fun simplify_tac ctxt = CONVERSION (simplify_conv ctxt);
   460 
   461 val trivial_tac = Induct_Args.trivial_tac;
   462 
   463 
   464 
   465 (** cases method **)
   466 
   467 (*
   468   rule selection scheme:
   469           cases         - default case split
   470     `A t` cases ...     - predicate/set cases
   471           cases t       - type cases
   472     ...   cases ... r   - explicit rule
   473 *)
   474 
   475 local
   476 
   477 fun get_casesT ctxt ((SOME t :: _) :: _) = find_casesT ctxt (Term.fastype_of t)
   478   | get_casesT _ _ = [];
   479 
   480 fun get_casesP ctxt (fact :: _) = find_casesP ctxt (Thm.concl_of fact)
   481   | get_casesP _ _ = [];
   482 
   483 in
   484 
   485 fun cases_tac ctxt simp insts opt_rule facts =
   486   let
   487     val thy = Proof_Context.theory_of ctxt;
   488 
   489     fun inst_rule r =
   490       (if null insts then r
   491        else
   492          (align_left "Rule has fewer premises than arguments given" (Thm.prems_of r) insts
   493            |> maps (prep_inst ctxt align_left I)
   494            |> Drule.cterm_instantiate) r)
   495       |> simp ? mark_constraints (Rule_Cases.get_constraints r) ctxt
   496       |> pair (Rule_Cases.get r);
   497 
   498     val ruleq =
   499       (case opt_rule of
   500         SOME r => Seq.single (inst_rule r)
   501       | NONE =>
   502           (get_casesP ctxt facts @ get_casesT ctxt insts @ [Induct_Args.cases_default])
   503           |> tap (trace_rules ctxt casesN)
   504           |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
   505   in
   506     fn i => fn st =>
   507       ruleq
   508       |> Seq.maps (Rule_Cases.consume [] facts)
   509       |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
   510         let
   511           val rule' = rule
   512             |> simp ? (simplified_rule' ctxt #> unmark_constraints);
   513         in
   514           CASES (Rule_Cases.make_common (thy,
   515               Thm.prop_of (Rule_Cases.internalize_params rule')) cases)
   516             ((Method.insert_tac more_facts THEN' rtac rule' THEN_ALL_NEW
   517                 (if simp then TRY o trivial_tac else K all_tac)) i) st
   518         end)
   519   end;
   520 
   521 end;
   522 
   523 
   524 
   525 (** induct method **)
   526 
   527 val conjunction_congs = [@{thm Pure.all_conjunction}, @{thm imp_conjunction}];
   528 
   529 
   530 (* atomize *)
   531 
   532 fun atomize_term thy =
   533   Raw_Simplifier.rewrite_term thy Induct_Args.atomize []
   534   #> Object_Logic.drop_judgment thy;
   535 
   536 val atomize_cterm = Raw_Simplifier.rewrite true Induct_Args.atomize;
   537 
   538 val atomize_tac = Simplifier.rewrite_goal_tac Induct_Args.atomize;
   539 
   540 val inner_atomize_tac =
   541   Simplifier.rewrite_goal_tac (map Thm.symmetric conjunction_congs) THEN' atomize_tac;
   542 
   543 
   544 (* rulify *)
   545 
   546 fun rulify_term thy =
   547   Raw_Simplifier.rewrite_term thy (Induct_Args.rulify @ conjunction_congs) [] #>
   548   Raw_Simplifier.rewrite_term thy Induct_Args.rulify_fallback [];
   549 
   550 fun rulified_term thm =
   551   let
   552     val thy = Thm.theory_of_thm thm;
   553     val rulify = rulify_term thy;
   554     val (As, B) = Logic.strip_horn (Thm.prop_of thm);
   555   in (thy, Logic.list_implies (map rulify As, rulify B)) end;
   556 
   557 val rulify_tac =
   558   Simplifier.rewrite_goal_tac (Induct_Args.rulify @ conjunction_congs) THEN'
   559   Simplifier.rewrite_goal_tac Induct_Args.rulify_fallback THEN'
   560   Goal.conjunction_tac THEN_ALL_NEW
   561   (Simplifier.rewrite_goal_tac [@{thm Pure.conjunction_imp}] THEN' Goal.norm_hhf_tac);
   562 
   563 
   564 (* prepare rule *)
   565 
   566 fun rule_instance ctxt inst rule =
   567   Drule.cterm_instantiate (prep_inst ctxt align_left I (Thm.prop_of rule, inst)) rule;
   568 
   569 fun internalize k th =
   570   th |> Thm.permute_prems 0 k
   571   |> Conv.fconv_rule (Conv.concl_conv (Thm.nprems_of th - k) atomize_cterm);
   572 
   573 
   574 (* guess rule instantiation -- cannot handle pending goal parameters *)
   575 
   576 local
   577 
   578 fun dest_env thy env =
   579   let
   580     val cert = Thm.cterm_of thy;
   581     val certT = Thm.ctyp_of thy;
   582     val pairs = Vartab.dest (Envir.term_env env);
   583     val types = Vartab.dest (Envir.type_env env);
   584     val ts = map (cert o Envir.norm_term env o #2 o #2) pairs;
   585     val xs = map2 (curry (cert o Var)) (map #1 pairs) (map (#T o Thm.rep_cterm) ts);
   586   in (map (fn (xi, (S, T)) => (certT (TVar (xi, S)), certT T)) types, xs ~~ ts) end;
   587 
   588 in
   589 
   590 fun guess_instance ctxt rule i st =
   591   let
   592     val thy = Proof_Context.theory_of ctxt;
   593     val maxidx = Thm.maxidx_of st;
   594     val goal = Thm.term_of (Thm.cprem_of st i);  (*exception Subscript*)
   595     val params = rev (Term.rename_wrt_term goal (Logic.strip_params goal));
   596   in
   597     if not (null params) then
   598       (warning ("Cannot determine rule instantiation due to pending parameter(s): " ^
   599         commas_quote (map (Syntax.string_of_term ctxt o Syntax_Trans.mark_bound_abs) params));
   600       Seq.single rule)
   601     else
   602       let
   603         val rule' = Thm.incr_indexes (maxidx + 1) rule;
   604         val concl = Logic.strip_assums_concl goal;
   605       in
   606         Unify.smash_unifiers thy [(Thm.concl_of rule', concl)] (Envir.empty (Thm.maxidx_of rule'))
   607         |> Seq.map (fn env => Drule.instantiate_normalize (dest_env thy env) rule')
   608       end
   609   end
   610   handle General.Subscript => Seq.empty;
   611 
   612 end;
   613 
   614 
   615 (* special renaming of rule parameters *)
   616 
   617 fun special_rename_params ctxt [[SOME (Free (z, Type (T, _)))]] [thm] =
   618       let
   619         val x = Name.clean (Variable.revert_fixed ctxt z);
   620         fun index i [] = []
   621           | index i (y :: ys) =
   622               if x = y then x ^ string_of_int i :: index (i + 1) ys
   623               else y :: index i ys;
   624         fun rename_params [] = []
   625           | rename_params ((y, Type (U, _)) :: ys) =
   626               (if U = T then x else y) :: rename_params ys
   627           | rename_params ((y, _) :: ys) = y :: rename_params ys;
   628         fun rename_asm A =
   629           let
   630             val xs = rename_params (Logic.strip_params A);
   631             val xs' =
   632               (case filter (fn x' => x' = x) xs of
   633                 [] => xs | [_] => xs | _ => index 1 xs);
   634           in Logic.list_rename_params xs' A end;
   635         fun rename_prop p =
   636           let val (As, C) = Logic.strip_horn p
   637           in Logic.list_implies (map rename_asm As, C) end;
   638         val cp' = cterm_fun rename_prop (Thm.cprop_of thm);
   639         val thm' = Thm.equal_elim (Thm.reflexive cp') thm;
   640       in [Rule_Cases.save thm thm'] end
   641   | special_rename_params _ _ ths = ths;
   642 
   643 
   644 (* arbitrary_tac *)
   645 
   646 local
   647 
   648 fun goal_prefix k ((c as Const ("all", _)) $ Abs (a, T, B)) = c $ Abs (a, T, goal_prefix k B)
   649   | goal_prefix 0 _ = Term.dummy_prop
   650   | goal_prefix k ((c as Const ("==>", _)) $ A $ B) = c $ A $ goal_prefix (k - 1) B
   651   | goal_prefix _ _ = Term.dummy_prop;
   652 
   653 fun goal_params k (Const ("all", _) $ Abs (_, _, B)) = goal_params k B + 1
   654   | goal_params 0 _ = 0
   655   | goal_params k (Const ("==>", _) $ _ $ B) = goal_params (k - 1) B
   656   | goal_params _ _ = 0;
   657 
   658 fun meta_spec_tac ctxt n (x, T) = SUBGOAL (fn (goal, i) =>
   659   let
   660     val thy = Proof_Context.theory_of ctxt;
   661     val cert = Thm.cterm_of thy;
   662 
   663     val v = Free (x, T);
   664     fun spec_rule prfx (xs, body) =
   665       @{thm Pure.meta_spec}
   666       |> Thm.rename_params_rule ([Name.clean (Variable.revert_fixed ctxt x)], 1)
   667       |> Thm.lift_rule (cert prfx)
   668       |> `(Thm.prop_of #> Logic.strip_assums_concl)
   669       |-> (fn pred $ arg =>
   670         Drule.cterm_instantiate
   671           [(cert (Term.head_of pred), cert (Logic.rlist_abs (xs, body))),
   672            (cert (Term.head_of arg), cert (Logic.rlist_abs (xs, v)))]);
   673 
   674     fun goal_concl k xs (Const ("all", _) $ Abs (a, T, B)) = goal_concl k ((a, T) :: xs) B
   675       | goal_concl 0 xs B =
   676           if not (Term.exists_subterm (fn t => t aconv v) B) then NONE
   677           else SOME (xs, absfree (x, T) (Term.incr_boundvars 1 B))
   678       | goal_concl k xs (Const ("==>", _) $ _ $ B) = goal_concl (k - 1) xs B
   679       | goal_concl _ _ _ = NONE;
   680   in
   681     (case goal_concl n [] goal of
   682       SOME concl =>
   683         (compose_tac (false, spec_rule (goal_prefix n goal) concl, 1) THEN' rtac asm_rl) i
   684     | NONE => all_tac)
   685   end);
   686 
   687 fun miniscope_tac p = CONVERSION o
   688   Conv.params_conv p (K (Raw_Simplifier.rewrite true [Thm.symmetric Drule.norm_hhf_eq]));
   689 
   690 in
   691 
   692 fun arbitrary_tac _ _ [] = K all_tac
   693   | arbitrary_tac ctxt n xs = SUBGOAL (fn (goal, i) =>
   694      (EVERY' (map (meta_spec_tac ctxt n) xs) THEN'
   695       (miniscope_tac (goal_params n goal) ctxt)) i);
   696 
   697 end;
   698 
   699 
   700 (* add_defs *)
   701 
   702 fun add_defs def_insts =
   703   let
   704     fun add (SOME (_, (t, true))) ctxt = ((SOME t, []), ctxt)
   705       | add (SOME (SOME x, (t, _))) ctxt =
   706           let val ([(lhs, (_, th))], ctxt') =
   707             Local_Defs.add_defs [((x, NoSyn), ((Thm.def_binding x, []), t))] ctxt
   708           in ((SOME lhs, [th]), ctxt') end
   709       | add (SOME (NONE, (t as Free _, _))) ctxt = ((SOME t, []), ctxt)
   710       | add (SOME (NONE, (t, _))) ctxt =
   711           let
   712             val (s, _) = Name.variant "x" (Variable.names_of ctxt);
   713             val x = Binding.name s;
   714             val ([(lhs, (_, th))], ctxt') = ctxt
   715               |> Local_Defs.add_defs [((x, NoSyn), ((Thm.def_binding x, []), t))];
   716           in ((SOME lhs, [th]), ctxt') end
   717       | add NONE ctxt = ((NONE, []), ctxt);
   718   in fold_map add def_insts #> apfst (split_list #> apsnd flat) end;
   719 
   720 
   721 (* induct_tac *)
   722 
   723 (*
   724   rule selection scheme:
   725     `A x` induct ...     - predicate/set induction
   726           induct x       - type induction
   727     ...   induct ... r   - explicit rule
   728 *)
   729 
   730 fun get_inductT ctxt insts =
   731   fold_rev (map_product cons) (insts |> map
   732       ((fn [] => NONE | ts => List.last ts) #>
   733         (fn NONE => TVar (("'a", 0), []) | SOME t => Term.fastype_of t) #>
   734         find_inductT ctxt)) [[]]
   735   |> filter_out (forall Rule_Cases.is_inner_rule);
   736 
   737 fun get_inductP ctxt (fact :: _) = map single (find_inductP ctxt (Thm.concl_of fact))
   738   | get_inductP _ _ = [];
   739 
   740 type case_data = (((string * string list) * string list) list * int);
   741 
   742 fun gen_induct_tac mod_cases ctxt simp def_insts arbitrary taking opt_rule facts =
   743   let
   744     val thy = Proof_Context.theory_of ctxt;
   745 
   746     val ((insts, defs), defs_ctxt) = fold_map add_defs def_insts ctxt |>> split_list;
   747     val atomized_defs = map (map (Conv.fconv_rule atomize_cterm)) defs;
   748 
   749     fun inst_rule (concls, r) =
   750       (if null insts then `Rule_Cases.get r
   751        else (align_left "Rule has fewer conclusions than arguments given"
   752           (map Logic.strip_imp_concl (Logic.dest_conjunctions (Thm.concl_of r))) insts
   753         |> maps (prep_inst ctxt align_right (atomize_term thy))
   754         |> Drule.cterm_instantiate) r |> pair (Rule_Cases.get r))
   755       |> mod_cases thy
   756       |> (fn ((cases, consumes), th) => (((cases, concls), consumes), th));
   757 
   758     val ruleq =
   759       (case opt_rule of
   760         SOME rs => Seq.single (inst_rule (Rule_Cases.strict_mutual_rule ctxt rs))
   761       | NONE =>
   762           (get_inductP ctxt facts @
   763             map (special_rename_params defs_ctxt insts) (get_inductT ctxt insts))
   764           |> map_filter (Rule_Cases.mutual_rule ctxt)
   765           |> tap (trace_rules ctxt inductN o map #2)
   766           |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
   767 
   768     fun rule_cases ctxt rule cases =
   769       let
   770         val rule' = Rule_Cases.internalize_params rule;
   771         val rule'' = rule' |> simp ? simplified_rule ctxt;
   772         val nonames = map (fn ((cn, _), cls) => ((cn, []), cls));
   773         val cases' = if Thm.eq_thm_prop (rule', rule'') then cases else nonames cases;
   774       in Rule_Cases.make_nested (Thm.prop_of rule'') (rulified_term rule'') cases' end;
   775   in
   776     (fn i => fn st =>
   777       ruleq
   778       |> Seq.maps (Rule_Cases.consume (flat defs) facts)
   779       |> Seq.maps (fn (((cases, concls), (more_consumes, more_facts)), rule) =>
   780         (PRECISE_CONJUNCTS (length concls) (ALLGOALS (fn j =>
   781           (CONJUNCTS (ALLGOALS
   782             let
   783               val adefs = nth_list atomized_defs (j - 1);
   784               val frees = fold (Term.add_frees o Thm.prop_of) adefs [];
   785               val xs = nth_list arbitrary (j - 1);
   786               val k = nth concls (j - 1) + more_consumes
   787             in
   788               Method.insert_tac (more_facts @ adefs) THEN'
   789                 (if simp then
   790                    rotate_tac k (length adefs) THEN'
   791                    arbitrary_tac defs_ctxt k (List.partition (member op = frees) xs |> op @)
   792                  else
   793                    arbitrary_tac defs_ctxt k xs)
   794              end)
   795           THEN' inner_atomize_tac) j))
   796         THEN' atomize_tac) i st |> Seq.maps (fn st' =>
   797             guess_instance ctxt (internalize more_consumes rule) i st'
   798             |> Seq.map (rule_instance ctxt (burrow_options (Variable.polymorphic ctxt) taking))
   799             |> Seq.maps (fn rule' =>
   800               CASES (rule_cases ctxt rule' cases)
   801                 (rtac rule' i THEN
   802                   PRIMITIVE (singleton (Proof_Context.export defs_ctxt ctxt))) st'))))
   803     THEN_ALL_NEW_CASES
   804       ((if simp then simplify_tac ctxt THEN' (TRY o trivial_tac)
   805         else K all_tac)
   806        THEN_ALL_NEW rulify_tac)
   807   end;
   808 
   809 val induct_tac = gen_induct_tac (K I);
   810 
   811 
   812 
   813 (** coinduct method **)
   814 
   815 (*
   816   rule selection scheme:
   817     goal "A x" coinduct ...   - predicate/set coinduction
   818                coinduct x     - type coinduction
   819                coinduct ... r - explicit rule
   820 *)
   821 
   822 local
   823 
   824 fun get_coinductT ctxt (SOME t :: _) = find_coinductT ctxt (Term.fastype_of t)
   825   | get_coinductT _ _ = [];
   826 
   827 fun get_coinductP ctxt goal = find_coinductP ctxt (Logic.strip_assums_concl goal);
   828 
   829 fun main_prop_of th =
   830   if Rule_Cases.get_consumes th > 0 then Thm.major_prem_of th else Thm.concl_of th;
   831 
   832 in
   833 
   834 fun coinduct_tac ctxt inst taking opt_rule facts =
   835   let
   836     val thy = Proof_Context.theory_of ctxt;
   837 
   838     fun inst_rule r =
   839       if null inst then `Rule_Cases.get r
   840       else Drule.cterm_instantiate (prep_inst ctxt align_right I (main_prop_of r, inst)) r
   841         |> pair (Rule_Cases.get r);
   842 
   843     fun ruleq goal =
   844       (case opt_rule of
   845         SOME r => Seq.single (inst_rule r)
   846       | NONE =>
   847           (get_coinductP ctxt goal @ get_coinductT ctxt inst)
   848           |> tap (trace_rules ctxt coinductN)
   849           |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
   850   in
   851     SUBGOAL_CASES (fn (goal, i) => fn st =>
   852       ruleq goal
   853       |> Seq.maps (Rule_Cases.consume [] facts)
   854       |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
   855         guess_instance ctxt rule i st
   856         |> Seq.map (rule_instance ctxt (burrow_options (Variable.polymorphic ctxt) taking))
   857         |> Seq.maps (fn rule' =>
   858           CASES (Rule_Cases.make_common (thy,
   859               Thm.prop_of (Rule_Cases.internalize_params rule')) cases)
   860             (Method.insert_tac more_facts i THEN rtac rule' i) st)))
   861   end;
   862 
   863 end;
   864 
   865 
   866 
   867 (** concrete syntax **)
   868 
   869 val arbitraryN = "arbitrary";
   870 val takingN = "taking";
   871 val ruleN = "rule";
   872 
   873 local
   874 
   875 fun single_rule [rule] = rule
   876   | single_rule _ = error "Single rule expected";
   877 
   878 fun named_rule k arg get =
   879   Scan.lift (Args.$$$ k -- Args.colon) |-- Scan.repeat arg :|--
   880     (fn names => Scan.peek (fn context => Scan.succeed (names |> map (fn name =>
   881       (case get (Context.proof_of context) name of SOME x => x
   882       | NONE => error ("No rule for " ^ k ^ " " ^ quote name))))));
   883 
   884 fun rule get_type get_pred =
   885   named_rule typeN (Args.type_name false) get_type ||
   886   named_rule predN (Args.const false) get_pred ||
   887   named_rule setN (Args.const false) get_pred ||
   888   Scan.lift (Args.$$$ ruleN -- Args.colon) |-- Attrib.thms;
   889 
   890 val cases_rule = rule lookup_casesT lookup_casesP >> single_rule;
   891 val induct_rule = rule lookup_inductT lookup_inductP;
   892 val coinduct_rule = rule lookup_coinductT lookup_coinductP >> single_rule;
   893 
   894 val inst = Scan.lift (Args.$$$ "_") >> K NONE || Args.term >> SOME;
   895 
   896 val inst' = Scan.lift (Args.$$$ "_") >> K NONE ||
   897   Args.term >> (SOME o rpair false) ||
   898   Scan.lift (Args.$$$ "(") |-- (Args.term >> (SOME o rpair true)) --|
   899     Scan.lift (Args.$$$ ")");
   900 
   901 val def_inst =
   902   ((Scan.lift (Args.binding --| (Args.$$$ "\<equiv>" || Args.$$$ "==")) >> SOME)
   903       -- (Args.term >> rpair false)) >> SOME ||
   904     inst' >> Option.map (pair NONE);
   905 
   906 val free = Args.context -- Args.term >> (fn (_, Free v) => v | (ctxt, t) =>
   907   error ("Bad free variable: " ^ Syntax.string_of_term ctxt t));
   908 
   909 fun unless_more_args scan = Scan.unless (Scan.lift
   910   ((Args.$$$ arbitraryN || Args.$$$ takingN || Args.$$$ typeN ||
   911     Args.$$$ predN || Args.$$$ setN || Args.$$$ ruleN) -- Args.colon)) scan;
   912 
   913 val arbitrary = Scan.optional (Scan.lift (Args.$$$ arbitraryN -- Args.colon) |--
   914   Parse.and_list1' (Scan.repeat (unless_more_args free))) [];
   915 
   916 val taking = Scan.optional (Scan.lift (Args.$$$ takingN -- Args.colon) |--
   917   Scan.repeat1 (unless_more_args inst)) [];
   918 
   919 in
   920 
   921 val cases_setup =
   922   Method.setup @{binding cases}
   923     (Args.mode no_simpN --
   924       (Parse.and_list' (Scan.repeat (unless_more_args inst)) -- Scan.option cases_rule) >>
   925       (fn (no_simp, (insts, opt_rule)) => fn ctxt =>
   926         METHOD_CASES (fn facts => Seq.DETERM (HEADGOAL
   927           (cases_tac ctxt (not no_simp) insts opt_rule facts)))))
   928     "case analysis on types or predicates/sets";
   929 
   930 fun gen_induct_setup binding itac =
   931   Method.setup binding
   932     (Args.mode no_simpN -- (Parse.and_list' (Scan.repeat (unless_more_args def_inst)) --
   933       (arbitrary -- taking -- Scan.option induct_rule)) >>
   934       (fn (no_simp, (insts, ((arbitrary, taking), opt_rule))) => fn ctxt =>
   935         RAW_METHOD_CASES (fn facts =>
   936           Seq.DETERM
   937             (HEADGOAL (itac ctxt (not no_simp) insts arbitrary taking opt_rule facts)))))
   938     "induction on types or predicates/sets";
   939 
   940 val induct_setup = gen_induct_setup @{binding induct} induct_tac;
   941 
   942 val coinduct_setup =
   943   Method.setup @{binding coinduct}
   944     (Scan.repeat (unless_more_args inst) -- taking -- Scan.option coinduct_rule >>
   945       (fn ((insts, taking), opt_rule) => fn ctxt =>
   946         RAW_METHOD_CASES (fn facts =>
   947           Seq.DETERM (HEADGOAL (coinduct_tac ctxt insts taking opt_rule facts)))))
   948     "coinduction on types or predicates/sets";
   949 
   950 end;
   951 
   952 
   953 
   954 (** theory setup **)
   955 
   956 val setup = attrib_setup #> cases_setup  #> induct_setup #> coinduct_setup;
   957 
   958 end;