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