src/Tools/induct.ML
author wenzelm
Tue Mar 17 14:12:43 2009 +0100 (2009-03-17)
changeset 30560 0cc3b7f03ade
parent 30528 7173bf123335
child 30722 623d4831c8cf
permissions -rw-r--r--
adapted to general Item_Net;
     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 end;
    14 
    15 signature INDUCT =
    16 sig
    17   (*rule declarations*)
    18   val vars_of: term -> term list
    19   val dest_rules: Proof.context ->
    20     {type_cases: (string * thm) list, pred_cases: (string * thm) list,
    21       type_induct: (string * thm) list, pred_induct: (string * thm) list,
    22       type_coinduct: (string * thm) list, pred_coinduct: (string * thm) list}
    23   val print_rules: Proof.context -> unit
    24   val lookup_casesT: Proof.context -> string -> thm option
    25   val lookup_casesP: Proof.context -> string -> thm option
    26   val lookup_inductT: Proof.context -> string -> thm option
    27   val lookup_inductP: Proof.context -> string -> thm option
    28   val lookup_coinductT: Proof.context -> string -> thm option
    29   val lookup_coinductP: Proof.context -> string -> thm option
    30   val find_casesT: Proof.context -> typ -> thm list
    31   val find_casesP: Proof.context -> term -> thm list
    32   val find_inductT: Proof.context -> typ -> thm list
    33   val find_inductP: Proof.context -> term -> thm list
    34   val find_coinductT: Proof.context -> typ -> thm list
    35   val find_coinductP: Proof.context -> term -> thm list
    36   val cases_type: string -> attribute
    37   val cases_pred: string -> attribute
    38   val cases_del: attribute
    39   val induct_type: string -> attribute
    40   val induct_pred: string -> attribute
    41   val induct_del: attribute
    42   val coinduct_type: string -> attribute
    43   val coinduct_pred: string -> attribute
    44   val coinduct_del: attribute
    45   val casesN: string
    46   val inductN: string
    47   val coinductN: string
    48   val typeN: string
    49   val predN: string
    50   val setN: string
    51   (*proof methods*)
    52   val fix_tac: Proof.context -> int -> (string * typ) list -> int -> tactic
    53   val add_defs: (binding option * term) option list -> Proof.context ->
    54     (term option list * thm list) * Proof.context
    55   val atomize_term: theory -> term -> term
    56   val atomize_tac: int -> tactic
    57   val inner_atomize_tac: int -> tactic
    58   val rulified_term: thm -> theory * term
    59   val rulify_tac: int -> tactic
    60   val internalize: int -> thm -> thm
    61   val guess_instance: Proof.context -> thm -> int -> thm -> thm Seq.seq
    62   val cases_tac: Proof.context -> term option list list -> thm option ->
    63     thm list -> int -> cases_tactic
    64   val get_inductT: Proof.context -> term option list list -> thm list list
    65   val induct_tac: Proof.context -> (binding option * term) option list list ->
    66     (string * typ) list list -> term option list -> thm list option ->
    67     thm list -> int -> cases_tactic
    68   val coinduct_tac: Proof.context -> term option list -> term option list -> thm option ->
    69     thm list -> int -> cases_tactic
    70   val setup: theory -> theory
    71 end;
    72 
    73 functor InductFun(Data: INDUCT_DATA): INDUCT =
    74 struct
    75 
    76 
    77 (** misc utils **)
    78 
    79 (* encode_type -- for indexing purposes *)
    80 
    81 fun encode_type (Type (c, Ts)) = Term.list_comb (Const (c, dummyT), map encode_type Ts)
    82   | encode_type (TFree (a, _)) = Free (a, dummyT)
    83   | encode_type (TVar (a, _)) = Var (a, dummyT);
    84 
    85 
    86 (* variables -- ordered left-to-right, preferring right *)
    87 
    88 fun vars_of tm =
    89   rev (distinct (op =) (Term.fold_aterms (fn (t as Var _) => cons t | _ => I) tm []));
    90 
    91 local
    92 
    93 val mk_var = encode_type o #2 o Term.dest_Var;
    94 
    95 fun concl_var which thm = mk_var (which (vars_of (Thm.concl_of thm))) handle Empty =>
    96   raise THM ("No variables in conclusion of rule", 0, [thm]);
    97 
    98 in
    99 
   100 fun left_var_prem thm = mk_var (hd (vars_of (hd (Thm.prems_of thm)))) handle Empty =>
   101   raise THM ("No variables in major premise of rule", 0, [thm]);
   102 
   103 val left_var_concl = concl_var hd;
   104 val right_var_concl = concl_var List.last;
   105 
   106 end;
   107 
   108 
   109 
   110 (** induct data **)
   111 
   112 (* rules *)
   113 
   114 type rules = (string * thm) Item_Net.T;
   115 
   116 val init_rules =
   117   Item_Net.init (fn ((s1: string, th1), (s2, th2)) => s1 = s2 andalso
   118     Thm.eq_thm_prop (th1, th2));
   119 
   120 fun filter_rules (rs: rules) th =
   121   filter (fn (_, th') => Thm.eq_thm_prop (th, th')) (Item_Net.content rs);
   122 
   123 fun lookup_rule (rs: rules) = AList.lookup (op =) (Item_Net.content rs);
   124 
   125 fun pretty_rules ctxt kind rs =
   126   let val thms = map snd (Item_Net.content rs)
   127   in Pretty.big_list kind (map (ProofContext.pretty_thm ctxt) thms) end;
   128 
   129 
   130 (* context data *)
   131 
   132 structure InductData = GenericDataFun
   133 (
   134   type T = (rules * rules) * (rules * rules) * (rules * rules);
   135   val empty =
   136     ((init_rules (left_var_prem o #2), init_rules (Thm.major_prem_of o #2)),
   137      (init_rules (right_var_concl o #2), init_rules (Thm.major_prem_of o #2)),
   138      (init_rules (left_var_concl o #2), init_rules (Thm.concl_of o #2)));
   139   val extend = I;
   140   fun merge _ (((casesT1, casesP1), (inductT1, inductP1), (coinductT1, coinductP1)),
   141       ((casesT2, casesP2), (inductT2, inductP2), (coinductT2, coinductP2))) =
   142     ((Item_Net.merge (casesT1, casesT2), Item_Net.merge (casesP1, casesP2)),
   143       (Item_Net.merge (inductT1, inductT2), Item_Net.merge (inductP1, inductP2)),
   144       (Item_Net.merge (coinductT1, coinductT2), Item_Net.merge (coinductP1, coinductP2)));
   145 );
   146 
   147 val get_local = InductData.get o Context.Proof;
   148 
   149 fun dest_rules ctxt =
   150   let val ((casesT, casesP), (inductT, inductP), (coinductT, coinductP)) = get_local ctxt in
   151     {type_cases = Item_Net.content casesT,
   152      pred_cases = Item_Net.content casesP,
   153      type_induct = Item_Net.content inductT,
   154      pred_induct = Item_Net.content inductP,
   155      type_coinduct = Item_Net.content coinductT,
   156      pred_coinduct = Item_Net.content coinductP}
   157   end;
   158 
   159 fun print_rules ctxt =
   160   let val ((casesT, casesP), (inductT, inductP), (coinductT, coinductP)) = get_local ctxt in
   161    [pretty_rules ctxt "coinduct type:" coinductT,
   162     pretty_rules ctxt "coinduct pred:" coinductP,
   163     pretty_rules ctxt "induct type:" inductT,
   164     pretty_rules ctxt "induct pred:" inductP,
   165     pretty_rules ctxt "cases type:" casesT,
   166     pretty_rules ctxt "cases pred:" casesP]
   167     |> Pretty.chunks |> Pretty.writeln
   168   end;
   169 
   170 val _ =
   171   OuterSyntax.improper_command "print_induct_rules" "print induction and cases rules"
   172     OuterKeyword.diag (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_context o
   173       Toplevel.keep (print_rules o Toplevel.context_of)));
   174 
   175 
   176 (* access rules *)
   177 
   178 val lookup_casesT = lookup_rule o #1 o #1 o get_local;
   179 val lookup_casesP = lookup_rule o #2 o #1 o get_local;
   180 val lookup_inductT = lookup_rule o #1 o #2 o get_local;
   181 val lookup_inductP = lookup_rule o #2 o #2 o get_local;
   182 val lookup_coinductT = lookup_rule o #1 o #3 o get_local;
   183 val lookup_coinductP = lookup_rule o #2 o #3 o get_local;
   184 
   185 
   186 fun find_rules which how ctxt x =
   187   map snd (Item_Net.retrieve (which (get_local ctxt)) (how x));
   188 
   189 val find_casesT = find_rules (#1 o #1) encode_type;
   190 val find_casesP = find_rules (#2 o #1) I;
   191 val find_inductT = find_rules (#1 o #2) encode_type;
   192 val find_inductP = find_rules (#2 o #2) I;
   193 val find_coinductT = find_rules (#1 o #3) encode_type;
   194 val find_coinductP = find_rules (#2 o #3) I;
   195 
   196 
   197 
   198 (** attributes **)
   199 
   200 local
   201 
   202 fun mk_att f g name arg =
   203   let val (x, thm) = g arg in (InductData.map (f (name, thm)) x, thm) end;
   204 
   205 fun del_att which = Thm.declaration_attribute (fn th => InductData.map (which (pairself (fn rs =>
   206   fold Item_Net.delete (filter_rules rs th) rs))));
   207 
   208 fun map1 f (x, y, z) = (f x, y, z);
   209 fun map2 f (x, y, z) = (x, f y, z);
   210 fun map3 f (x, y, z) = (x, y, f z);
   211 
   212 fun add_casesT rule x = map1 (apfst (Item_Net.insert rule)) x;
   213 fun add_casesP rule x = map1 (apsnd (Item_Net.insert rule)) x;
   214 fun add_inductT rule x = map2 (apfst (Item_Net.insert rule)) x;
   215 fun add_inductP rule x = map2 (apsnd (Item_Net.insert rule)) x;
   216 fun add_coinductT rule x = map3 (apfst (Item_Net.insert rule)) x;
   217 fun add_coinductP rule x = map3 (apsnd (Item_Net.insert rule)) x;
   218 
   219 val consumes0 = RuleCases.consumes_default 0;
   220 val consumes1 = RuleCases.consumes_default 1;
   221 
   222 in
   223 
   224 val cases_type = mk_att add_casesT consumes0;
   225 val cases_pred = mk_att add_casesP consumes1;
   226 val cases_del = del_att map1;
   227 
   228 val induct_type = mk_att add_inductT consumes0;
   229 val induct_pred = mk_att add_inductP consumes1;
   230 val induct_del = del_att map2;
   231 
   232 val coinduct_type = mk_att add_coinductT consumes0;
   233 val coinduct_pred = mk_att add_coinductP consumes1;
   234 val coinduct_del = del_att map3;
   235 
   236 end;
   237 
   238 
   239 
   240 (** attribute syntax **)
   241 
   242 val casesN = "cases";
   243 val inductN = "induct";
   244 val coinductN = "coinduct";
   245 
   246 val typeN = "type";
   247 val predN = "pred";
   248 val setN = "set";
   249 
   250 local
   251 
   252 fun spec k arg =
   253   Scan.lift (Args.$$$ k -- Args.colon) |-- arg ||
   254   Scan.lift (Args.$$$ k) >> K "";
   255 
   256 fun attrib add_type add_pred del =
   257   spec typeN Args.tyname >> add_type ||
   258   spec predN Args.const >> add_pred ||
   259   spec setN Args.const >> add_pred ||
   260   Scan.lift Args.del >> K del;
   261 
   262 val cases_att = attrib cases_type cases_pred cases_del;
   263 val induct_att = attrib induct_type induct_pred induct_del;
   264 val coinduct_att = attrib coinduct_type coinduct_pred coinduct_del;
   265 
   266 in
   267 
   268 val attrib_setup =
   269   Attrib.setup @{binding cases} cases_att "declaration of cases rule" #>
   270   Attrib.setup @{binding induct} induct_att "declaration of induction rule" #>
   271   Attrib.setup @{binding coinduct} coinduct_att "declaration of coinduction rule";
   272 
   273 end;
   274 
   275 
   276 
   277 (** method utils **)
   278 
   279 (* alignment *)
   280 
   281 fun align_left msg xs ys =
   282   let val m = length xs and n = length ys
   283   in if m < n then error msg else (Library.take (n, xs) ~~ ys) end;
   284 
   285 fun align_right msg xs ys =
   286   let val m = length xs and n = length ys
   287   in if m < n then error msg else (Library.drop (m - n, xs) ~~ ys) end;
   288 
   289 
   290 (* prep_inst *)
   291 
   292 fun prep_inst thy align tune (tm, ts) =
   293   let
   294     val cert = Thm.cterm_of thy;
   295     fun prep_var (x, SOME t) =
   296           let
   297             val cx = cert x;
   298             val xT = #T (Thm.rep_cterm cx);
   299             val ct = cert (tune t);
   300             val tT = Thm.ctyp_of_term ct;
   301           in
   302             if Type.could_unify (Thm.typ_of tT, xT) then SOME (cx, ct)
   303             else error (Pretty.string_of (Pretty.block
   304              [Pretty.str "Ill-typed instantiation:", Pretty.fbrk,
   305               Display.pretty_cterm ct, Pretty.str " ::", Pretty.brk 1,
   306               Display.pretty_ctyp (#T (Thm.crep_cterm ct))]))
   307           end
   308       | prep_var (_, NONE) = NONE;
   309     val xs = vars_of tm;
   310   in
   311     align "Rule has fewer variables than instantiations given" xs ts
   312     |> map_filter prep_var
   313   end;
   314 
   315 
   316 (* trace_rules *)
   317 
   318 fun trace_rules _ kind [] = error ("Unable to figure out " ^ kind ^ " rule")
   319   | trace_rules ctxt _ rules = Method.trace ctxt rules;
   320 
   321 
   322 
   323 (** cases method **)
   324 
   325 (*
   326   rule selection scheme:
   327           cases         - default case split
   328     `A t` cases ...     - predicate/set cases
   329           cases t       - type cases
   330     ...   cases ... r   - explicit rule
   331 *)
   332 
   333 local
   334 
   335 fun get_casesT ctxt ((SOME t :: _) :: _) = find_casesT ctxt (Term.fastype_of t)
   336   | get_casesT _ _ = [];
   337 
   338 fun get_casesP ctxt (fact :: _) = find_casesP ctxt (Thm.concl_of fact)
   339   | get_casesP _ _ = [];
   340 
   341 in
   342 
   343 fun cases_tac ctxt insts opt_rule facts =
   344   let
   345     val thy = ProofContext.theory_of ctxt;
   346     val cert = Thm.cterm_of thy;
   347 
   348     fun inst_rule r =
   349       if null insts then `RuleCases.get r
   350       else (align_left "Rule has fewer premises than arguments given" (Thm.prems_of r) insts
   351         |> maps (prep_inst thy align_left I)
   352         |> Drule.cterm_instantiate) r |> pair (RuleCases.get r);
   353 
   354     val ruleq =
   355       (case opt_rule of
   356         SOME r => Seq.single (inst_rule r)
   357       | NONE =>
   358           (get_casesP ctxt facts @ get_casesT ctxt insts @ [Data.cases_default])
   359           |> tap (trace_rules ctxt casesN)
   360           |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
   361   in
   362     fn i => fn st =>
   363       ruleq
   364       |> Seq.maps (RuleCases.consume [] facts)
   365       |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
   366         CASES (RuleCases.make_common false (thy, Thm.prop_of rule) cases)
   367           (Method.insert_tac more_facts i THEN Tactic.rtac rule i) st)
   368   end;
   369 
   370 end;
   371 
   372 
   373 
   374 (** induct method **)
   375 
   376 val conjunction_congs = [@{thm Pure.all_conjunction}, @{thm imp_conjunction}];
   377 
   378 
   379 (* atomize *)
   380 
   381 fun atomize_term thy =
   382   MetaSimplifier.rewrite_term thy Data.atomize []
   383   #> ObjectLogic.drop_judgment thy;
   384 
   385 val atomize_cterm = MetaSimplifier.rewrite true Data.atomize;
   386 
   387 val atomize_tac = Simplifier.rewrite_goal_tac Data.atomize;
   388 
   389 val inner_atomize_tac =
   390   Simplifier.rewrite_goal_tac (map Thm.symmetric conjunction_congs) THEN' atomize_tac;
   391 
   392 
   393 (* rulify *)
   394 
   395 fun rulify_term thy =
   396   MetaSimplifier.rewrite_term thy (Data.rulify @ conjunction_congs) [] #>
   397   MetaSimplifier.rewrite_term thy Data.rulify_fallback [];
   398 
   399 fun rulified_term thm =
   400   let
   401     val thy = Thm.theory_of_thm thm;
   402     val rulify = rulify_term thy;
   403     val (As, B) = Logic.strip_horn (Thm.prop_of thm);
   404   in (thy, Logic.list_implies (map rulify As, rulify B)) end;
   405 
   406 val rulify_tac =
   407   Simplifier.rewrite_goal_tac (Data.rulify @ conjunction_congs) THEN'
   408   Simplifier.rewrite_goal_tac Data.rulify_fallback THEN'
   409   Goal.conjunction_tac THEN_ALL_NEW
   410   (Simplifier.rewrite_goal_tac [@{thm Pure.conjunction_imp}] THEN' Goal.norm_hhf_tac);
   411 
   412 
   413 (* prepare rule *)
   414 
   415 fun rule_instance thy inst rule =
   416   Drule.cterm_instantiate (prep_inst thy align_left I (Thm.prop_of rule, inst)) rule;
   417 
   418 fun internalize k th =
   419   th |> Thm.permute_prems 0 k
   420   |> Conv.fconv_rule (Conv.concl_conv (Thm.nprems_of th - k) atomize_cterm);
   421 
   422 
   423 (* guess rule instantiation -- cannot handle pending goal parameters *)
   424 
   425 local
   426 
   427 fun dest_env thy (env as Envir.Envir {iTs, ...}) =
   428   let
   429     val cert = Thm.cterm_of thy;
   430     val certT = Thm.ctyp_of thy;
   431     val pairs = Envir.alist_of env;
   432     val ts = map (cert o Envir.norm_term env o #2 o #2) pairs;
   433     val xs = map2 (curry (cert o Var)) (map #1 pairs) (map (#T o Thm.rep_cterm) ts);
   434   in (map (fn (xi, (S, T)) => (certT (TVar (xi, S)), certT T)) (Vartab.dest iTs), xs ~~ ts) end;
   435 
   436 in
   437 
   438 fun guess_instance ctxt rule i st =
   439   let
   440     val thy = ProofContext.theory_of ctxt;
   441     val maxidx = Thm.maxidx_of st;
   442     val goal = Thm.term_of (Thm.cprem_of st i);  (*exception Subscript*)
   443     val params = rev (Term.rename_wrt_term goal (Logic.strip_params goal));
   444   in
   445     if not (null params) then
   446       (warning ("Cannot determine rule instantiation due to pending parameter(s): " ^
   447         commas_quote (map (Syntax.string_of_term ctxt o Syntax.mark_boundT) params));
   448       Seq.single rule)
   449     else
   450       let
   451         val rule' = Thm.incr_indexes (maxidx + 1) rule;
   452         val concl = Logic.strip_assums_concl goal;
   453       in
   454         Unify.smash_unifiers thy [(Thm.concl_of rule', concl)]
   455           (Envir.empty (#maxidx (Thm.rep_thm rule')))
   456         |> Seq.map (fn env => Drule.instantiate (dest_env thy env) rule')
   457       end
   458   end handle Subscript => Seq.empty;
   459 
   460 end;
   461 
   462 
   463 (* special renaming of rule parameters *)
   464 
   465 fun special_rename_params ctxt [[SOME (Free (z, Type (T, _)))]] [thm] =
   466       let
   467         val x = Name.clean (ProofContext.revert_skolem ctxt z);
   468         fun index i [] = []
   469           | index i (y :: ys) =
   470               if x = y then x ^ string_of_int i :: index (i + 1) ys
   471               else y :: index i ys;
   472         fun rename_params [] = []
   473           | rename_params ((y, Type (U, _)) :: ys) =
   474               (if U = T then x else y) :: rename_params ys
   475           | rename_params ((y, _) :: ys) = y :: rename_params ys;
   476         fun rename_asm A =
   477           let
   478             val xs = rename_params (Logic.strip_params A);
   479             val xs' =
   480               (case filter (fn x' => x' = x) xs of
   481                 [] => xs | [_] => xs | _ => index 1 xs);
   482           in Logic.list_rename_params (xs', A) end;
   483         fun rename_prop p =
   484           let val (As, C) = Logic.strip_horn p
   485           in Logic.list_implies (map rename_asm As, C) end;
   486         val cp' = cterm_fun rename_prop (Thm.cprop_of thm);
   487         val thm' = Thm.equal_elim (Thm.reflexive cp') thm;
   488       in [RuleCases.save thm thm'] end
   489   | special_rename_params _ _ ths = ths;
   490 
   491 
   492 (* fix_tac *)
   493 
   494 local
   495 
   496 fun goal_prefix k ((c as Const ("all", _)) $ Abs (a, T, B)) = c $ Abs (a, T, goal_prefix k B)
   497   | goal_prefix 0 _ = Term.dummy_pattern propT
   498   | goal_prefix k ((c as Const ("==>", _)) $ A $ B) = c $ A $ goal_prefix (k - 1) B
   499   | goal_prefix _ _ = Term.dummy_pattern propT;
   500 
   501 fun goal_params k (Const ("all", _) $ Abs (_, _, B)) = goal_params k B + 1
   502   | goal_params 0 _ = 0
   503   | goal_params k (Const ("==>", _) $ _ $ B) = goal_params (k - 1) B
   504   | goal_params _ _ = 0;
   505 
   506 fun meta_spec_tac ctxt n (x, T) = SUBGOAL (fn (goal, i) =>
   507   let
   508     val thy = ProofContext.theory_of ctxt;
   509     val cert = Thm.cterm_of thy;
   510     val certT = Thm.ctyp_of thy;
   511 
   512     val v = Free (x, T);
   513     fun spec_rule prfx (xs, body) =
   514       @{thm Pure.meta_spec}
   515       |> Thm.rename_params_rule ([Name.clean (ProofContext.revert_skolem ctxt x)], 1)
   516       |> Thm.lift_rule (cert prfx)
   517       |> `(Thm.prop_of #> Logic.strip_assums_concl)
   518       |-> (fn pred $ arg =>
   519         Drule.cterm_instantiate
   520           [(cert (Term.head_of pred), cert (Logic.rlist_abs (xs, body))),
   521            (cert (Term.head_of arg), cert (Logic.rlist_abs (xs, v)))]);
   522 
   523     fun goal_concl k xs (Const ("all", _) $ Abs (a, T, B)) = goal_concl k ((a, T) :: xs) B
   524       | goal_concl 0 xs B =
   525           if not (Term.exists_subterm (fn t => t aconv v) B) then NONE
   526           else SOME (xs, Term.absfree (x, T, Term.incr_boundvars 1 B))
   527       | goal_concl k xs (Const ("==>", _) $ _ $ B) = goal_concl (k - 1) xs B
   528       | goal_concl _ _ _ = NONE;
   529   in
   530     (case goal_concl n [] goal of
   531       SOME concl =>
   532         (compose_tac (false, spec_rule (goal_prefix n goal) concl, 1) THEN' rtac asm_rl) i
   533     | NONE => all_tac)
   534   end);
   535 
   536 fun miniscope_tac p = CONVERSION o
   537   Conv.params_conv p (K (MetaSimplifier.rewrite true [Thm.symmetric Drule.norm_hhf_eq]));
   538 
   539 in
   540 
   541 fun fix_tac _ _ [] = K all_tac
   542   | fix_tac ctxt n xs = SUBGOAL (fn (goal, i) =>
   543      (EVERY' (map (meta_spec_tac ctxt n) xs) THEN'
   544       (miniscope_tac (goal_params n goal) ctxt)) i);
   545 
   546 end;
   547 
   548 
   549 (* add_defs *)
   550 
   551 fun add_defs def_insts =
   552   let
   553     fun add (SOME (SOME x, t)) ctxt =
   554           let val ([(lhs, (_, th))], ctxt') =
   555             LocalDefs.add_defs [((x, NoSyn), (Thm.empty_binding, t))] ctxt
   556           in ((SOME lhs, [th]), ctxt') end
   557       | add (SOME (NONE, t)) ctxt = ((SOME t, []), ctxt)
   558       | add NONE ctxt = ((NONE, []), ctxt);
   559   in fold_map add def_insts #> apfst (split_list #> apsnd flat) end;
   560 
   561 
   562 (* induct_tac *)
   563 
   564 (*
   565   rule selection scheme:
   566     `A x` induct ...     - predicate/set induction
   567           induct x       - type induction
   568     ...   induct ... r   - explicit rule
   569 *)
   570 
   571 fun get_inductT ctxt insts =
   572   fold_rev multiply (insts |> map
   573       ((fn [] => NONE | ts => List.last ts) #>
   574         (fn NONE => TVar (("'a", 0), []) | SOME t => Term.fastype_of t) #>
   575         find_inductT ctxt)) [[]]
   576   |> filter_out (forall Thm.is_internal);
   577 
   578 fun get_inductP ctxt (fact :: _) = map single (find_inductP ctxt (Thm.concl_of fact))
   579   | get_inductP _ _ = [];
   580 
   581 fun induct_tac ctxt def_insts arbitrary taking opt_rule facts =
   582   let
   583     val thy = ProofContext.theory_of ctxt;
   584     val cert = Thm.cterm_of thy;
   585 
   586     val ((insts, defs), defs_ctxt) = fold_map add_defs def_insts ctxt |>> split_list;
   587     val atomized_defs = map (map (Conv.fconv_rule ObjectLogic.atomize)) defs;
   588 
   589     fun inst_rule (concls, r) =
   590       (if null insts then `RuleCases.get r
   591        else (align_left "Rule has fewer conclusions than arguments given"
   592           (map Logic.strip_imp_concl (Logic.dest_conjunctions (Thm.concl_of r))) insts
   593         |> maps (prep_inst thy align_right (atomize_term thy))
   594         |> Drule.cterm_instantiate) r |> pair (RuleCases.get r))
   595       |> (fn ((cases, consumes), th) => (((cases, concls), consumes), th));
   596 
   597     val ruleq =
   598       (case opt_rule of
   599         SOME rs => Seq.single (inst_rule (RuleCases.strict_mutual_rule ctxt rs))
   600       | NONE =>
   601           (get_inductP ctxt facts @
   602             map (special_rename_params defs_ctxt insts) (get_inductT ctxt insts))
   603           |> map_filter (RuleCases.mutual_rule ctxt)
   604           |> tap (trace_rules ctxt inductN o map #2)
   605           |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
   606 
   607     fun rule_cases rule =
   608       RuleCases.make_nested false (Thm.prop_of rule) (rulified_term rule);
   609   in
   610     (fn i => fn st =>
   611       ruleq
   612       |> Seq.maps (RuleCases.consume (flat defs) facts)
   613       |> Seq.maps (fn (((cases, concls), (more_consumes, more_facts)), rule) =>
   614         (PRECISE_CONJUNCTS (length concls) (ALLGOALS (fn j =>
   615           (CONJUNCTS (ALLGOALS
   616             (Method.insert_tac (more_facts @ nth_list atomized_defs (j - 1))
   617               THEN' fix_tac defs_ctxt
   618                 (nth concls (j - 1) + more_consumes)
   619                 (nth_list arbitrary (j - 1))))
   620           THEN' inner_atomize_tac) j))
   621         THEN' atomize_tac) i st |> Seq.maps (fn st' =>
   622             guess_instance ctxt (internalize more_consumes rule) i st'
   623             |> Seq.map (rule_instance thy (burrow_options (Variable.polymorphic ctxt) taking))
   624             |> Seq.maps (fn rule' =>
   625               CASES (rule_cases rule' cases)
   626                 (Tactic.rtac rule' i THEN
   627                   PRIMITIVE (singleton (ProofContext.export defs_ctxt ctxt))) st'))))
   628     THEN_ALL_NEW_CASES rulify_tac
   629   end;
   630 
   631 
   632 
   633 (** coinduct method **)
   634 
   635 (*
   636   rule selection scheme:
   637     goal "A x" coinduct ...   - predicate/set coinduction
   638                coinduct x     - type coinduction
   639                coinduct ... r - explicit rule
   640 *)
   641 
   642 local
   643 
   644 fun get_coinductT ctxt (SOME t :: _) = find_coinductT ctxt (Term.fastype_of t)
   645   | get_coinductT _ _ = [];
   646 
   647 fun get_coinductP ctxt goal = find_coinductP ctxt (Logic.strip_assums_concl goal);
   648 
   649 fun main_prop_of th =
   650   if RuleCases.get_consumes th > 0 then Thm.major_prem_of th else Thm.concl_of th;
   651 
   652 in
   653 
   654 fun coinduct_tac ctxt inst taking opt_rule facts =
   655   let
   656     val thy = ProofContext.theory_of ctxt;
   657     val cert = Thm.cterm_of thy;
   658 
   659     fun inst_rule r =
   660       if null inst then `RuleCases.get r
   661       else Drule.cterm_instantiate (prep_inst thy align_right I (main_prop_of r, inst)) r
   662         |> pair (RuleCases.get r);
   663 
   664     fun ruleq goal =
   665       (case opt_rule of
   666         SOME r => Seq.single (inst_rule r)
   667       | NONE =>
   668           (get_coinductP ctxt goal @ get_coinductT ctxt inst)
   669           |> tap (trace_rules ctxt coinductN)
   670           |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
   671   in
   672     SUBGOAL_CASES (fn (goal, i) => fn st =>
   673       ruleq goal
   674       |> Seq.maps (RuleCases.consume [] facts)
   675       |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
   676         guess_instance ctxt rule i st
   677         |> Seq.map (rule_instance thy (burrow_options (Variable.polymorphic ctxt) taking))
   678         |> Seq.maps (fn rule' =>
   679           CASES (RuleCases.make_common false (thy, Thm.prop_of rule') cases)
   680             (Method.insert_tac more_facts i THEN Tactic.rtac rule' i) st)))
   681   end;
   682 
   683 end;
   684 
   685 
   686 
   687 (** concrete syntax **)
   688 
   689 structure P = OuterParse;
   690 
   691 val arbitraryN = "arbitrary";
   692 val takingN = "taking";
   693 val ruleN = "rule";
   694 
   695 local
   696 
   697 fun single_rule [rule] = rule
   698   | single_rule _ = error "Single rule expected";
   699 
   700 fun named_rule k arg get =
   701   Scan.lift (Args.$$$ k -- Args.colon) |-- Scan.repeat arg :|--
   702     (fn names => Scan.peek (fn context => Scan.succeed (names |> map (fn name =>
   703       (case get (Context.proof_of context) name of SOME x => x
   704       | NONE => error ("No rule for " ^ k ^ " " ^ quote name))))));
   705 
   706 fun rule get_type get_pred =
   707   named_rule typeN Args.tyname get_type ||
   708   named_rule predN Args.const get_pred ||
   709   named_rule setN Args.const get_pred ||
   710   Scan.lift (Args.$$$ ruleN -- Args.colon) |-- Attrib.thms;
   711 
   712 val cases_rule = rule lookup_casesT lookup_casesP >> single_rule;
   713 val induct_rule = rule lookup_inductT lookup_inductP;
   714 val coinduct_rule = rule lookup_coinductT lookup_coinductP >> single_rule;
   715 
   716 val inst = Scan.lift (Args.$$$ "_") >> K NONE || Args.term >> SOME;
   717 
   718 val def_inst =
   719   ((Scan.lift (Args.binding --| (Args.$$$ "\<equiv>" || Args.$$$ "==")) >> SOME)
   720       -- Args.term) >> SOME ||
   721     inst >> Option.map (pair NONE);
   722 
   723 val free = Args.context -- Args.term >> (fn (_, Free v) => v | (ctxt, t) =>
   724   error ("Bad free variable: " ^ Syntax.string_of_term ctxt t));
   725 
   726 fun unless_more_args scan = Scan.unless (Scan.lift
   727   ((Args.$$$ arbitraryN || Args.$$$ takingN || Args.$$$ typeN ||
   728     Args.$$$ predN || Args.$$$ setN || Args.$$$ ruleN) -- Args.colon)) scan;
   729 
   730 val arbitrary = Scan.optional (Scan.lift (Args.$$$ arbitraryN -- Args.colon) |--
   731   P.and_list1' (Scan.repeat (unless_more_args free))) [];
   732 
   733 val taking = Scan.optional (Scan.lift (Args.$$$ takingN -- Args.colon) |--
   734   Scan.repeat1 (unless_more_args inst)) [];
   735 
   736 in
   737 
   738 val cases_meth =
   739   P.and_list' (Scan.repeat (unless_more_args inst)) -- Scan.option cases_rule >>
   740   (fn (insts, opt_rule) => fn ctxt =>
   741     METHOD_CASES (fn facts => Seq.DETERM (HEADGOAL (cases_tac ctxt insts opt_rule facts))));
   742 
   743 val induct_meth =
   744   P.and_list' (Scan.repeat (unless_more_args def_inst)) --
   745     (arbitrary -- taking -- Scan.option induct_rule) >>
   746   (fn (insts, ((arbitrary, taking), opt_rule)) => fn ctxt =>
   747     RAW_METHOD_CASES (fn facts =>
   748       Seq.DETERM (HEADGOAL (induct_tac ctxt insts arbitrary taking opt_rule facts))));
   749 
   750 val coinduct_meth =
   751   Scan.repeat (unless_more_args inst) -- taking -- Scan.option coinduct_rule >>
   752   (fn ((insts, taking), opt_rule) => fn ctxt =>
   753     RAW_METHOD_CASES (fn facts =>
   754       Seq.DETERM (HEADGOAL (coinduct_tac ctxt insts taking opt_rule facts))));
   755 
   756 end;
   757 
   758 
   759 
   760 (** theory setup **)
   761 
   762 val setup =
   763   attrib_setup #>
   764   Method.setup @{binding cases} cases_meth "case analysis on types or predicates/sets" #>
   765   Method.setup @{binding induct} induct_meth "induction on types or predicates/sets" #>
   766   Method.setup @{binding coinduct} coinduct_meth "coinduction on types or predicates/sets";
   767 
   768 end;