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