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