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