src/Provers/induct_method.ML
author wenzelm
Fri Dec 23 18:36:27 2005 +0100 (2005-12-23)
changeset 18512 f8df49d4af35
parent 18496 ef36f9be255e
child 18580 4fdd39ea2f40
permissions -rw-r--r--
removed obsolete atomize_old;
induct: align_left insts of mutual rules;
wenzelm@11670
     1
(*  Title:      Provers/induct_method.ML
wenzelm@11670
     2
    ID:         $Id$
wenzelm@11670
     3
    Author:     Markus Wenzel, TU Muenchen
wenzelm@11670
     4
wenzelm@11735
     5
Proof by cases and induction on sets and types.
wenzelm@11670
     6
*)
wenzelm@11670
     7
wenzelm@11670
     8
signature INDUCT_METHOD_DATA =
wenzelm@11670
     9
sig
wenzelm@11670
    10
  val cases_default: thm
wenzelm@11670
    11
  val atomize: thm list
wenzelm@18465
    12
  val rulify: thm list
wenzelm@18465
    13
  val rulify_fallback: thm list
wenzelm@11670
    14
end;
wenzelm@11670
    15
wenzelm@11670
    16
signature INDUCT_METHOD =
wenzelm@11670
    17
sig
wenzelm@18250
    18
  val fix_tac: Proof.context -> int -> (string * typ) list -> int -> tactic
wenzelm@18287
    19
  val add_defs: (string option * term) option list -> Proof.context ->
wenzelm@18287
    20
    (term option list * thm list) * Proof.context
wenzelm@18250
    21
  val atomize_term: theory -> term -> term
wenzelm@18250
    22
  val atomize_tac: int -> tactic
wenzelm@18512
    23
  val inner_atomize_tac: int -> tactic
wenzelm@18250
    24
  val rulified_term: thm -> theory * term
wenzelm@18250
    25
  val rulify_tac: int -> tactic
wenzelm@18259
    26
  val guess_instance: thm -> int -> thm -> thm Seq.seq
wenzelm@16391
    27
  val cases_tac: Proof.context -> bool -> term option list list -> thm option ->
wenzelm@18224
    28
    thm list -> int -> cases_tactic
wenzelm@18178
    29
  val induct_tac: Proof.context -> bool -> (string option * term) option list list ->
wenzelm@18465
    30
    (string * typ) list list -> term option list -> thm list option -> thm list -> int ->
wenzelm@18465
    31
    cases_tactic
wenzelm@18235
    32
  val coinduct_tac: Proof.context -> bool -> term option list -> term option list ->
wenzelm@18235
    33
    thm option -> thm list -> int -> cases_tactic
wenzelm@11670
    34
  val setup: (theory -> theory) list
wenzelm@11670
    35
end;
wenzelm@11670
    36
wenzelm@11670
    37
functor InductMethodFun(Data: INDUCT_METHOD_DATA): INDUCT_METHOD =
wenzelm@11670
    38
struct
wenzelm@11670
    39
wenzelm@18465
    40
val meta_spec = thm "Pure.meta_spec";
wenzelm@18465
    41
val all_conjunction = thm "Pure.all_conjunction";
wenzelm@18465
    42
val imp_conjunction = thm "Pure.imp_conjunction";
wenzelm@18465
    43
val conjunction_imp = thm "Pure.conjunction_imp";
wenzelm@18465
    44
val conjunction_assoc = thm "Pure.conjunction_assoc";
wenzelm@18465
    45
val conjunction_congs = [all_conjunction, imp_conjunction];
wenzelm@18465
    46
wenzelm@18465
    47
wenzelm@11670
    48
wenzelm@11670
    49
(** misc utils **)
wenzelm@11670
    50
wenzelm@18287
    51
(* alignment *)
wenzelm@11670
    52
wenzelm@11670
    53
fun align_left msg xs ys =
wenzelm@11670
    54
  let val m = length xs and n = length ys
wenzelm@11735
    55
  in if m < n then raise ERROR_MESSAGE msg else (Library.take (n, xs) ~~ ys) end;
wenzelm@11670
    56
wenzelm@11670
    57
fun align_right msg xs ys =
wenzelm@11670
    58
  let val m = length xs and n = length ys
wenzelm@11735
    59
  in if m < n then raise ERROR_MESSAGE msg else (Library.drop (m - n, xs) ~~ ys) end;
wenzelm@11670
    60
wenzelm@11670
    61
wenzelm@11735
    62
(* prep_inst *)
wenzelm@11670
    63
wenzelm@18205
    64
fun prep_inst thy align tune (tm, ts) =
wenzelm@11670
    65
  let
wenzelm@18205
    66
    val cert = Thm.cterm_of thy;
skalberg@15531
    67
    fun prep_var (x, SOME t) =
wenzelm@11670
    68
          let
wenzelm@11670
    69
            val cx = cert x;
wenzelm@18147
    70
            val {T = xT, thy, ...} = Thm.rep_cterm cx;
wenzelm@12799
    71
            val ct = cert (tune t);
wenzelm@11670
    72
          in
wenzelm@18147
    73
            if Sign.typ_instance thy (#T (Thm.rep_cterm ct), xT) then SOME (cx, ct)
wenzelm@11735
    74
            else raise ERROR_MESSAGE (Pretty.string_of (Pretty.block
wenzelm@11735
    75
             [Pretty.str "Ill-typed instantiation:", Pretty.fbrk,
wenzelm@11735
    76
              Display.pretty_cterm ct, Pretty.str " ::", Pretty.brk 1,
wenzelm@11735
    77
              Display.pretty_ctyp (#T (Thm.crep_cterm ct))]))
wenzelm@11670
    78
          end
skalberg@15531
    79
      | prep_var (_, NONE) = NONE;
wenzelm@11735
    80
    val xs = InductAttrib.vars_of tm;
wenzelm@11670
    81
  in
wenzelm@11735
    82
    align "Rule has fewer variables than instantiations given" xs ts
skalberg@15570
    83
    |> List.mapPartial prep_var
wenzelm@11670
    84
  end;
wenzelm@11670
    85
wenzelm@11670
    86
wenzelm@18205
    87
(* trace_rules *)
wenzelm@18205
    88
wenzelm@18205
    89
fun trace_rules _ kind [] = error ("Unable to figure out " ^ kind ^ " rule")
wenzelm@18205
    90
  | trace_rules ctxt _ rules = Method.trace ctxt rules;
wenzelm@18205
    91
wenzelm@18205
    92
wenzelm@18205
    93
(* make_cases *)
wenzelm@18178
    94
wenzelm@18224
    95
fun make_cases is_open rule =
wenzelm@18224
    96
  RuleCases.make is_open NONE (Thm.theory_of_thm rule, Thm.prop_of rule);
wenzelm@18224
    97
wenzelm@18178
    98
fun warn_open true = warning "Encountered open rule cases -- deprecated"
wenzelm@18178
    99
  | warn_open false = ();
wenzelm@18178
   100
wenzelm@18178
   101
wenzelm@11670
   102
wenzelm@11670
   103
(** cases method **)
wenzelm@11670
   104
wenzelm@11670
   105
(*
wenzelm@11735
   106
  rule selection scheme:
wenzelm@18178
   107
          cases         - default case split
wenzelm@18178
   108
    `x:A` cases ...     - set cases
wenzelm@11735
   109
          cases t       - type cases
wenzelm@18178
   110
    ...   cases ... r   - explicit rule
wenzelm@11670
   111
*)
wenzelm@11670
   112
wenzelm@11670
   113
local
wenzelm@11670
   114
wenzelm@18178
   115
fun find_casesT ctxt ((SOME t :: _) :: _) = InductAttrib.find_casesT ctxt (Term.fastype_of t)
wenzelm@11735
   116
  | find_casesT _ _ = [];
wenzelm@11735
   117
wenzelm@18224
   118
fun find_casesS ctxt (fact :: _) = InductAttrib.find_casesS ctxt (Thm.concl_of fact)
wenzelm@11735
   119
  | find_casesS _ _ = [];
wenzelm@11735
   120
wenzelm@16391
   121
in
wenzelm@16391
   122
wenzelm@16391
   123
fun cases_tac ctxt is_open insts opt_rule facts =
wenzelm@11670
   124
  let
wenzelm@18224
   125
    val _ = warn_open is_open;
wenzelm@18147
   126
    val thy = ProofContext.theory_of ctxt;
wenzelm@18147
   127
    val cert = Thm.cterm_of thy;
wenzelm@11670
   128
wenzelm@11735
   129
    fun inst_rule r =
wenzelm@18224
   130
      if null insts then `RuleCases.get r
wenzelm@11735
   131
      else (align_left "Rule has fewer premises than arguments given" (Thm.prems_of r) insts
wenzelm@18205
   132
        |> (List.concat o map (prep_inst thy align_left I))
wenzelm@18224
   133
        |> Drule.cterm_instantiate) r |> pair (RuleCases.get r);
wenzelm@11670
   134
wenzelm@11735
   135
    val ruleq =
wenzelm@12852
   136
      (case opt_rule of
wenzelm@18205
   137
        SOME r => Seq.single (inst_rule r)
wenzelm@18205
   138
      | NONE =>
wenzelm@18205
   139
          (find_casesS ctxt facts @ find_casesT ctxt insts @ [Data.cases_default])
wenzelm@18205
   140
          |> tap (trace_rules ctxt InductAttrib.casesN)
wenzelm@18224
   141
          |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
wenzelm@18178
   142
  in
wenzelm@18178
   143
    fn i => fn st =>
wenzelm@18224
   144
      ruleq
wenzelm@18235
   145
      |> Seq.maps (RuleCases.consume [] facts)
wenzelm@18224
   146
      |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
wenzelm@18224
   147
        CASES (make_cases is_open rule cases)
wenzelm@18224
   148
          (Method.insert_tac more_facts i THEN Tactic.rtac rule i) st)
wenzelm@18178
   149
  end;
wenzelm@11670
   150
wenzelm@11670
   151
end;
wenzelm@11670
   152
wenzelm@11670
   153
wenzelm@11670
   154
wenzelm@11670
   155
(** induct method **)
wenzelm@11670
   156
wenzelm@18465
   157
(* atomize *)
wenzelm@18465
   158
wenzelm@18512
   159
fun atomize_term thy =
wenzelm@18512
   160
  MetaSimplifier.rewrite_term thy Data.atomize []
wenzelm@18465
   161
  #> ObjectLogic.drop_judgment thy;
wenzelm@18465
   162
wenzelm@18512
   163
val atomize_cterm = Tactic.rewrite true Data.atomize;
wenzelm@18465
   164
wenzelm@18512
   165
val atomize_tac = Tactic.rewrite_goal_tac Data.atomize;
wenzelm@18465
   166
wenzelm@18512
   167
val inner_atomize_tac =
wenzelm@18512
   168
  Tactic.rewrite_goal_tac (map Thm.symmetric conjunction_congs) THEN' atomize_tac;
wenzelm@18465
   169
wenzelm@18465
   170
wenzelm@18465
   171
(* rulify *)
wenzelm@18465
   172
wenzelm@18465
   173
fun rulify_term thy =
wenzelm@18465
   174
  MetaSimplifier.rewrite_term thy (Data.rulify @ conjunction_congs) [] #>
wenzelm@18465
   175
  MetaSimplifier.rewrite_term thy Data.rulify_fallback [];
wenzelm@18465
   176
wenzelm@18465
   177
fun rulified_term thm =
wenzelm@18465
   178
  let
wenzelm@18465
   179
    val thy = Thm.theory_of_thm thm;
wenzelm@18465
   180
    val rulify = rulify_term thy;
wenzelm@18465
   181
    val (As, B) = Logic.strip_horn (Thm.prop_of thm);
wenzelm@18465
   182
  in (thy, Logic.list_implies (map rulify As, rulify B)) end;
wenzelm@18465
   183
wenzelm@18465
   184
val curry_prems_tac =
wenzelm@18465
   185
  let
wenzelm@18465
   186
    val rule = conjunction_imp;
wenzelm@18465
   187
    val thy = Thm.theory_of_thm rule;
wenzelm@18465
   188
    val proc = Simplifier.simproc_i thy "curry_prems"
wenzelm@18465
   189
      [#1 (Logic.dest_equals (Thm.prop_of rule))]
wenzelm@18465
   190
      (fn _ => fn ss => fn _ =>  (*WORKAROUND: prevent descending into meta conjunctions*)
wenzelm@18465
   191
        if exists (equal propT o #2 o #1) (#2 (#bounds (#1 (Simplifier.rep_ss ss))))
wenzelm@18465
   192
        then NONE else SOME rule);
wenzelm@18465
   193
    val ss = MetaSimplifier.theory_context thy Simplifier.empty_ss addsimprocs [proc];
wenzelm@18465
   194
  in Simplifier.full_simp_tac ss end;
wenzelm@18465
   195
wenzelm@18465
   196
val rulify_tac =
wenzelm@18465
   197
  Tactic.rewrite_goal_tac (Data.rulify @ conjunction_congs) THEN'
wenzelm@18465
   198
  Tactic.rewrite_goal_tac Data.rulify_fallback THEN'
wenzelm@18465
   199
  Tactic.conjunction_tac THEN_ALL_NEW
wenzelm@18465
   200
  (curry_prems_tac THEN' Tactic.norm_hhf_tac);
wenzelm@18465
   201
wenzelm@18465
   202
wenzelm@18465
   203
(* prepare rule *)
wenzelm@18465
   204
wenzelm@18465
   205
fun rule_instance thy inst rule =
wenzelm@18465
   206
  Drule.cterm_instantiate (prep_inst thy align_left I (Thm.prop_of rule, inst)) rule;
wenzelm@18465
   207
wenzelm@18465
   208
fun mutual_rule ths =
wenzelm@18465
   209
  (case RuleCases.mutual_rule ths of
wenzelm@18465
   210
    NONE => error "Failed to join given rules into one mutual rule"
wenzelm@18465
   211
  | SOME res => res);
wenzelm@18465
   212
wenzelm@18512
   213
fun internalize k th =
wenzelm@18465
   214
  th |> Thm.permute_prems 0 k
wenzelm@18512
   215
  |> Drule.fconv_rule (Drule.concl_conv (Thm.nprems_of th - k) atomize_cterm);
wenzelm@18465
   216
wenzelm@18465
   217
wenzelm@18465
   218
(* guess rule instantiation -- cannot handle pending goal parameters *)
wenzelm@18465
   219
wenzelm@18465
   220
local
wenzelm@18465
   221
wenzelm@18465
   222
fun dest_env thy (env as Envir.Envir {iTs, ...}) =
wenzelm@18465
   223
  let
wenzelm@18465
   224
    val cert = Thm.cterm_of thy;
wenzelm@18465
   225
    val certT = Thm.ctyp_of thy;
wenzelm@18465
   226
    val pairs = Envir.alist_of env;
wenzelm@18465
   227
    val ts = map (cert o Envir.norm_term env o #2 o #2) pairs;
wenzelm@18465
   228
    val xs = map2 (curry (cert o Var)) (map #1 pairs) (map (#T o Thm.rep_cterm) ts);
wenzelm@18465
   229
  in (map (fn (xi, (S, T)) => (certT (TVar (xi, S)), certT T)) (Vartab.dest iTs), xs ~~ ts) end;
wenzelm@18465
   230
wenzelm@18465
   231
in
wenzelm@18465
   232
wenzelm@18465
   233
fun guess_instance rule i st =
wenzelm@18465
   234
  let
wenzelm@18465
   235
    val {thy, maxidx, ...} = Thm.rep_thm st;
wenzelm@18465
   236
    val goal = Thm.term_of (Thm.cprem_of st i);  (*exception Subscript*)
wenzelm@18465
   237
    val params = rev (rename_wrt_term goal (Logic.strip_params goal));
wenzelm@18465
   238
  in
wenzelm@18465
   239
    if not (null params) then
wenzelm@18465
   240
      (warning ("Cannot determine rule instantiation due to pending parameter(s): " ^
wenzelm@18465
   241
        commas_quote (map (Sign.string_of_term thy o Syntax.mark_boundT) params));
wenzelm@18465
   242
      Seq.single rule)
wenzelm@18465
   243
    else
wenzelm@18465
   244
      let
wenzelm@18465
   245
        val rule' = Thm.incr_indexes (maxidx + 1) rule;
wenzelm@18465
   246
        val concl = Logic.strip_assums_concl goal;
wenzelm@18465
   247
      in
wenzelm@18465
   248
        Unify.smash_unifiers (thy, Envir.empty (#maxidx (Thm.rep_thm rule')),
wenzelm@18465
   249
          [(Thm.concl_of rule', concl)])
wenzelm@18465
   250
        |> Seq.map (fn env => Drule.instantiate (dest_env thy env) rule')
wenzelm@18465
   251
      end
wenzelm@18465
   252
  end handle Subscript => Seq.empty;
wenzelm@18465
   253
wenzelm@18465
   254
end;
wenzelm@18465
   255
wenzelm@18465
   256
wenzelm@18465
   257
(* special renaming of rule parameters *)
wenzelm@18465
   258
wenzelm@18465
   259
fun special_rename_params ctxt [[SOME (Free (z, Type (T, _)))]] [thm] =
wenzelm@18465
   260
      let
wenzelm@18465
   261
        val x = ProofContext.revert_skolem ctxt z;
wenzelm@18465
   262
        fun index i [] = []
wenzelm@18465
   263
          | index i (y :: ys) =
wenzelm@18465
   264
              if x = y then x ^ string_of_int i :: index (i + 1) ys
wenzelm@18465
   265
              else y :: index i ys;
wenzelm@18465
   266
        fun rename_params [] = []
wenzelm@18465
   267
          | rename_params ((y, Type (U, _)) :: ys) =
wenzelm@18465
   268
              (if U = T then x else y) :: rename_params ys
wenzelm@18465
   269
          | rename_params ((y, _) :: ys) = y :: rename_params ys;
wenzelm@18465
   270
        fun rename_asm A =
wenzelm@18465
   271
          let
wenzelm@18465
   272
            val xs = rename_params (Logic.strip_params A);
wenzelm@18465
   273
            val xs' =
wenzelm@18465
   274
              (case List.filter (equal x) xs of
wenzelm@18465
   275
                [] => xs | [_] => xs | _ => index 1 xs);
wenzelm@18465
   276
          in Logic.list_rename_params (xs', A) end;
wenzelm@18465
   277
        fun rename_prop p =
wenzelm@18465
   278
          let val (As, C) = Logic.strip_horn p
wenzelm@18465
   279
          in Logic.list_implies (map rename_asm As, C) end;
wenzelm@18465
   280
        val cp' = cterm_fun rename_prop (Thm.cprop_of thm);
wenzelm@18465
   281
        val thm' = Thm.equal_elim (Thm.reflexive cp') thm;
wenzelm@18465
   282
      in [RuleCases.save thm thm'] end
wenzelm@18465
   283
  | special_rename_params _ _ ths = ths;
wenzelm@18465
   284
wenzelm@18465
   285
wenzelm@18235
   286
(* fix_tac *)
wenzelm@11670
   287
wenzelm@18250
   288
local
wenzelm@18240
   289
wenzelm@18250
   290
fun goal_prefix k ((c as Const ("all", _)) $ Abs (a, T, B)) = c $ Abs (a, T, goal_prefix k B)
wenzelm@18250
   291
  | goal_prefix 0 _ = Term.dummy_pattern propT
wenzelm@18250
   292
  | goal_prefix k ((c as Const ("==>", _)) $ A $ B) = c $ A $ goal_prefix (k - 1) B
wenzelm@18250
   293
  | goal_prefix _ _ = Term.dummy_pattern propT;
wenzelm@18250
   294
wenzelm@18250
   295
fun goal_params k (Const ("all", _) $ Abs (_, _, B)) = goal_params k B + 1
wenzelm@18250
   296
  | goal_params 0 _ = 0
wenzelm@18250
   297
  | goal_params k (Const ("==>", _) $ _ $ B) = goal_params (k - 1) B
wenzelm@18250
   298
  | goal_params _ _ = 0;
wenzelm@11670
   299
wenzelm@18250
   300
fun meta_spec_tac ctxt n (x, T) = SUBGOAL (fn (goal, i) =>
wenzelm@18178
   301
  let
wenzelm@18250
   302
    val thy = ProofContext.theory_of ctxt;
wenzelm@18178
   303
    val cert = Thm.cterm_of thy;
wenzelm@18178
   304
    val certT = Thm.ctyp_of thy;
wenzelm@18178
   305
wenzelm@18178
   306
    val v = Free (x, T);
wenzelm@18250
   307
    fun spec_rule prfx (xs, body) =
wenzelm@18250
   308
      meta_spec
wenzelm@18250
   309
      |> Thm.rename_params_rule ([ProofContext.revert_skolem ctxt x], 1)
wenzelm@18250
   310
      |> Thm.lift_rule (cert prfx)
wenzelm@18250
   311
      |> `(Thm.prop_of #> Logic.strip_assums_concl)
wenzelm@18250
   312
      |-> (fn pred $ arg =>
wenzelm@18250
   313
        Drule.cterm_instantiate
wenzelm@18250
   314
          [(cert (Term.head_of pred), cert (Unify.rlist_abs (xs, body))),
wenzelm@18250
   315
           (cert (Term.head_of arg), cert (Unify.rlist_abs (xs, v)))]);
wenzelm@18250
   316
wenzelm@18250
   317
    fun goal_concl k xs (Const ("all", _) $ Abs (a, T, B)) = goal_concl k ((a, T) :: xs) B
wenzelm@18250
   318
      | goal_concl 0 xs B =
wenzelm@18250
   319
          if not (Term.exists_subterm (fn t => t aconv v) B) then NONE
wenzelm@18250
   320
          else SOME (xs, Term.absfree (x, T, Term.incr_boundvars 1 B))
wenzelm@18250
   321
      | goal_concl k xs (Const ("==>", _) $ _ $ B) = goal_concl (k - 1) xs B
wenzelm@18250
   322
      | goal_concl _ _ _ = NONE;
wenzelm@18205
   323
  in
wenzelm@18250
   324
    (case goal_concl n [] goal of
wenzelm@18250
   325
      SOME concl =>
wenzelm@18250
   326
        (compose_tac (false, spec_rule (goal_prefix n goal) concl, 1) THEN' rtac asm_rl) i
wenzelm@18465
   327
    | NONE => (warning ("Induction: no variable " ^ quote (ProofContext.string_of_term ctxt v) ^
wenzelm@18250
   328
        " to be fixed -- ignored"); all_tac))
wenzelm@18250
   329
  end);
wenzelm@18250
   330
wenzelm@18465
   331
fun miniscope_tac p i = PRIMITIVE (Drule.fconv_rule
wenzelm@18250
   332
  (Drule.goals_conv (Library.equal i)
wenzelm@18465
   333
    (Drule.forall_conv p (Tactic.rewrite true [Thm.symmetric Drule.norm_hhf_eq]))));
wenzelm@18178
   334
wenzelm@18178
   335
in
wenzelm@18178
   336
wenzelm@18250
   337
fun fix_tac _ _ [] = K all_tac
wenzelm@18250
   338
  | fix_tac ctxt n xs = SUBGOAL (fn (goal, i) =>
wenzelm@18250
   339
     (EVERY' (map (meta_spec_tac ctxt n) xs) THEN'
wenzelm@18250
   340
      (miniscope_tac (goal_params n goal))) i);
wenzelm@18178
   341
wenzelm@18178
   342
end;
wenzelm@18178
   343
wenzelm@18178
   344
wenzelm@18235
   345
(* add_defs *)
wenzelm@18178
   346
wenzelm@18178
   347
fun add_defs def_insts =
wenzelm@18178
   348
  let
wenzelm@18178
   349
    fun add (SOME (SOME x, t)) ctxt =
wenzelm@18178
   350
          let val ((lhs, def), ctxt') = ProofContext.add_def (x, t) ctxt
wenzelm@18178
   351
          in ((SOME (Free lhs), [def]), ctxt') end
wenzelm@18178
   352
      | add (SOME (NONE, t)) ctxt = ((SOME t, []), ctxt)
wenzelm@18178
   353
      | add NONE ctxt = ((NONE, []), ctxt);
wenzelm@18178
   354
  in fold_map add def_insts #> apfst (split_list #> apsnd List.concat) end;
wenzelm@18178
   355
wenzelm@11790
   356
wenzelm@18178
   357
(* induct_tac *)
wenzelm@18178
   358
wenzelm@18178
   359
(*
wenzelm@18178
   360
  rule selection scheme:
wenzelm@18178
   361
    `x:A` induct ...     - set induction
wenzelm@18178
   362
          induct x       - type induction
wenzelm@18178
   363
    ...   induct ... r   - explicit rule
wenzelm@18178
   364
*)
wenzelm@18178
   365
wenzelm@18178
   366
local
nipkow@15235
   367
wenzelm@11735
   368
fun find_inductT ctxt insts =
wenzelm@18147
   369
  fold_rev multiply (insts |> List.mapPartial (fn [] => NONE | ts => List.last ts)
wenzelm@18205
   370
    |> map (InductAttrib.find_inductT ctxt o Term.fastype_of)) [[]]
wenzelm@18465
   371
  |> filter_out (forall Drule.is_internal);
wenzelm@11670
   372
wenzelm@18465
   373
fun find_inductS ctxt (fact :: _) = map single (InductAttrib.find_inductS ctxt (Thm.concl_of fact))
wenzelm@11735
   374
  | find_inductS _ _ = [];
wenzelm@11735
   375
wenzelm@16391
   376
in
wenzelm@11790
   377
wenzelm@18512
   378
fun induct_tac ctxt is_open def_insts fixing taking opt_rule facts =
wenzelm@11670
   379
  let
wenzelm@18224
   380
    val _ = warn_open is_open;
wenzelm@18147
   381
    val thy = ProofContext.theory_of ctxt;
wenzelm@18147
   382
    val cert = Thm.cterm_of thy;
wenzelm@11670
   383
wenzelm@18178
   384
    val ((insts, defs), defs_ctxt) = fold_map add_defs def_insts ctxt |>> split_list;
wenzelm@18259
   385
    val atomized_defs = map (map ObjectLogic.atomize_thm) defs;
wenzelm@18178
   386
wenzelm@18465
   387
    fun inst_rule (concls, r) =
wenzelm@18465
   388
      (if null insts then `RuleCases.get r
wenzelm@18512
   389
       else (align_left "Rule has fewer conclusions than arguments given"
wenzelm@18465
   390
          (map Logic.strip_imp_concl (Logic.dest_conjunctions (Thm.concl_of r))) insts
wenzelm@18512
   391
        |> (List.concat o map (prep_inst thy align_right (atomize_term thy)))
wenzelm@18465
   392
        |> Drule.cterm_instantiate) r |> pair (RuleCases.get r))
wenzelm@18465
   393
      |> (fn ((cases, consumes), th) => (((cases, concls), consumes), th));
wenzelm@11670
   394
wenzelm@11735
   395
    val ruleq =
wenzelm@11735
   396
      (case opt_rule of
wenzelm@18465
   397
        SOME rs => Seq.single (inst_rule (mutual_rule rs))
wenzelm@18205
   398
      | NONE =>
wenzelm@18205
   399
          (find_inductS ctxt facts @
wenzelm@18205
   400
            map (special_rename_params defs_ctxt insts) (find_inductT ctxt insts))
wenzelm@18465
   401
          |> List.mapPartial RuleCases.mutual_rule
wenzelm@18465
   402
          |> tap (trace_rules ctxt InductAttrib.inductN o map #2)
wenzelm@18465
   403
          |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
wenzelm@11670
   404
wenzelm@18224
   405
    fun rule_cases rule = RuleCases.make is_open (SOME (Thm.prop_of rule)) (rulified_term rule);
wenzelm@18178
   406
  in
wenzelm@18205
   407
    (fn i => fn st =>
wenzelm@18224
   408
      ruleq
wenzelm@18235
   409
      |> Seq.maps (RuleCases.consume (List.concat defs) facts)
wenzelm@18465
   410
      |> Seq.maps (fn (((cases, concls), (more_consumes, more_facts)), rule) =>
wenzelm@18496
   411
        (PRECISE_CONJUNCTS (length concls) (ALLGOALS (fn j =>
wenzelm@18496
   412
          (CONJUNCTS (ALLGOALS
wenzelm@18465
   413
            (Method.insert_tac (more_facts @ nth_list atomized_defs (j - 1))
wenzelm@18465
   414
              THEN' fix_tac defs_ctxt
wenzelm@18465
   415
                (nth concls (j - 1) + more_consumes)
wenzelm@18465
   416
                (nth_list fixing (j - 1))))
wenzelm@18512
   417
          THEN' inner_atomize_tac) j))
wenzelm@18512
   418
        THEN' atomize_tac) i st |> Seq.maps (fn st' =>
wenzelm@18512
   419
            guess_instance (internalize more_consumes rule) i st'
wenzelm@18235
   420
            |> Seq.map (rule_instance thy taking)
wenzelm@18235
   421
            |> Seq.maps (fn rule' =>
wenzelm@18224
   422
              CASES (rule_cases rule' cases)
wenzelm@18224
   423
                (Tactic.rtac rule' i THEN
wenzelm@18224
   424
                  PRIMSEQ (ProofContext.exports defs_ctxt ctxt)) st'))))
wenzelm@18178
   425
    THEN_ALL_NEW_CASES rulify_tac
wenzelm@18178
   426
  end;
wenzelm@11670
   427
wenzelm@18205
   428
end;
wenzelm@18205
   429
wenzelm@18205
   430
wenzelm@18205
   431
wenzelm@18205
   432
(** coinduct method **)
wenzelm@18205
   433
wenzelm@18205
   434
(*
wenzelm@18205
   435
  rule selection scheme:
wenzelm@18224
   436
    goal "x:A" coinduct ...   - set coinduction
wenzelm@18224
   437
               coinduct x     - type coinduction
wenzelm@18224
   438
               coinduct ... r - explicit rule
wenzelm@18205
   439
*)
wenzelm@18205
   440
wenzelm@18205
   441
local
wenzelm@18205
   442
wenzelm@18205
   443
fun find_coinductT ctxt (SOME t :: _) = InductAttrib.find_coinductT ctxt (Term.fastype_of t)
wenzelm@18205
   444
  | find_coinductT _ _ = [];
wenzelm@18205
   445
wenzelm@18224
   446
fun find_coinductS ctxt goal = InductAttrib.find_coinductS ctxt (Logic.strip_assums_concl goal);
wenzelm@18205
   447
wenzelm@18205
   448
in
wenzelm@18205
   449
wenzelm@18235
   450
fun coinduct_tac ctxt is_open inst taking opt_rule facts =
wenzelm@18205
   451
  let
wenzelm@18224
   452
    val _ = warn_open is_open;
wenzelm@18205
   453
    val thy = ProofContext.theory_of ctxt;
wenzelm@18205
   454
    val cert = Thm.cterm_of thy;
wenzelm@18205
   455
wenzelm@18465
   456
    fun inst_rule r =
wenzelm@18465
   457
      if null inst then `RuleCases.get r
wenzelm@18465
   458
      else Drule.cterm_instantiate (prep_inst thy align_left I (Thm.concl_of r, inst)) r
wenzelm@18465
   459
        |> pair (RuleCases.get r);
wenzelm@18205
   460
wenzelm@18224
   461
    fun ruleq goal =
wenzelm@18205
   462
      (case opt_rule of
wenzelm@18465
   463
        SOME r => Seq.single (inst_rule r)
wenzelm@18205
   464
      | NONE =>
wenzelm@18224
   465
          (find_coinductS ctxt goal @ find_coinductT ctxt inst)
wenzelm@18205
   466
          |> tap (trace_rules ctxt InductAttrib.coinductN)
wenzelm@18465
   467
          |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
wenzelm@18205
   468
  in
wenzelm@18224
   469
    SUBGOAL_CASES (fn (goal, i) => fn st =>
wenzelm@18224
   470
      ruleq goal
wenzelm@18235
   471
      |> Seq.maps (RuleCases.consume [] facts)
wenzelm@18224
   472
      |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
wenzelm@18259
   473
        guess_instance rule i st
wenzelm@18235
   474
        |> Seq.map (rule_instance thy taking)
wenzelm@18235
   475
        |> Seq.maps (fn rule' =>
wenzelm@18224
   476
          CASES (make_cases is_open rule' cases)
wenzelm@18224
   477
            (Method.insert_tac more_facts i THEN Tactic.rtac rule' i) st)))
wenzelm@18205
   478
  end;
wenzelm@18205
   479
wenzelm@11670
   480
end;
wenzelm@11670
   481
wenzelm@11670
   482
wenzelm@11670
   483
wenzelm@11670
   484
(** concrete syntax **)
wenzelm@11670
   485
wenzelm@11670
   486
val openN = "open";
wenzelm@18205
   487
val fixingN = "fixing";
wenzelm@18235
   488
val takingN = "taking";
wenzelm@11670
   489
val ruleN = "rule";
wenzelm@11670
   490
wenzelm@11670
   491
local
wenzelm@11670
   492
wenzelm@18465
   493
fun single_rule [rule] = rule
wenzelm@18465
   494
  | single_rule _ = error "Single rule expected";
wenzelm@18465
   495
wenzelm@15703
   496
fun named_rule k arg get =
wenzelm@18465
   497
  Scan.lift (Args.$$$ k -- Args.colon) |-- Scan.repeat arg :--
wenzelm@18465
   498
    (fn names => Scan.peek (fn ctxt => Scan.succeed (names |> map (fn name =>
wenzelm@18465
   499
      (case get ctxt name of SOME x => x
wenzelm@18465
   500
      | NONE => error ("No rule for " ^ k ^ " " ^ quote name)))))) >> #2;
wenzelm@11670
   501
wenzelm@11670
   502
fun rule get_type get_set =
wenzelm@15703
   503
  named_rule InductAttrib.typeN Args.local_tyname get_type ||
wenzelm@15703
   504
  named_rule InductAttrib.setN Args.local_const get_set ||
wenzelm@18465
   505
  Scan.lift (Args.$$$ ruleN -- Args.colon) |-- Attrib.local_thmss;
wenzelm@11670
   506
wenzelm@18465
   507
val cases_rule = rule InductAttrib.lookup_casesT InductAttrib.lookup_casesS >> single_rule;
wenzelm@11670
   508
val induct_rule = rule InductAttrib.lookup_inductT InductAttrib.lookup_inductS;
wenzelm@18465
   509
val coinduct_rule =
wenzelm@18465
   510
  rule InductAttrib.lookup_coinductT InductAttrib.lookup_coinductS >> single_rule;
wenzelm@11670
   511
wenzelm@18178
   512
val inst = Scan.lift (Args.$$$ "_") >> K NONE || Args.local_term >> SOME;
wenzelm@18147
   513
wenzelm@18178
   514
val def_inst =
wenzelm@18178
   515
  ((Scan.lift (Args.name --| (Args.$$$ "\\<equiv>" || Args.$$$ "==")) >> SOME)
wenzelm@18178
   516
      -- Args.local_term) >> SOME ||
wenzelm@18178
   517
    inst >> Option.map (pair NONE);
wenzelm@11670
   518
wenzelm@18147
   519
val free = Scan.state -- Args.local_term >> (fn (_, Free v) => v | (ctxt, t) =>
wenzelm@18147
   520
  error ("Bad free variable: " ^ ProofContext.string_of_term ctxt t));
wenzelm@18147
   521
wenzelm@18178
   522
fun unless_more_args scan = Scan.unless (Scan.lift
wenzelm@18235
   523
  ((Args.$$$ fixingN || Args.$$$ takingN || Args.$$$ InductAttrib.typeN ||
wenzelm@18235
   524
    Args.$$$ InductAttrib.setN || Args.$$$ ruleN) -- Args.colon)) scan;
wenzelm@18205
   525
wenzelm@18205
   526
val fixing = Scan.optional (Scan.lift (Args.$$$ fixingN -- Args.colon) |--
wenzelm@18205
   527
  Args.and_list1 (Scan.repeat (unless_more_args free))) [];
wenzelm@18178
   528
wenzelm@18235
   529
val taking = Scan.optional (Scan.lift (Args.$$$ takingN -- Args.colon) |--
wenzelm@18235
   530
  Scan.repeat1 (unless_more_args inst)) [];
wenzelm@18235
   531
wenzelm@11670
   532
in
wenzelm@11670
   533
wenzelm@18235
   534
fun cases_meth src =
wenzelm@18235
   535
  Method.syntax (Args.mode openN --
wenzelm@18235
   536
    (Args.and_list (Scan.repeat (unless_more_args inst)) -- Scan.option cases_rule)) src
wenzelm@18235
   537
  #> (fn (ctxt, (is_open, (insts, opt_rule))) =>
wenzelm@18235
   538
    Method.METHOD_CASES (fn facts =>
wenzelm@18235
   539
      Seq.DETERM (HEADGOAL (cases_tac ctxt is_open insts opt_rule facts))));
wenzelm@18178
   540
wenzelm@18512
   541
fun induct_meth src =
wenzelm@18235
   542
  Method.syntax (Args.mode openN --
wenzelm@18235
   543
    (Args.and_list (Scan.repeat (unless_more_args def_inst)) --
wenzelm@18235
   544
    (fixing -- taking -- Scan.option induct_rule))) src
wenzelm@18235
   545
  #> (fn (ctxt, (is_open, (insts, ((fixing, taking), opt_rule)))) =>
wenzelm@18235
   546
    Method.RAW_METHOD_CASES (fn facts =>
wenzelm@18512
   547
      Seq.DETERM (HEADGOAL (induct_tac ctxt is_open insts fixing taking opt_rule facts))));
wenzelm@18205
   548
wenzelm@18235
   549
fun coinduct_meth src =
wenzelm@18235
   550
  Method.syntax (Args.mode openN --
wenzelm@18235
   551
    (Scan.repeat (unless_more_args inst) -- taking -- Scan.option coinduct_rule)) src
wenzelm@18235
   552
  #> (fn (ctxt, (is_open, ((insts, taking), opt_rule))) =>
wenzelm@18235
   553
    Method.RAW_METHOD_CASES (fn facts =>
wenzelm@18235
   554
      Seq.DETERM (HEADGOAL (coinduct_tac ctxt is_open insts taking opt_rule facts))));
wenzelm@11670
   555
wenzelm@11670
   556
end;
wenzelm@11670
   557
wenzelm@11670
   558
wenzelm@11670
   559
wenzelm@11670
   560
(** theory setup **)
wenzelm@11670
   561
wenzelm@11670
   562
val setup =
wenzelm@11670
   563
  [Method.add_methods
wenzelm@18235
   564
    [(InductAttrib.casesN, cases_meth, "case analysis on types or sets"),
wenzelm@18512
   565
     (InductAttrib.inductN, induct_meth, "induction on types or sets"),
wenzelm@18235
   566
     (InductAttrib.coinductN, coinduct_meth, "coinduction on types or sets")]];
wenzelm@11670
   567
wenzelm@11670
   568
end;