src/HOL/Tools/inductive.ML
author haftmann
Thu Aug 12 13:23:46 2010 +0200 (2010-08-12)
changeset 38388 94d5624dd1f7
parent 38350 480b2de9927c
child 38665 e92223c886f8
permissions -rw-r--r--
Named_Target.theory_init
haftmann@31723
     1
(*  Title:      HOL/Tools/inductive.ML
berghofe@5094
     2
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
wenzelm@21367
     3
    Author:     Stefan Berghofer and Markus Wenzel, TU Muenchen
berghofe@5094
     4
wenzelm@6424
     5
(Co)Inductive Definition module for HOL.
berghofe@5094
     6
berghofe@5094
     7
Features:
wenzelm@6424
     8
  * least or greatest fixedpoints
wenzelm@6424
     9
  * mutually recursive definitions
wenzelm@6424
    10
  * definitions involving arbitrary monotone operators
wenzelm@6424
    11
  * automatically proves introduction and elimination rules
berghofe@5094
    12
berghofe@5094
    13
  Introduction rules have the form
berghofe@21024
    14
  [| M Pj ti, ..., Q x, ... |] ==> Pk t
berghofe@5094
    15
  where M is some monotone operator (usually the identity)
berghofe@21024
    16
  Q x is any side condition on the free variables
berghofe@5094
    17
  ti, t are any terms
berghofe@21024
    18
  Pj, Pk are two of the predicates being defined in mutual recursion
berghofe@5094
    19
*)
berghofe@5094
    20
haftmann@31723
    21
signature BASIC_INDUCTIVE =
berghofe@5094
    22
sig
wenzelm@33458
    23
  type inductive_result =
wenzelm@33458
    24
    {preds: term list, elims: thm list, raw_induct: thm,
bulwahn@37734
    25
     induct: thm, inducts: thm list, intrs: thm list, eqs: thm list}
wenzelm@21526
    26
  val morph_result: morphism -> inductive_result -> inductive_result
wenzelm@33458
    27
  type inductive_info = {names: string list, coind: bool} * inductive_result
wenzelm@21526
    28
  val the_inductive: Proof.context -> string -> inductive_info
wenzelm@21367
    29
  val print_inductives: Proof.context -> unit
wenzelm@18728
    30
  val mono_add: attribute
wenzelm@18728
    31
  val mono_del: attribute
wenzelm@21367
    32
  val get_monos: Proof.context -> thm list
wenzelm@21367
    33
  val mk_cases: Proof.context -> term -> thm
wenzelm@10910
    34
  val inductive_forall_name: string
wenzelm@10910
    35
  val inductive_forall_def: thm
wenzelm@10910
    36
  val rulify: thm -> thm
wenzelm@28839
    37
  val inductive_cases: (Attrib.binding * string list) list -> local_theory ->
wenzelm@28084
    38
    thm list list * local_theory
wenzelm@28839
    39
  val inductive_cases_i: (Attrib.binding * term list) list -> local_theory ->
wenzelm@28084
    40
    thm list list * local_theory
wenzelm@33458
    41
  type inductive_flags =
wenzelm@33669
    42
    {quiet_mode: bool, verbose: bool, alt_name: binding, coind: bool,
wenzelm@33669
    43
      no_elim: bool, no_ind: bool, skip_mono: bool, fork_mono: bool}
wenzelm@24815
    44
  val add_inductive_i:
haftmann@29581
    45
    inductive_flags -> ((binding * typ) * mixfix) list ->
wenzelm@28084
    46
    (string * typ) list -> (Attrib.binding * term) list -> thm list -> local_theory ->
wenzelm@28084
    47
    inductive_result * local_theory
wenzelm@28083
    48
  val add_inductive: bool -> bool ->
haftmann@29581
    49
    (binding * string option * mixfix) list ->
haftmann@29581
    50
    (binding * string option * mixfix) list ->
wenzelm@28084
    51
    (Attrib.binding * string) list ->
wenzelm@28083
    52
    (Facts.ref * Attrib.src list) list ->
wenzelm@29388
    53
    bool -> local_theory -> inductive_result * local_theory
wenzelm@33726
    54
  val add_inductive_global: inductive_flags ->
haftmann@29581
    55
    ((binding * typ) * mixfix) list -> (string * typ) list -> (Attrib.binding * term) list ->
wenzelm@28084
    56
    thm list -> theory -> inductive_result * theory
berghofe@22789
    57
  val arities_of: thm -> (string * int) list
berghofe@22789
    58
  val params_of: thm -> term list
berghofe@22789
    59
  val partition_rules: thm -> thm list -> (string * thm list) list
berghofe@25822
    60
  val partition_rules': thm -> (thm * 'a) list -> (string * (thm * 'a) list) list
berghofe@22789
    61
  val unpartition_rules: thm list -> (string * 'a list) list -> 'a list
berghofe@22789
    62
  val infer_intro_vars: thm -> int -> thm list -> term list list
wenzelm@18708
    63
  val setup: theory -> theory
berghofe@5094
    64
end;
berghofe@5094
    65
haftmann@31723
    66
signature INDUCTIVE =
berghofe@23762
    67
sig
haftmann@31723
    68
  include BASIC_INDUCTIVE
wenzelm@33458
    69
  type add_ind_def =
wenzelm@33458
    70
    inductive_flags ->
wenzelm@33458
    71
    term list -> (Attrib.binding * term) list -> thm list ->
wenzelm@33458
    72
    term list -> (binding * mixfix) list ->
wenzelm@33458
    73
    local_theory -> inductive_result * local_theory
bulwahn@35757
    74
  val declare_rules: binding -> bool -> bool -> string list -> term list ->
berghofe@34986
    75
    thm list -> binding list -> Attrib.src list list -> (thm * string list * int) list ->
bulwahn@37734
    76
    thm list -> thm -> local_theory -> thm list * thm list * thm list * thm * thm list * local_theory
berghofe@23762
    77
  val add_ind_def: add_ind_def
wenzelm@28083
    78
  val gen_add_inductive_i: add_ind_def -> inductive_flags ->
haftmann@29581
    79
    ((binding * typ) * mixfix) list -> (string * typ) list -> (Attrib.binding * term) list ->
wenzelm@28084
    80
    thm list -> local_theory -> inductive_result * local_theory
wenzelm@28083
    81
  val gen_add_inductive: add_ind_def -> bool -> bool ->
haftmann@29581
    82
    (binding * string option * mixfix) list ->
haftmann@29581
    83
    (binding * string option * mixfix) list ->
wenzelm@28084
    84
    (Attrib.binding * string) list -> (Facts.ref * Attrib.src list) list ->
wenzelm@29388
    85
    bool -> local_theory -> inductive_result * local_theory
wenzelm@36958
    86
  val gen_ind_decl: add_ind_def -> bool -> (bool -> local_theory -> local_theory) parser
berghofe@23762
    87
end;
berghofe@23762
    88
haftmann@31723
    89
structure Inductive: INDUCTIVE =
berghofe@5094
    90
struct
berghofe@5094
    91
wenzelm@9598
    92
wenzelm@10729
    93
(** theory context references **)
wenzelm@10729
    94
wenzelm@11991
    95
val inductive_forall_name = "HOL.induct_forall";
haftmann@32602
    96
val inductive_forall_def = @{thm induct_forall_def};
wenzelm@11991
    97
val inductive_conj_name = "HOL.induct_conj";
haftmann@32602
    98
val inductive_conj_def = @{thm induct_conj_def};
haftmann@32602
    99
val inductive_conj = @{thms induct_conj};
haftmann@32602
   100
val inductive_atomize = @{thms induct_atomize};
haftmann@32602
   101
val inductive_rulify = @{thms induct_rulify};
haftmann@32602
   102
val inductive_rulify_fallback = @{thms induct_rulify_fallback};
wenzelm@10729
   103
berghofe@21024
   104
val notTrueE = TrueI RSN (2, notE);
berghofe@21024
   105
val notFalseI = Seq.hd (atac 1 notI);
wenzelm@32181
   106
wenzelm@32181
   107
val simp_thms' = map mk_meta_eq
wenzelm@32181
   108
  @{lemma "(~True) = False" "(~False) = True"
wenzelm@32181
   109
      "(True --> P) = P" "(False --> P) = True"
wenzelm@32181
   110
      "(P & True) = P" "(True & P) = P"
wenzelm@32181
   111
    by (fact simp_thms)+};
berghofe@21024
   112
haftmann@32652
   113
val simp_thms'' = map mk_meta_eq [@{thm inf_fun_eq}, @{thm inf_bool_eq}] @ simp_thms';
haftmann@32652
   114
haftmann@32652
   115
val simp_thms''' = map mk_meta_eq
haftmann@32652
   116
  [@{thm le_fun_def}, @{thm le_bool_def}, @{thm sup_fun_eq}, @{thm sup_bool_eq}];
wenzelm@10729
   117
wenzelm@10729
   118
wenzelm@22846
   119
(** context data **)
berghofe@7710
   120
berghofe@21024
   121
type inductive_result =
berghofe@23762
   122
  {preds: term list, elims: thm list, raw_induct: thm,
bulwahn@37734
   123
   induct: thm, inducts: thm list, intrs: thm list, eqs: thm list};
berghofe@7710
   124
bulwahn@37734
   125
fun morph_result phi {preds, elims, raw_induct: thm, induct, inducts, intrs, eqs} =
wenzelm@21526
   126
  let
wenzelm@21526
   127
    val term = Morphism.term phi;
wenzelm@21526
   128
    val thm = Morphism.thm phi;
wenzelm@21526
   129
    val fact = Morphism.fact phi;
wenzelm@21526
   130
  in
berghofe@23762
   131
   {preds = map term preds, elims = fact elims, raw_induct = thm raw_induct,
bulwahn@37734
   132
    induct = thm induct, inducts = fact inducts, intrs = fact intrs, eqs = fact eqs}
wenzelm@21526
   133
  end;
wenzelm@21526
   134
berghofe@21024
   135
type inductive_info =
berghofe@21024
   136
  {names: string list, coind: bool} * inductive_result;
berghofe@21024
   137
wenzelm@33519
   138
structure InductiveData = Generic_Data
wenzelm@22846
   139
(
berghofe@7710
   140
  type T = inductive_info Symtab.table * thm list;
berghofe@7710
   141
  val empty = (Symtab.empty, []);
wenzelm@16432
   142
  val extend = I;
wenzelm@33519
   143
  fun merge ((tab1, monos1), (tab2, monos2)) : T =
wenzelm@24039
   144
    (Symtab.merge (K true) (tab1, tab2), Thm.merge_thms (monos1, monos2));
wenzelm@22846
   145
);
berghofe@7710
   146
wenzelm@21526
   147
val get_inductives = InductiveData.get o Context.Proof;
wenzelm@22846
   148
wenzelm@22846
   149
fun print_inductives ctxt =
wenzelm@22846
   150
  let
wenzelm@22846
   151
    val (tab, monos) = get_inductives ctxt;
wenzelm@22846
   152
    val space = Consts.space_of (ProofContext.consts_of ctxt);
wenzelm@22846
   153
  in
wenzelm@33095
   154
    [Pretty.strs ("(co)inductives:" :: map #1 (Name_Space.extern_table (space, tab))),
wenzelm@32091
   155
     Pretty.big_list "monotonicity rules:" (map (Display.pretty_thm ctxt) monos)]
wenzelm@22846
   156
    |> Pretty.chunks |> Pretty.writeln
wenzelm@22846
   157
  end;
berghofe@7710
   158
berghofe@7710
   159
berghofe@7710
   160
(* get and put data *)
berghofe@7710
   161
wenzelm@21367
   162
fun the_inductive ctxt name =
wenzelm@21526
   163
  (case Symtab.lookup (#1 (get_inductives ctxt)) name of
berghofe@21024
   164
    NONE => error ("Unknown (co)inductive predicate " ^ quote name)
skalberg@15531
   165
  | SOME info => info);
wenzelm@9598
   166
wenzelm@25380
   167
fun put_inductives names info = InductiveData.map
wenzelm@25380
   168
  (apfst (fold (fn name => Symtab.update (name, info)) names));
berghofe@7710
   169
wenzelm@8277
   170
berghofe@7710
   171
berghofe@7710
   172
(** monotonicity rules **)
berghofe@7710
   173
wenzelm@21526
   174
val get_monos = #2 o get_inductives;
wenzelm@21367
   175
val map_monos = InductiveData.map o apsnd;
wenzelm@8277
   176
berghofe@7710
   177
fun mk_mono thm =
berghofe@7710
   178
  let
berghofe@33933
   179
    fun eq2mono thm' = thm' RS (thm' RS eq_to_mono);
haftmann@32652
   180
    fun dest_less_concl thm = dest_less_concl (thm RS @{thm le_funD})
haftmann@32652
   181
      handle THM _ => thm RS @{thm le_boolD}
berghofe@7710
   182
  in
berghofe@33933
   183
    case concl_of thm of
berghofe@22275
   184
      Const ("==", _) $ _ $ _ => eq2mono (thm RS meta_eq_to_obj_eq)
wenzelm@35364
   185
    | _ $ (Const (@{const_name "op ="}, _) $ _ $ _) => eq2mono thm
haftmann@35092
   186
    | _ $ (Const (@{const_name Orderings.less_eq}, _) $ _ $ _) =>
berghofe@33933
   187
      dest_less_concl (Seq.hd (REPEAT (FIRSTGOAL
berghofe@33933
   188
        (resolve_tac [@{thm le_funI}, @{thm le_boolI'}])) thm))
berghofe@33933
   189
    | _ => thm
wenzelm@32091
   190
  end handle THM _ =>
wenzelm@32091
   191
    error ("Bad monotonicity theorem:\n" ^ Display.string_of_thm_without_context thm);
berghofe@7710
   192
berghofe@33933
   193
val mono_add = Thm.declaration_attribute (map_monos o Thm.add_thm o mk_mono);
berghofe@33933
   194
val mono_del = Thm.declaration_attribute (map_monos o Thm.del_thm o mk_mono);
berghofe@7710
   195
berghofe@7710
   196
wenzelm@7107
   197
wenzelm@10735
   198
(** misc utilities **)
wenzelm@6424
   199
wenzelm@26477
   200
fun message quiet_mode s = if quiet_mode then () else writeln s;
wenzelm@26477
   201
fun clean_message quiet_mode s = if ! quick_and_dirty then () else message quiet_mode s;
berghofe@5662
   202
wenzelm@6424
   203
fun coind_prefix true = "co"
wenzelm@6424
   204
  | coind_prefix false = "";
wenzelm@6424
   205
wenzelm@24133
   206
fun log (b:int) m n = if m >= n then 0 else 1 + log b (b * m) n;
wenzelm@6424
   207
berghofe@21024
   208
fun make_bool_args f g [] i = []
berghofe@21024
   209
  | make_bool_args f g (x :: xs) i =
berghofe@21024
   210
      (if i mod 2 = 0 then f x else g x) :: make_bool_args f g xs (i div 2);
berghofe@21024
   211
berghofe@21024
   212
fun make_bool_args' xs =
berghofe@21024
   213
  make_bool_args (K HOLogic.false_const) (K HOLogic.true_const) xs;
berghofe@21024
   214
haftmann@33957
   215
fun arg_types_of k c = drop k (binder_types (fastype_of c));
haftmann@33077
   216
berghofe@21024
   217
fun find_arg T x [] = sys_error "find_arg"
berghofe@21024
   218
  | find_arg T x ((p as (_, (SOME _, _))) :: ps) =
berghofe@21024
   219
      apsnd (cons p) (find_arg T x ps)
berghofe@21024
   220
  | find_arg T x ((p as (U, (NONE, y))) :: ps) =
wenzelm@23577
   221
      if (T: typ) = U then (y, (U, (SOME x, y)) :: ps)
berghofe@21024
   222
      else apsnd (cons p) (find_arg T x ps);
berghofe@7020
   223
berghofe@21024
   224
fun make_args Ts xs =
haftmann@28524
   225
  map (fn (T, (NONE, ())) => Const (@{const_name undefined}, T) | (_, (SOME t, ())) => t)
berghofe@21024
   226
    (fold (fn (t, T) => snd o find_arg T t) xs (map (rpair (NONE, ())) Ts));
berghofe@7020
   227
berghofe@21024
   228
fun make_args' Ts xs Us =
berghofe@21024
   229
  fst (fold_map (fn T => find_arg T ()) Us (Ts ~~ map (pair NONE) xs));
berghofe@7020
   230
berghofe@21024
   231
fun dest_predicate cs params t =
berghofe@5094
   232
  let
berghofe@21024
   233
    val k = length params;
berghofe@21024
   234
    val (c, ts) = strip_comb t;
berghofe@21024
   235
    val (xs, ys) = chop k ts;
haftmann@31986
   236
    val i = find_index (fn c' => c' = c) cs;
berghofe@21024
   237
  in
berghofe@21024
   238
    if xs = params andalso i >= 0 then
haftmann@33077
   239
      SOME (c, i, ys, chop (length ys) (arg_types_of k c))
berghofe@21024
   240
    else NONE
berghofe@5094
   241
  end;
berghofe@5094
   242
berghofe@21024
   243
fun mk_names a 0 = []
berghofe@21024
   244
  | mk_names a 1 = [a]
berghofe@21024
   245
  | mk_names a n = map (fn i => a ^ string_of_int i) (1 upto n);
berghofe@10988
   246
bulwahn@37734
   247
fun select_disj 1 1 = []
bulwahn@37734
   248
  | select_disj _ 1 = [rtac disjI1]
bulwahn@37734
   249
  | select_disj n i = (rtac disjI2)::(select_disj (n - 1) (i - 1));
wenzelm@6424
   250
wenzelm@6424
   251
wenzelm@10729
   252
(** process rules **)
wenzelm@10729
   253
wenzelm@10729
   254
local
berghofe@5094
   255
berghofe@23762
   256
fun err_in_rule ctxt name t msg =
wenzelm@16432
   257
  error (cat_lines ["Ill-formed introduction rule " ^ quote name,
wenzelm@24920
   258
    Syntax.string_of_term ctxt t, msg]);
wenzelm@10729
   259
berghofe@23762
   260
fun err_in_prem ctxt name t p msg =
wenzelm@24920
   261
  error (cat_lines ["Ill-formed premise", Syntax.string_of_term ctxt p,
wenzelm@24920
   262
    "in introduction rule " ^ quote name, Syntax.string_of_term ctxt t, msg]);
berghofe@5094
   263
berghofe@21024
   264
val bad_concl = "Conclusion of introduction rule must be an inductive predicate";
wenzelm@10729
   265
berghofe@21024
   266
val bad_ind_occ = "Inductive predicate occurs in argument of inductive predicate";
berghofe@21024
   267
berghofe@21024
   268
val bad_app = "Inductive predicate must be applied to parameter(s) ";
paulson@11358
   269
wenzelm@16432
   270
fun atomize_term thy = MetaSimplifier.rewrite_term thy inductive_atomize [];
wenzelm@10729
   271
wenzelm@10729
   272
in
berghofe@5094
   273
wenzelm@28083
   274
fun check_rule ctxt cs params ((binding, att), rule) =
wenzelm@10729
   275
  let
wenzelm@30218
   276
    val err_name = Binding.str_of binding;
berghofe@21024
   277
    val params' = Term.variant_frees rule (Logic.strip_params rule);
berghofe@21024
   278
    val frees = rev (map Free params');
berghofe@21024
   279
    val concl = subst_bounds (frees, Logic.strip_assums_concl rule);
berghofe@21024
   280
    val prems = map (curry subst_bounds frees) (Logic.strip_assums_hyp rule);
berghofe@23762
   281
    val rule' = Logic.list_implies (prems, concl);
berghofe@23762
   282
    val aprems = map (atomize_term (ProofContext.theory_of ctxt)) prems;
berghofe@21024
   283
    val arule = list_all_free (params', Logic.list_implies (aprems, concl));
berghofe@21024
   284
berghofe@21024
   285
    fun check_ind err t = case dest_predicate cs params t of
berghofe@21024
   286
        NONE => err (bad_app ^
wenzelm@24920
   287
          commas (map (Syntax.string_of_term ctxt) params))
berghofe@21024
   288
      | SOME (_, _, ys, _) =>
berghofe@21024
   289
          if exists (fn c => exists (fn t => Logic.occs (c, t)) ys) cs
berghofe@21024
   290
          then err bad_ind_occ else ();
berghofe@21024
   291
berghofe@21024
   292
    fun check_prem' prem t =
haftmann@36692
   293
      if member (op =) cs (head_of t) then
haftmann@29006
   294
        check_ind (err_in_prem ctxt err_name rule prem) t
berghofe@21024
   295
      else (case t of
berghofe@21024
   296
          Abs (_, _, t) => check_prem' prem t
berghofe@21024
   297
        | t $ u => (check_prem' prem t; check_prem' prem u)
berghofe@21024
   298
        | _ => ());
berghofe@5094
   299
wenzelm@10729
   300
    fun check_prem (prem, aprem) =
berghofe@21024
   301
      if can HOLogic.dest_Trueprop aprem then check_prem' prem prem
haftmann@29006
   302
      else err_in_prem ctxt err_name rule prem "Non-atomic premise";
wenzelm@10729
   303
  in
paulson@11358
   304
    (case concl of
wenzelm@35364
   305
       Const (@{const_name Trueprop}, _) $ t =>
haftmann@36692
   306
         if member (op =) cs (head_of t) then
haftmann@29006
   307
           (check_ind (err_in_rule ctxt err_name rule') t;
berghofe@21024
   308
            List.app check_prem (prems ~~ aprems))
haftmann@29006
   309
         else err_in_rule ctxt err_name rule' bad_concl
haftmann@29006
   310
     | _ => err_in_rule ctxt err_name rule' bad_concl);
wenzelm@28083
   311
    ((binding, att), arule)
wenzelm@10729
   312
  end;
berghofe@5094
   313
berghofe@24744
   314
val rulify =
wenzelm@18222
   315
  hol_simplify inductive_conj
wenzelm@18463
   316
  #> hol_simplify inductive_rulify
wenzelm@18463
   317
  #> hol_simplify inductive_rulify_fallback
wenzelm@30552
   318
  #> Simplifier.norm_hhf;
wenzelm@10729
   319
wenzelm@10729
   320
end;
wenzelm@10729
   321
berghofe@5094
   322
wenzelm@6424
   323
berghofe@21024
   324
(** proofs for (co)inductive predicates **)
wenzelm@6424
   325
berghofe@26534
   326
(* prove monotonicity *)
berghofe@5094
   327
berghofe@36642
   328
fun prove_mono quiet_mode skip_mono fork_mono predT fp_fun monos ctxt =
wenzelm@29388
   329
 (message (quiet_mode orelse skip_mono andalso !quick_and_dirty orelse fork_mono)
berghofe@26534
   330
    "  Proving monotonicity ...";
wenzelm@32970
   331
  (if skip_mono then Skip_Proof.prove else if fork_mono then Goal.prove_future else Goal.prove) ctxt
berghofe@36642
   332
    [] []
wenzelm@17985
   333
    (HOLogic.mk_Trueprop
wenzelm@24815
   334
      (Const (@{const_name Orderings.mono}, (predT --> predT) --> HOLogic.boolT) $ fp_fun))
wenzelm@25380
   335
    (fn _ => EVERY [rtac @{thm monoI} 1,
haftmann@32652
   336
      REPEAT (resolve_tac [@{thm le_funI}, @{thm le_boolI'}] 1),
berghofe@21024
   337
      REPEAT (FIRST
berghofe@21024
   338
        [atac 1,
berghofe@33933
   339
         resolve_tac (map mk_mono monos @ get_monos ctxt) 1,
haftmann@32652
   340
         etac @{thm le_funE} 1, dtac @{thm le_boolD} 1])]));
berghofe@5094
   341
wenzelm@6424
   342
wenzelm@10735
   343
(* prove introduction rules *)
berghofe@5094
   344
berghofe@36642
   345
fun prove_intrs quiet_mode coind mono fp_def k intr_ts rec_preds_defs ctxt ctxt' =
berghofe@5094
   346
  let
wenzelm@26477
   347
    val _ = clean_message quiet_mode "  Proving the introduction rules ...";
berghofe@5094
   348
berghofe@21024
   349
    val unfold = funpow k (fn th => th RS fun_cong)
berghofe@21024
   350
      (mono RS (fp_def RS
haftmann@32652
   351
        (if coind then @{thm def_gfp_unfold} else @{thm def_lfp_unfold})));
berghofe@5094
   352
berghofe@21024
   353
    val rules = [refl, TrueI, notFalseI, exI, conjI];
berghofe@21024
   354
berghofe@36642
   355
    val intrs = map_index (fn (i, intr) =>
berghofe@36642
   356
      Skip_Proof.prove ctxt [] [] intr (fn _ => EVERY
berghofe@21024
   357
       [rewrite_goals_tac rec_preds_defs,
berghofe@21024
   358
        rtac (unfold RS iffD2) 1,
berghofe@21024
   359
        EVERY1 (select_disj (length intr_ts) (i + 1)),
wenzelm@17985
   360
        (*Not ares_tac, since refl must be tried before any equality assumptions;
wenzelm@17985
   361
          backtracking may occur if the premises have extra variables!*)
berghofe@36642
   362
        DEPTH_SOLVE_1 (resolve_tac rules 1 APPEND assume_tac 1)])
berghofe@36642
   363
       |> singleton (ProofContext.export ctxt ctxt')) intr_ts
berghofe@5094
   364
berghofe@5094
   365
  in (intrs, unfold) end;
berghofe@5094
   366
wenzelm@6424
   367
wenzelm@10735
   368
(* prove elimination rules *)
berghofe@5094
   369
berghofe@36642
   370
fun prove_elims quiet_mode cs params intr_ts intr_names unfold rec_preds_defs ctxt ctxt''' =
berghofe@5094
   371
  let
wenzelm@26477
   372
    val _ = clean_message quiet_mode "  Proving the elimination rules ...";
berghofe@5094
   373
berghofe@36642
   374
    val ([pname], ctxt') = Variable.variant_fixes ["P"] ctxt;
berghofe@21024
   375
    val P = HOLogic.mk_Trueprop (Free (pname, HOLogic.boolT));
berghofe@21024
   376
berghofe@21024
   377
    fun dest_intr r =
berghofe@21024
   378
      (the (dest_predicate cs params (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))),
berghofe@21024
   379
       Logic.strip_assums_hyp r, Logic.strip_params r);
berghofe@21024
   380
berghofe@21024
   381
    val intrs = map dest_intr intr_ts ~~ intr_names;
berghofe@21024
   382
berghofe@21024
   383
    val rules1 = [disjE, exE, FalseE];
berghofe@21024
   384
    val rules2 = [conjE, FalseE, notTrueE];
berghofe@21024
   385
berghofe@21024
   386
    fun prove_elim c =
berghofe@21024
   387
      let
haftmann@33077
   388
        val Ts = arg_types_of (length params) c;
berghofe@21024
   389
        val (anames, ctxt'') = Variable.variant_fixes (mk_names "a" (length Ts)) ctxt';
berghofe@21024
   390
        val frees = map Free (anames ~~ Ts);
berghofe@21024
   391
berghofe@21024
   392
        fun mk_elim_prem ((_, _, us, _), ts, params') =
berghofe@21024
   393
          list_all (params',
berghofe@21024
   394
            Logic.list_implies (map (HOLogic.mk_Trueprop o HOLogic.mk_eq)
berghofe@21024
   395
              (frees ~~ us) @ ts, P));
wenzelm@33317
   396
        val c_intrs = filter (equal c o #1 o #1 o #1) intrs;
berghofe@21024
   397
        val prems = HOLogic.mk_Trueprop (list_comb (c, params @ frees)) ::
berghofe@21024
   398
           map mk_elim_prem (map #1 c_intrs)
berghofe@21024
   399
      in
wenzelm@32970
   400
        (Skip_Proof.prove ctxt'' [] prems P
berghofe@21024
   401
          (fn {prems, ...} => EVERY
berghofe@21024
   402
            [cut_facts_tac [hd prems] 1,
berghofe@21024
   403
             rewrite_goals_tac rec_preds_defs,
berghofe@21024
   404
             dtac (unfold RS iffD1) 1,
berghofe@21024
   405
             REPEAT (FIRSTGOAL (eresolve_tac rules1)),
berghofe@21024
   406
             REPEAT (FIRSTGOAL (eresolve_tac rules2)),
berghofe@21024
   407
             EVERY (map (fn prem =>
berghofe@21024
   408
               DEPTH_SOLVE_1 (ares_tac [rewrite_rule rec_preds_defs prem, conjI] 1)) (tl prems))])
berghofe@36642
   409
          |> singleton (ProofContext.export ctxt'' ctxt'''),
berghofe@34986
   410
         map #2 c_intrs, length Ts)
berghofe@21024
   411
      end
berghofe@21024
   412
berghofe@21024
   413
   in map prove_elim cs end;
berghofe@5094
   414
bulwahn@37734
   415
(* prove simplification equations *)
wenzelm@6424
   416
wenzelm@37901
   417
fun prove_eqs quiet_mode cs params intr_ts intrs (elims: (thm * bstring list * int) list) ctxt ctxt'' =
bulwahn@37734
   418
  let
bulwahn@37734
   419
    val _ = clean_message quiet_mode "  Proving the simplification rules ...";
bulwahn@37734
   420
    
bulwahn@37734
   421
    fun dest_intr r =
bulwahn@37734
   422
      (the (dest_predicate cs params (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))),
bulwahn@37734
   423
       Logic.strip_assums_hyp r, Logic.strip_params r);
bulwahn@37734
   424
    val intr_ts' = map dest_intr intr_ts;
wenzelm@37901
   425
    fun prove_eq c (elim: thm * 'a * 'b) =
bulwahn@37734
   426
      let
bulwahn@37734
   427
        val Ts = arg_types_of (length params) c;
bulwahn@37734
   428
        val (anames, ctxt') = Variable.variant_fixes (mk_names "a" (length Ts)) ctxt;
bulwahn@37734
   429
        val frees = map Free (anames ~~ Ts);
bulwahn@37734
   430
        val c_intrs = filter (equal c o #1 o #1 o #1) (intr_ts' ~~ intrs);
bulwahn@37734
   431
        fun mk_intr_conj (((_, _, us, _), ts, params'), _) =
bulwahn@37734
   432
          let
bulwahn@37734
   433
            fun list_ex ([], t) = t
bulwahn@37734
   434
              | list_ex ((a,T)::vars, t) =
bulwahn@37734
   435
                 (HOLogic.exists_const T) $ (Abs(a, T, list_ex(vars,t)));
bulwahn@37734
   436
            val conjs = map2 (curry HOLogic.mk_eq) frees us @ (map HOLogic.dest_Trueprop ts)
bulwahn@37734
   437
          in
bulwahn@37734
   438
            list_ex (params', if null conjs then @{term True} else foldr1 HOLogic.mk_conj conjs)
bulwahn@37734
   439
          end;
bulwahn@37734
   440
        val lhs = list_comb (c, params @ frees)
bulwahn@37734
   441
        val rhs =
bulwahn@37734
   442
          if null c_intrs then @{term False} else foldr1 HOLogic.mk_disj (map mk_intr_conj c_intrs)
bulwahn@37734
   443
        val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs))
bulwahn@37734
   444
        fun prove_intr1 (i, _) = Subgoal.FOCUS_PREMS (fn {params, prems, ...} =>
bulwahn@37734
   445
            let
bulwahn@37734
   446
              val (prems', last_prem) = split_last prems
bulwahn@37734
   447
            in
bulwahn@37734
   448
              EVERY1 (select_disj (length c_intrs) (i + 1))
bulwahn@37734
   449
              THEN EVERY (replicate (length params) (rtac @{thm exI} 1))
bulwahn@37734
   450
              THEN EVERY (map (fn prem => (rtac @{thm conjI} 1 THEN rtac prem 1)) prems')
bulwahn@37734
   451
              THEN rtac last_prem 1
bulwahn@37734
   452
            end) ctxt' 1
bulwahn@37734
   453
        fun prove_intr2 (((_, _, us, _), ts, params'), intr) =
bulwahn@37734
   454
          EVERY (replicate (length params') (etac @{thm exE} 1))
bulwahn@37734
   455
          THEN EVERY (replicate (length ts + length us - 1) (etac @{thm conjE} 1))
bulwahn@37734
   456
          THEN Subgoal.FOCUS_PREMS (fn {params, prems, ...} =>
bulwahn@37734
   457
            let
bulwahn@37734
   458
              val (eqs, prems') = chop (length us) prems
bulwahn@37734
   459
              val rew_thms = map (fn th => th RS @{thm eq_reflection}) eqs
bulwahn@37734
   460
            in
bulwahn@37734
   461
              rewrite_goal_tac rew_thms 1
bulwahn@37734
   462
              THEN rtac intr 1
bulwahn@37734
   463
              THEN (EVERY (map (fn p => rtac p 1) prems'))              
bulwahn@37734
   464
            end) ctxt' 1 
bulwahn@37734
   465
      in
bulwahn@37734
   466
        Skip_Proof.prove ctxt' [] [] eq (fn {...} =>
bulwahn@37734
   467
          rtac @{thm iffI} 1 THEN etac (#1 elim) 1
bulwahn@37734
   468
          THEN EVERY (map_index prove_intr1 c_intrs)
bulwahn@37734
   469
          THEN (if null c_intrs then etac @{thm FalseE} 1 else
bulwahn@37734
   470
            let val (c_intrs', last_c_intr) = split_last c_intrs in
bulwahn@37734
   471
              EVERY (map (fn ci => etac @{thm disjE} 1 THEN prove_intr2 ci) c_intrs')
bulwahn@37734
   472
              THEN prove_intr2 last_c_intr
bulwahn@37734
   473
            end))
bulwahn@37734
   474
        |> rulify
bulwahn@37734
   475
        |> singleton (ProofContext.export ctxt' ctxt'')
bulwahn@37734
   476
      end;  
bulwahn@37734
   477
  in
bulwahn@37734
   478
    map2 prove_eq cs elims
bulwahn@37734
   479
  end;
bulwahn@37734
   480
  
wenzelm@10735
   481
(* derivation of simplified elimination rules *)
berghofe@5094
   482
wenzelm@11682
   483
local
wenzelm@11682
   484
wenzelm@11682
   485
(*delete needless equality assumptions*)
wenzelm@29064
   486
val refl_thin = Goal.prove_global @{theory HOL} [] [] @{prop "!!P. a = a ==> P ==> P"}
haftmann@22838
   487
  (fn _ => assume_tac 1);
berghofe@21024
   488
val elim_rls = [asm_rl, FalseE, refl_thin, conjE, exE];
wenzelm@11682
   489
val elim_tac = REPEAT o Tactic.eresolve_tac elim_rls;
wenzelm@11682
   490
berghofe@23762
   491
fun simp_case_tac ss i =
berghofe@23762
   492
  EVERY' [elim_tac, asm_full_simp_tac ss, elim_tac, REPEAT o bound_hyp_subst_tac] i;
wenzelm@21367
   493
wenzelm@11682
   494
in
wenzelm@9598
   495
wenzelm@21367
   496
fun mk_cases ctxt prop =
wenzelm@7107
   497
  let
wenzelm@21367
   498
    val thy = ProofContext.theory_of ctxt;
wenzelm@32149
   499
    val ss = simpset_of ctxt;
wenzelm@21367
   500
wenzelm@21526
   501
    fun err msg =
wenzelm@21526
   502
      error (Pretty.string_of (Pretty.block
wenzelm@24920
   503
        [Pretty.str msg, Pretty.fbrk, Syntax.pretty_term ctxt prop]));
wenzelm@21526
   504
wenzelm@24861
   505
    val elims = Induct.find_casesP ctxt prop;
wenzelm@21367
   506
wenzelm@21367
   507
    val cprop = Thm.cterm_of thy prop;
berghofe@23762
   508
    val tac = ALLGOALS (simp_case_tac ss) THEN prune_params_tac;
wenzelm@21367
   509
    fun mk_elim rl =
wenzelm@36546
   510
      Thm.implies_intr cprop (Tactic.rule_by_tactic ctxt tac (Thm.assume cprop RS rl))
wenzelm@21367
   511
      |> singleton (Variable.export (Variable.auto_fixes prop ctxt) ctxt);
wenzelm@7107
   512
  in
wenzelm@7107
   513
    (case get_first (try mk_elim) elims of
skalberg@15531
   514
      SOME r => r
wenzelm@21526
   515
    | NONE => err "Proposition not an inductive predicate:")
wenzelm@7107
   516
  end;
wenzelm@7107
   517
wenzelm@11682
   518
end;
wenzelm@11682
   519
wenzelm@21367
   520
(* inductive_cases *)
wenzelm@7107
   521
wenzelm@21367
   522
fun gen_inductive_cases prep_att prep_prop args lthy =
wenzelm@9598
   523
  let
wenzelm@21367
   524
    val thy = ProofContext.theory_of lthy;
wenzelm@37957
   525
    val facts = args |> Par_List.map (fn ((a, atts), props) =>
wenzelm@21367
   526
      ((a, map (prep_att thy) atts),
wenzelm@37957
   527
        Par_List.map (Thm.no_attributes o single o mk_cases lthy o prep_prop lthy) props));
wenzelm@33671
   528
  in lthy |> Local_Theory.notes facts |>> map snd end;
berghofe@5094
   529
wenzelm@24509
   530
val inductive_cases = gen_inductive_cases Attrib.intern_src Syntax.read_prop;
wenzelm@24509
   531
val inductive_cases_i = gen_inductive_cases (K I) Syntax.check_prop;
wenzelm@7107
   532
wenzelm@6424
   533
wenzelm@30722
   534
val ind_cases_setup =
wenzelm@30722
   535
  Method.setup @{binding ind_cases}
wenzelm@30722
   536
    (Scan.lift (Scan.repeat1 Args.name_source --
wenzelm@30722
   537
      Scan.optional (Args.$$$ "for" |-- Scan.repeat1 Args.name) []) >>
wenzelm@30722
   538
      (fn (raw_props, fixes) => fn ctxt =>
wenzelm@30722
   539
        let
wenzelm@30722
   540
          val (_, ctxt') = Variable.add_fixes fixes ctxt;
wenzelm@30722
   541
          val props = Syntax.read_props ctxt' raw_props;
wenzelm@30722
   542
          val ctxt'' = fold Variable.declare_term props ctxt';
wenzelm@30722
   543
          val rules = ProofContext.export ctxt'' ctxt (map (mk_cases ctxt'') props)
wenzelm@30722
   544
        in Method.erule 0 rules end))
wenzelm@30722
   545
    "dynamic case analysis on predicates";
wenzelm@9598
   546
bulwahn@37734
   547
(* derivation of simplified equation *)
wenzelm@9598
   548
bulwahn@37734
   549
fun mk_simp_eq ctxt prop =
bulwahn@37734
   550
  let
bulwahn@37734
   551
    val ctxt' = Variable.auto_fixes prop ctxt
bulwahn@38118
   552
    val cname = fst (dest_Const (fst (strip_comb (HOLogic.dest_Trueprop prop))))
bulwahn@37734
   553
    val info = the_inductive ctxt cname
bulwahn@37734
   554
    val eq = nth (#eqs (snd info)) (find_index (fn c => c = cname) (#names (fst info)))
bulwahn@38118
   555
    val lhs_eq = fst (HOLogic.dest_eq (HOLogic.dest_Trueprop (Thm.prop_of eq)))
bulwahn@38118
   556
    val subst = Pattern.match (ProofContext.theory_of ctxt) (lhs_eq, HOLogic.dest_Trueprop prop)
bulwahn@38118
   557
      (Vartab.empty, Vartab.empty)
bulwahn@37734
   558
    val certify = cterm_of (ProofContext.theory_of ctxt)
bulwahn@38118
   559
    val inst = map (fn v => (certify (Var v), certify (Envir.subst_term subst (Var v))))
bulwahn@38118
   560
      (Term.add_vars lhs_eq [])
bulwahn@38118
   561
   in
bulwahn@38118
   562
    cterm_instantiate inst eq
bulwahn@37734
   563
    |> Conv.fconv_rule (Conv.arg_conv (Conv.arg_conv
bulwahn@37734
   564
      (Simplifier.full_rewrite (simpset_of ctxt))))
bulwahn@37734
   565
    |> singleton (Variable.export ctxt' ctxt)
bulwahn@37734
   566
  end
bulwahn@37734
   567
bulwahn@37734
   568
(* inductive simps *)
bulwahn@37734
   569
bulwahn@37734
   570
fun gen_inductive_simps prep_att prep_prop args lthy =
bulwahn@37734
   571
  let
bulwahn@37734
   572
    val thy = ProofContext.theory_of lthy;
bulwahn@37734
   573
    val facts = args |> map (fn ((a, atts), props) =>
bulwahn@37734
   574
      ((a, map (prep_att thy) atts),
bulwahn@37734
   575
        map (Thm.no_attributes o single o mk_simp_eq lthy o prep_prop lthy) props));
bulwahn@37734
   576
  in lthy |> Local_Theory.notes facts |>> map snd end;
bulwahn@37734
   577
bulwahn@37734
   578
val inductive_simps = gen_inductive_simps Attrib.intern_src Syntax.read_prop;
bulwahn@37734
   579
val inductive_simps_i = gen_inductive_simps (K I) Syntax.check_prop;
bulwahn@37734
   580
    
wenzelm@10735
   581
(* prove induction rule *)
berghofe@5094
   582
wenzelm@26477
   583
fun prove_indrule quiet_mode cs argTs bs xs rec_const params intr_ts mono
berghofe@36642
   584
    fp_def rec_preds_defs ctxt ctxt''' =
berghofe@5094
   585
  let
wenzelm@26477
   586
    val _ = clean_message quiet_mode "  Proving the induction rule ...";
wenzelm@20047
   587
    val thy = ProofContext.theory_of ctxt;
berghofe@5094
   588
berghofe@21024
   589
    (* predicates for induction rule *)
berghofe@21024
   590
berghofe@36642
   591
    val (pnames, ctxt') = Variable.variant_fixes (mk_names "P" (length cs)) ctxt;
haftmann@33077
   592
    val preds = map2 (curry Free) pnames
haftmann@33077
   593
      (map (fn c => arg_types_of (length params) c ---> HOLogic.boolT) cs);
berghofe@21024
   594
berghofe@21024
   595
    (* transform an introduction rule into a premise for induction rule *)
berghofe@21024
   596
berghofe@21024
   597
    fun mk_ind_prem r =
berghofe@21024
   598
      let
wenzelm@33669
   599
        fun subst s =
wenzelm@33669
   600
          (case dest_predicate cs params s of
berghofe@21024
   601
            SOME (_, i, ys, (_, Ts)) =>
berghofe@21024
   602
              let
berghofe@21024
   603
                val k = length Ts;
berghofe@21024
   604
                val bs = map Bound (k - 1 downto 0);
berghofe@23762
   605
                val P = list_comb (List.nth (preds, i),
berghofe@23762
   606
                  map (incr_boundvars k) ys @ bs);
berghofe@21024
   607
                val Q = list_abs (mk_names "x" k ~~ Ts,
berghofe@23762
   608
                  HOLogic.mk_binop inductive_conj_name
berghofe@23762
   609
                    (list_comb (incr_boundvars k s, bs), P))
berghofe@21024
   610
              in (Q, case Ts of [] => SOME (s, P) | _ => NONE) end
wenzelm@33669
   611
          | NONE =>
wenzelm@33669
   612
              (case s of
wenzelm@33669
   613
                (t $ u) => (fst (subst t) $ fst (subst u), NONE)
wenzelm@33669
   614
              | (Abs (a, T, t)) => (Abs (a, T, fst (subst t)), NONE)
wenzelm@33669
   615
              | _ => (s, NONE)));
berghofe@7293
   616
wenzelm@33338
   617
        fun mk_prem s prems =
wenzelm@33338
   618
          (case subst s of
wenzelm@33338
   619
            (_, SOME (t, u)) => t :: u :: prems
wenzelm@33338
   620
          | (t, _) => t :: prems);
berghofe@21024
   621
berghofe@21024
   622
        val SOME (_, i, ys, _) = dest_predicate cs params
berghofe@21024
   623
          (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))
berghofe@21024
   624
berghofe@21024
   625
      in list_all_free (Logic.strip_params r,
wenzelm@33338
   626
        Logic.list_implies (map HOLogic.mk_Trueprop (fold_rev mk_prem
wenzelm@33338
   627
          (map HOLogic.dest_Trueprop (Logic.strip_assums_hyp r)) []),
berghofe@21024
   628
            HOLogic.mk_Trueprop (list_comb (List.nth (preds, i), ys))))
berghofe@21024
   629
      end;
berghofe@21024
   630
berghofe@21024
   631
    val ind_prems = map mk_ind_prem intr_ts;
berghofe@21024
   632
wenzelm@21526
   633
berghofe@21024
   634
    (* make conclusions for induction rules *)
berghofe@21024
   635
berghofe@21024
   636
    val Tss = map (binder_types o fastype_of) preds;
berghofe@21024
   637
    val (xnames, ctxt'') =
berghofe@21024
   638
      Variable.variant_fixes (mk_names "x" (length (flat Tss))) ctxt';
berghofe@21024
   639
    val mutual_ind_concl = HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
berghofe@21024
   640
        (map (fn (((xnames, Ts), c), P) =>
berghofe@21024
   641
           let val frees = map Free (xnames ~~ Ts)
berghofe@21024
   642
           in HOLogic.mk_imp
berghofe@21024
   643
             (list_comb (c, params @ frees), list_comb (P, frees))
berghofe@21024
   644
           end) (unflat Tss xnames ~~ Tss ~~ cs ~~ preds)));
berghofe@5094
   645
paulson@13626
   646
berghofe@5094
   647
    (* make predicate for instantiation of abstract induction rule *)
berghofe@5094
   648
berghofe@21024
   649
    val ind_pred = fold_rev lambda (bs @ xs) (foldr1 HOLogic.mk_conj
wenzelm@33338
   650
      (map_index (fn (i, P) => fold_rev (curry HOLogic.mk_imp)
wenzelm@33338
   651
         (make_bool_args HOLogic.mk_not I bs i)
wenzelm@33338
   652
         (list_comb (P, make_args' argTs xs (binder_types (fastype_of P))))) preds));
berghofe@5094
   653
berghofe@5094
   654
    val ind_concl = HOLogic.mk_Trueprop
haftmann@35092
   655
      (HOLogic.mk_binrel @{const_name Orderings.less_eq} (rec_const, ind_pred));
berghofe@5094
   656
haftmann@32652
   657
    val raw_fp_induct = (mono RS (fp_def RS @{thm def_lfp_induct}));
paulson@13626
   658
wenzelm@32970
   659
    val induct = Skip_Proof.prove ctxt'' [] ind_prems ind_concl
wenzelm@20248
   660
      (fn {prems, ...} => EVERY
wenzelm@17985
   661
        [rewrite_goals_tac [inductive_conj_def],
berghofe@21024
   662
         DETERM (rtac raw_fp_induct 1),
haftmann@32652
   663
         REPEAT (resolve_tac [@{thm le_funI}, @{thm le_boolI}] 1),
haftmann@32610
   664
         rewrite_goals_tac simp_thms'',
berghofe@21024
   665
         (*This disjE separates out the introduction rules*)
berghofe@21024
   666
         REPEAT (FIRSTGOAL (eresolve_tac [disjE, exE, FalseE])),
berghofe@5094
   667
         (*Now break down the individual cases.  No disjE here in case
berghofe@5094
   668
           some premise involves disjunction.*)
paulson@13747
   669
         REPEAT (FIRSTGOAL (etac conjE ORELSE' bound_hyp_subst_tac)),
berghofe@21024
   670
         REPEAT (FIRSTGOAL
berghofe@21024
   671
           (resolve_tac [conjI, impI] ORELSE' (etac notE THEN' atac))),
berghofe@21024
   672
         EVERY (map (fn prem => DEPTH_SOLVE_1 (ares_tac [rewrite_rule
haftmann@32610
   673
             (inductive_conj_def :: rec_preds_defs @ simp_thms'') prem,
berghofe@22980
   674
           conjI, refl] 1)) prems)]);
berghofe@5094
   675
wenzelm@32970
   676
    val lemma = Skip_Proof.prove ctxt'' [] []
wenzelm@17985
   677
      (Logic.mk_implies (ind_concl, mutual_ind_concl)) (fn _ => EVERY
berghofe@21024
   678
        [rewrite_goals_tac rec_preds_defs,
berghofe@5094
   679
         REPEAT (EVERY
berghofe@5094
   680
           [REPEAT (resolve_tac [conjI, impI] 1),
haftmann@32652
   681
            REPEAT (eresolve_tac [@{thm le_funE}, @{thm le_boolE}] 1),
berghofe@21024
   682
            atac 1,
berghofe@21024
   683
            rewrite_goals_tac simp_thms',
berghofe@21024
   684
            atac 1])])
berghofe@5094
   685
berghofe@36642
   686
  in singleton (ProofContext.export ctxt'' ctxt''') (induct RS lemma) end;
berghofe@5094
   687
wenzelm@6424
   688
wenzelm@6424
   689
berghofe@21024
   690
(** specification of (co)inductive predicates **)
wenzelm@10729
   691
wenzelm@33458
   692
fun mk_ind_def quiet_mode skip_mono fork_mono alt_name coind
wenzelm@33458
   693
    cs intr_ts monos params cnames_syn lthy =
wenzelm@33458
   694
  let
haftmann@24915
   695
    val fp_name = if coind then @{const_name Inductive.gfp} else @{const_name Inductive.lfp};
berghofe@5094
   696
haftmann@33077
   697
    val argTs = fold (combine (op =) o arg_types_of (length params)) cs [];
berghofe@21024
   698
    val k = log 2 1 (length cs);
berghofe@21024
   699
    val predT = replicate k HOLogic.boolT ---> argTs ---> HOLogic.boolT;
wenzelm@33458
   700
    val p :: xs = map Free (Variable.variant_frees lthy intr_ts
berghofe@21024
   701
      (("p", predT) :: (mk_names "x" (length argTs) ~~ argTs)));
wenzelm@33458
   702
    val bs = map Free (Variable.variant_frees lthy (p :: xs @ intr_ts)
berghofe@21024
   703
      (map (rpair HOLogic.boolT) (mk_names "b" k)));
berghofe@21024
   704
wenzelm@33458
   705
    fun subst t =
wenzelm@33458
   706
      (case dest_predicate cs params t of
berghofe@21024
   707
        SOME (_, i, ts, (Ts, Us)) =>
berghofe@23762
   708
          let
berghofe@23762
   709
            val l = length Us;
wenzelm@33669
   710
            val zs = map Bound (l - 1 downto 0);
berghofe@21024
   711
          in
berghofe@21024
   712
            list_abs (map (pair "z") Us, list_comb (p,
berghofe@23762
   713
              make_bool_args' bs i @ make_args argTs
berghofe@23762
   714
                ((map (incr_boundvars l) ts ~~ Ts) @ (zs ~~ Us))))
berghofe@21024
   715
          end
wenzelm@33669
   716
      | NONE =>
wenzelm@33669
   717
          (case t of
wenzelm@33669
   718
            t1 $ t2 => subst t1 $ subst t2
wenzelm@33669
   719
          | Abs (x, T, u) => Abs (x, T, subst u)
wenzelm@33669
   720
          | _ => t));
berghofe@5149
   721
berghofe@5094
   722
    (* transform an introduction rule into a conjunction  *)
berghofe@21024
   723
    (*   [| p_i t; ... |] ==> p_j u                       *)
berghofe@5094
   724
    (* is transformed into                                *)
berghofe@21024
   725
    (*   b_j & x_j = u & p b_j t & ...                    *)
berghofe@5094
   726
berghofe@5094
   727
    fun transform_rule r =
berghofe@5094
   728
      let
berghofe@21024
   729
        val SOME (_, i, ts, (Ts, _)) = dest_predicate cs params
berghofe@21048
   730
          (HOLogic.dest_Trueprop (Logic.strip_assums_concl r));
berghofe@21048
   731
        val ps = make_bool_args HOLogic.mk_not I bs i @
berghofe@21048
   732
          map HOLogic.mk_eq (make_args' argTs xs Ts ~~ ts) @
berghofe@21048
   733
          map (subst o HOLogic.dest_Trueprop)
berghofe@21048
   734
            (Logic.strip_assums_hyp r)
wenzelm@33338
   735
      in
wenzelm@33338
   736
        fold_rev (fn (x, T) => fn P => HOLogic.exists_const T $ Abs (x, T, P))
wenzelm@33338
   737
          (Logic.strip_params r)
wenzelm@33338
   738
          (if null ps then HOLogic.true_const else foldr1 HOLogic.mk_conj ps)
berghofe@5094
   739
      end
berghofe@5094
   740
berghofe@5094
   741
    (* make a disjunction of all introduction rules *)
berghofe@5094
   742
berghofe@21024
   743
    val fp_fun = fold_rev lambda (p :: bs @ xs)
berghofe@21024
   744
      (if null intr_ts then HOLogic.false_const
berghofe@21024
   745
       else foldr1 HOLogic.mk_disj (map transform_rule intr_ts));
berghofe@5094
   746
berghofe@21024
   747
    (* add definiton of recursive predicates to theory *)
berghofe@5094
   748
wenzelm@28083
   749
    val rec_name =
haftmann@28965
   750
      if Binding.is_empty alt_name then
wenzelm@30223
   751
        Binding.name (space_implode "_" (map (Binding.name_of o fst) cnames_syn))
wenzelm@28083
   752
      else alt_name;
berghofe@5094
   753
wenzelm@33458
   754
    val ((rec_const, (_, fp_def)), lthy') = lthy
wenzelm@33671
   755
      |> Local_Theory.conceal
wenzelm@33766
   756
      |> Local_Theory.define
berghofe@21024
   757
        ((rec_name, case cnames_syn of [(_, syn)] => syn | _ => NoSyn),
blanchet@33577
   758
         ((Binding.empty, [Attrib.internal (K Nitpick_Defs.add)]),
blanchet@33577
   759
         fold_rev lambda params
wenzelm@33278
   760
           (Const (fp_name, (predT --> predT) --> predT) $ fp_fun)))
wenzelm@33671
   761
      ||> Local_Theory.restore_naming lthy;
berghofe@21024
   762
    val fp_def' = Simplifier.rewrite (HOL_basic_ss addsimps [fp_def])
wenzelm@33458
   763
      (cterm_of (ProofContext.theory_of lthy') (list_comb (rec_const, params)));
wenzelm@33278
   764
    val specs =
wenzelm@33278
   765
      if length cs < 2 then []
wenzelm@33278
   766
      else
wenzelm@33278
   767
        map_index (fn (i, (name_mx, c)) =>
wenzelm@33278
   768
          let
wenzelm@33278
   769
            val Ts = arg_types_of (length params) c;
wenzelm@33458
   770
            val xs = map Free (Variable.variant_frees lthy intr_ts
wenzelm@33278
   771
              (mk_names "x" (length Ts) ~~ Ts))
wenzelm@33278
   772
          in
wenzelm@33278
   773
            (name_mx, (Attrib.empty_binding, fold_rev lambda (params @ xs)
wenzelm@33278
   774
              (list_comb (rec_const, params @ make_bool_args' bs i @
wenzelm@33278
   775
                make_args argTs (xs ~~ Ts)))))
wenzelm@33278
   776
          end) (cnames_syn ~~ cs);
wenzelm@33458
   777
    val (consts_defs, lthy'') = lthy'
wenzelm@33671
   778
      |> Local_Theory.conceal
wenzelm@33766
   779
      |> fold_map Local_Theory.define specs
wenzelm@33671
   780
      ||> Local_Theory.restore_naming lthy';
berghofe@21024
   781
    val preds = (case cs of [_] => [rec_const] | _ => map #1 consts_defs);
berghofe@5094
   782
berghofe@36642
   783
    val (_, lthy''') = Variable.add_fixes (map (fst o dest_Free) params) lthy'';
berghofe@36642
   784
    val mono = prove_mono quiet_mode skip_mono fork_mono predT fp_fun monos lthy''';
berghofe@36642
   785
    val (_, lthy'''') =
berghofe@36642
   786
      Local_Theory.note (apfst Binding.conceal Attrib.empty_binding,
berghofe@36642
   787
        ProofContext.export lthy''' lthy'' [mono]) lthy'';
berghofe@5094
   788
berghofe@36642
   789
  in (lthy'''', lthy''', rec_name, mono, fp_def', map (#2 o #2) consts_defs,
berghofe@21024
   790
    list_comb (rec_const, params), preds, argTs, bs, xs)
berghofe@21024
   791
  end;
berghofe@5094
   792
wenzelm@33669
   793
fun declare_rules rec_binding coind no_ind cnames
bulwahn@37734
   794
    preds intrs intr_bindings intr_atts elims eqs raw_induct lthy =
berghofe@23762
   795
  let
wenzelm@30223
   796
    val rec_name = Binding.name_of rec_binding;
haftmann@32773
   797
    fun rec_qualified qualified = Binding.qualify qualified rec_name;
wenzelm@30223
   798
    val intr_names = map Binding.name_of intr_bindings;
wenzelm@33368
   799
    val ind_case_names = Rule_Cases.case_names intr_names;
berghofe@23762
   800
    val induct =
berghofe@23762
   801
      if coind then
wenzelm@33368
   802
        (raw_induct, [Rule_Cases.case_names [rec_name],
wenzelm@33368
   803
          Rule_Cases.case_conclusion (rec_name, intr_names),
wenzelm@33368
   804
          Rule_Cases.consumes 1, Induct.coinduct_pred (hd cnames)])
berghofe@23762
   805
      else if no_ind orelse length cnames > 1 then
wenzelm@33368
   806
        (raw_induct, [ind_case_names, Rule_Cases.consumes 0])
wenzelm@33368
   807
      else (raw_induct RSN (2, rev_mp), [ind_case_names, Rule_Cases.consumes 1]);
berghofe@23762
   808
wenzelm@33458
   809
    val (intrs', lthy1) =
wenzelm@33458
   810
      lthy |>
bulwahn@35757
   811
      Spec_Rules.add
bulwahn@35757
   812
        (if coind then Spec_Rules.Co_Inductive else Spec_Rules.Inductive) (preds, intrs) |>
wenzelm@33671
   813
      Local_Theory.notes
wenzelm@33278
   814
        (map (rec_qualified false) intr_bindings ~~ intr_atts ~~
wenzelm@33278
   815
          map (fn th => [([th],
blanchet@37264
   816
           [Attrib.internal (K (Context_Rules.intro_query NONE))])]) intrs) |>>
berghofe@24744
   817
      map (hd o snd);
wenzelm@33458
   818
    val (((_, elims'), (_, [induct'])), lthy2) =
wenzelm@33458
   819
      lthy1 |>
wenzelm@33671
   820
      Local_Theory.note ((rec_qualified true (Binding.name "intros"), []), intrs') ||>>
berghofe@34986
   821
      fold_map (fn (name, (elim, cases, k)) =>
wenzelm@33671
   822
        Local_Theory.note
wenzelm@33458
   823
          ((Binding.qualify true (Long_Name.base_name name) (Binding.name "cases"),
wenzelm@33458
   824
            [Attrib.internal (K (Rule_Cases.case_names cases)),
wenzelm@33458
   825
             Attrib.internal (K (Rule_Cases.consumes 1)),
berghofe@34986
   826
             Attrib.internal (K (Rule_Cases.constraints k)),
wenzelm@33458
   827
             Attrib.internal (K (Induct.cases_pred name)),
wenzelm@33458
   828
             Attrib.internal (K (Context_Rules.elim_query NONE))]), [elim]) #>
berghofe@23762
   829
        apfst (hd o snd)) (if null elims then [] else cnames ~~ elims) ||>>
wenzelm@33671
   830
      Local_Theory.note
haftmann@32773
   831
        ((rec_qualified true (Binding.name (coind_prefix coind ^ "induct")),
wenzelm@28107
   832
          map (Attrib.internal o K) (#2 induct)), [rulify (#1 induct)]);
berghofe@23762
   833
bulwahn@37734
   834
    val (eqs', lthy3) = lthy2 |> 
bulwahn@37734
   835
      fold_map (fn (name, eq) => Local_Theory.note
bulwahn@37734
   836
          ((Binding.qualify true (Long_Name.base_name name) (Binding.name "simps"), []), [eq])
bulwahn@37734
   837
          #> apfst (hd o snd))
bulwahn@37734
   838
        (if null eqs then [] else (cnames ~~ eqs))
bulwahn@37734
   839
    val (inducts, lthy4) =
bulwahn@37734
   840
      if no_ind orelse coind then ([], lthy3)
wenzelm@33458
   841
      else
bulwahn@37734
   842
        let val inducts = cnames ~~ Project_Rule.projects lthy3 (1 upto length cnames) induct' in
bulwahn@37734
   843
          lthy3 |>
wenzelm@33671
   844
          Local_Theory.notes [((rec_qualified true (Binding.name "inducts"), []),
wenzelm@33458
   845
            inducts |> map (fn (name, th) => ([th],
wenzelm@33458
   846
              [Attrib.internal (K ind_case_names),
wenzelm@33458
   847
               Attrib.internal (K (Rule_Cases.consumes 1)),
berghofe@35646
   848
               Attrib.internal (K (Induct.induct_pred name))])))] |>> snd o hd
wenzelm@33458
   849
        end;
bulwahn@37734
   850
  in (intrs', elims', eqs', induct', inducts, lthy4) end;
berghofe@23762
   851
berghofe@26534
   852
type inductive_flags =
wenzelm@33669
   853
  {quiet_mode: bool, verbose: bool, alt_name: binding, coind: bool,
wenzelm@33669
   854
    no_elim: bool, no_ind: bool, skip_mono: bool, fork_mono: bool};
berghofe@26534
   855
berghofe@26534
   856
type add_ind_def =
berghofe@26534
   857
  inductive_flags ->
wenzelm@28084
   858
  term list -> (Attrib.binding * term) list -> thm list ->
haftmann@29581
   859
  term list -> (binding * mixfix) list ->
wenzelm@33458
   860
  local_theory -> inductive_result * local_theory;
berghofe@23762
   861
wenzelm@33669
   862
fun add_ind_def {quiet_mode, verbose, alt_name, coind, no_elim, no_ind, skip_mono, fork_mono}
wenzelm@33458
   863
    cs intros monos params cnames_syn lthy =
berghofe@9072
   864
  let
wenzelm@25288
   865
    val _ = null cnames_syn andalso error "No inductive predicates given";
wenzelm@30223
   866
    val names = map (Binding.name_of o fst) cnames_syn;
wenzelm@26477
   867
    val _ = message (quiet_mode andalso not verbose)
wenzelm@28083
   868
      ("Proofs for " ^ coind_prefix coind ^ "inductive predicate(s) " ^ commas_quote names);
berghofe@9072
   869
wenzelm@33671
   870
    val cnames = map (Local_Theory.full_name lthy o #1) cnames_syn;  (* FIXME *)
berghofe@23762
   871
    val ((intr_names, intr_atts), intr_ts) =
wenzelm@33458
   872
      apfst split_list (split_list (map (check_rule lthy cs params) intros));
berghofe@21024
   873
berghofe@36642
   874
    val (lthy1, lthy2, rec_name, mono, fp_def, rec_preds_defs, rec_const, preds,
wenzelm@29388
   875
      argTs, bs, xs) = mk_ind_def quiet_mode skip_mono fork_mono alt_name coind cs intr_ts
wenzelm@33458
   876
        monos params cnames_syn lthy;
berghofe@9072
   877
wenzelm@26477
   878
    val (intrs, unfold) = prove_intrs quiet_mode coind mono fp_def (length bs + length xs)
berghofe@36642
   879
      intr_ts rec_preds_defs lthy2 lthy1;
wenzelm@33459
   880
    val elims =
wenzelm@33459
   881
      if no_elim then []
wenzelm@33459
   882
      else
wenzelm@33459
   883
        prove_elims quiet_mode cs params intr_ts (map Binding.name_of intr_names)
berghofe@36642
   884
          unfold rec_preds_defs lthy2 lthy1;
berghofe@22605
   885
    val raw_induct = zero_var_indexes
wenzelm@33459
   886
      (if no_ind then Drule.asm_rl
wenzelm@33459
   887
       else if coind then
berghofe@36642
   888
         singleton (ProofContext.export lthy2 lthy1)
wenzelm@35625
   889
           (rotate_prems ~1 (Object_Logic.rulify
wenzelm@28839
   890
             (fold_rule rec_preds_defs
haftmann@32652
   891
               (rewrite_rule simp_thms'''
haftmann@32652
   892
                (mono RS (fp_def RS @{thm def_coinduct}))))))
berghofe@21024
   893
       else
wenzelm@26477
   894
         prove_indrule quiet_mode cs argTs bs xs rec_const params intr_ts mono fp_def
berghofe@36642
   895
           rec_preds_defs lthy2 lthy1);
bulwahn@37734
   896
    val eqs =
bulwahn@37734
   897
      if no_elim then [] else prove_eqs quiet_mode cs params intr_ts intrs elims lthy2 lthy1
berghofe@5094
   898
bulwahn@37734
   899
    val elims' = map (fn (th, ns, i) => (rulify th, ns, i)) elims
bulwahn@37734
   900
    val intrs' = map rulify intrs
bulwahn@37734
   901
bulwahn@37734
   902
    val (intrs'', elims'', eqs', induct, inducts, lthy3) = declare_rules rec_name coind no_ind
bulwahn@37734
   903
      cnames preds intrs' intr_names intr_atts elims' eqs raw_induct lthy1;
berghofe@21048
   904
berghofe@21048
   905
    val result =
berghofe@21048
   906
      {preds = preds,
bulwahn@37734
   907
       intrs = intrs'',
bulwahn@37734
   908
       elims = elims'',
berghofe@21048
   909
       raw_induct = rulify raw_induct,
berghofe@35646
   910
       induct = induct,
bulwahn@37734
   911
       inducts = inducts,
bulwahn@37734
   912
       eqs = eqs'};
wenzelm@21367
   913
berghofe@36642
   914
    val lthy4 = lthy3
wenzelm@33671
   915
      |> Local_Theory.declaration false (fn phi =>
wenzelm@25380
   916
        let val result' = morph_result phi result;
wenzelm@25380
   917
        in put_inductives cnames (*global names!?*) ({names = cnames, coind = coind}, result') end);
berghofe@36642
   918
  in (result, lthy4) end;
berghofe@5094
   919
wenzelm@6424
   920
wenzelm@10735
   921
(* external interfaces *)
berghofe@5094
   922
wenzelm@26477
   923
fun gen_add_inductive_i mk_def
wenzelm@33669
   924
    (flags as {quiet_mode, verbose, alt_name, coind, no_elim, no_ind, skip_mono, fork_mono})
wenzelm@25029
   925
    cnames_syn pnames spec monos lthy =
berghofe@5094
   926
  let
wenzelm@25029
   927
    val thy = ProofContext.theory_of lthy;
wenzelm@6424
   928
    val _ = Theory.requires thy "Inductive" (coind_prefix coind ^ "inductive definitions");
berghofe@5094
   929
berghofe@21766
   930
wenzelm@25029
   931
    (* abbrevs *)
wenzelm@25029
   932
wenzelm@30223
   933
    val (_, ctxt1) = Variable.add_fixes (map (Binding.name_of o fst o fst) cnames_syn) lthy;
berghofe@21766
   934
wenzelm@25029
   935
    fun get_abbrev ((name, atts), t) =
wenzelm@25029
   936
      if can (Logic.strip_assums_concl #> Logic.dest_equals) t then
wenzelm@25029
   937
        let
haftmann@29006
   938
          val _ = Binding.is_empty name andalso null atts orelse
wenzelm@25029
   939
            error "Abbreviations may not have names or attributes";
wenzelm@35624
   940
          val ((x, T), rhs) = Local_Defs.abs_def (snd (Local_Defs.cert_def ctxt1 t));
wenzelm@28083
   941
          val var =
wenzelm@30223
   942
            (case find_first (fn ((c, _), _) => Binding.name_of c = x) cnames_syn of
wenzelm@25029
   943
              NONE => error ("Undeclared head of abbreviation " ^ quote x)
wenzelm@28083
   944
            | SOME ((b, T'), mx) =>
wenzelm@25029
   945
                if T <> T' then error ("Bad type specification for abbreviation " ^ quote x)
wenzelm@28083
   946
                else (b, mx));
wenzelm@28083
   947
        in SOME (var, rhs) end
wenzelm@25029
   948
      else NONE;
berghofe@21766
   949
wenzelm@25029
   950
    val abbrevs = map_filter get_abbrev spec;
wenzelm@30223
   951
    val bs = map (Binding.name_of o fst o fst) abbrevs;
wenzelm@25029
   952
berghofe@21766
   953
wenzelm@25029
   954
    (* predicates *)
berghofe@21766
   955
wenzelm@25029
   956
    val pre_intros = filter_out (is_some o get_abbrev) spec;
wenzelm@30223
   957
    val cnames_syn' = filter_out (member (op =) bs o Binding.name_of o fst o fst) cnames_syn;
wenzelm@30223
   958
    val cs = map (Free o apfst Binding.name_of o fst) cnames_syn';
wenzelm@25029
   959
    val ps = map Free pnames;
berghofe@5094
   960
wenzelm@30223
   961
    val (_, ctxt2) = lthy |> Variable.add_fixes (map (Binding.name_of o fst o fst) cnames_syn');
wenzelm@35624
   962
    val _ = map (fn abbr => Local_Defs.fixed_abbrev abbr ctxt2) abbrevs;
wenzelm@35624
   963
    val ctxt3 = ctxt2 |> fold (snd oo Local_Defs.fixed_abbrev) abbrevs;
wenzelm@25143
   964
    val expand = Assumption.export_term ctxt3 lthy #> ProofContext.cert_term lthy;
wenzelm@25029
   965
wenzelm@25029
   966
    fun close_rule r = list_all_free (rev (fold_aterms
berghofe@21024
   967
      (fn t as Free (v as (s, _)) =>
wenzelm@25029
   968
          if Variable.is_fixed ctxt1 s orelse
wenzelm@25029
   969
            member (op =) ps t then I else insert (op =) v
wenzelm@25029
   970
        | _ => I) r []), r);
berghofe@5094
   971
haftmann@26736
   972
    val intros = map (apsnd (Syntax.check_term lthy #> close_rule #> expand)) pre_intros;
wenzelm@25029
   973
    val preds = map (fn ((c, _), mx) => (c, mx)) cnames_syn';
berghofe@21048
   974
  in
wenzelm@25029
   975
    lthy
wenzelm@25029
   976
    |> mk_def flags cs intros monos ps preds
wenzelm@33671
   977
    ||> fold (snd oo Local_Theory.abbrev Syntax.mode_default) abbrevs
berghofe@21048
   978
  end;
berghofe@5094
   979
wenzelm@29388
   980
fun gen_add_inductive mk_def verbose coind cnames_syn pnames_syn intro_srcs raw_monos int lthy =
berghofe@5094
   981
  let
wenzelm@30486
   982
    val ((vars, intrs), _) = lthy
wenzelm@30486
   983
      |> ProofContext.set_mode ProofContext.mode_abbrev
wenzelm@30486
   984
      |> Specification.read_spec (cnames_syn @ pnames_syn) intro_srcs;
wenzelm@24721
   985
    val (cs, ps) = chop (length cnames_syn) vars;
wenzelm@24721
   986
    val monos = Attrib.eval_thms lthy raw_monos;
wenzelm@33669
   987
    val flags = {quiet_mode = false, verbose = verbose, alt_name = Binding.empty,
wenzelm@33669
   988
      coind = coind, no_elim = false, no_ind = false, skip_mono = false, fork_mono = not int};
wenzelm@26128
   989
  in
wenzelm@26128
   990
    lthy
wenzelm@30223
   991
    |> gen_add_inductive_i mk_def flags cs (map (apfst Binding.name_of o fst) ps) intrs monos
wenzelm@26128
   992
  end;
berghofe@5094
   993
berghofe@23762
   994
val add_inductive_i = gen_add_inductive_i add_ind_def;
berghofe@23762
   995
val add_inductive = gen_add_inductive add_ind_def;
berghofe@23762
   996
wenzelm@33726
   997
fun add_inductive_global flags cnames_syn pnames pre_intros monos thy =
wenzelm@25380
   998
  let
haftmann@29006
   999
    val name = Sign.full_name thy (fst (fst (hd cnames_syn)));
wenzelm@25380
  1000
    val ctxt' = thy
haftmann@38388
  1001
      |> Named_Target.theory_init
wenzelm@25380
  1002
      |> add_inductive_i flags cnames_syn pnames pre_intros monos |> snd
wenzelm@33671
  1003
      |> Local_Theory.exit;
wenzelm@25380
  1004
    val info = #2 (the_inductive ctxt' name);
wenzelm@25380
  1005
  in (info, ProofContext.theory_of ctxt') end;
wenzelm@6424
  1006
wenzelm@6424
  1007
berghofe@22789
  1008
(* read off arities of inductive predicates from raw induction rule *)
berghofe@22789
  1009
fun arities_of induct =
berghofe@22789
  1010
  map (fn (_ $ t $ u) =>
berghofe@22789
  1011
      (fst (dest_Const (head_of t)), length (snd (strip_comb u))))
berghofe@22789
  1012
    (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
berghofe@22789
  1013
berghofe@22789
  1014
(* read off parameters of inductive predicate from raw induction rule *)
berghofe@22789
  1015
fun params_of induct =
berghofe@22789
  1016
  let
berghofe@22789
  1017
    val (_ $ t $ u :: _) =
berghofe@22789
  1018
      HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct));
berghofe@22789
  1019
    val (_, ts) = strip_comb t;
berghofe@22789
  1020
    val (_, us) = strip_comb u
berghofe@22789
  1021
  in
berghofe@22789
  1022
    List.take (ts, length ts - length us)
berghofe@22789
  1023
  end;
berghofe@22789
  1024
berghofe@22789
  1025
val pname_of_intr =
berghofe@22789
  1026
  concl_of #> HOLogic.dest_Trueprop #> head_of #> dest_Const #> fst;
berghofe@22789
  1027
berghofe@22789
  1028
(* partition introduction rules according to predicate name *)
berghofe@25822
  1029
fun gen_partition_rules f induct intros =
berghofe@25822
  1030
  fold_rev (fn r => AList.map_entry op = (pname_of_intr (f r)) (cons r)) intros
berghofe@22789
  1031
    (map (rpair [] o fst) (arities_of induct));
berghofe@22789
  1032
berghofe@25822
  1033
val partition_rules = gen_partition_rules I;
berghofe@25822
  1034
fun partition_rules' induct = gen_partition_rules fst induct;
berghofe@25822
  1035
berghofe@22789
  1036
fun unpartition_rules intros xs =
berghofe@22789
  1037
  fold_map (fn r => AList.map_entry_yield op = (pname_of_intr r)
berghofe@22789
  1038
    (fn x :: xs => (x, xs)) #>> the) intros xs |> fst;
berghofe@22789
  1039
berghofe@22789
  1040
(* infer order of variables in intro rules from order of quantifiers in elim rule *)
berghofe@22789
  1041
fun infer_intro_vars elim arity intros =
berghofe@22789
  1042
  let
berghofe@22789
  1043
    val thy = theory_of_thm elim;
berghofe@22789
  1044
    val _ :: cases = prems_of elim;
berghofe@22789
  1045
    val used = map (fst o fst) (Term.add_vars (prop_of elim) []);
berghofe@22789
  1046
    fun mtch (t, u) =
berghofe@22789
  1047
      let
berghofe@22789
  1048
        val params = Logic.strip_params t;
berghofe@22789
  1049
        val vars = map (Var o apfst (rpair 0))
berghofe@22789
  1050
          (Name.variant_list used (map fst params) ~~ map snd params);
berghofe@22789
  1051
        val ts = map (curry subst_bounds (rev vars))
berghofe@22789
  1052
          (List.drop (Logic.strip_assums_hyp t, arity));
berghofe@22789
  1053
        val us = Logic.strip_imp_prems u;
berghofe@22789
  1054
        val tab = fold (Pattern.first_order_match thy) (ts ~~ us)
berghofe@22789
  1055
          (Vartab.empty, Vartab.empty);
berghofe@22789
  1056
      in
wenzelm@32035
  1057
        map (Envir.subst_term tab) vars
berghofe@22789
  1058
      end
berghofe@22789
  1059
  in
berghofe@22789
  1060
    map (mtch o apsnd prop_of) (cases ~~ intros)
berghofe@22789
  1061
  end;
berghofe@22789
  1062
berghofe@22789
  1063
wenzelm@25978
  1064
wenzelm@6437
  1065
(** package setup **)
wenzelm@6437
  1066
wenzelm@6437
  1067
(* setup theory *)
wenzelm@6437
  1068
wenzelm@8634
  1069
val setup =
wenzelm@30722
  1070
  ind_cases_setup #>
wenzelm@30528
  1071
  Attrib.setup @{binding mono} (Attrib.add_del mono_add mono_del)
wenzelm@30528
  1072
    "declaration of monotonicity rule";
wenzelm@6437
  1073
wenzelm@6437
  1074
wenzelm@6437
  1075
(* outer syntax *)
wenzelm@6424
  1076
wenzelm@36960
  1077
val _ = Keyword.keyword "monos";
wenzelm@24867
  1078
berghofe@23762
  1079
fun gen_ind_decl mk_def coind =
wenzelm@36960
  1080
  Parse.fixes -- Parse.for_fixes --
wenzelm@36954
  1081
  Scan.optional Parse_Spec.where_alt_specs [] --
wenzelm@36960
  1082
  Scan.optional (Parse.$$$ "monos" |-- Parse.!!! Parse_Spec.xthms1) []
wenzelm@26988
  1083
  >> (fn (((preds, params), specs), monos) =>
wenzelm@30486
  1084
      (snd oo gen_add_inductive mk_def true coind preds params specs monos));
berghofe@23762
  1085
berghofe@23762
  1086
val ind_decl = gen_ind_decl add_ind_def;
wenzelm@6424
  1087
wenzelm@33458
  1088
val _ =
wenzelm@36960
  1089
  Outer_Syntax.local_theory' "inductive" "define inductive predicates" Keyword.thy_decl
wenzelm@33458
  1090
    (ind_decl false);
wenzelm@33458
  1091
wenzelm@33458
  1092
val _ =
wenzelm@36960
  1093
  Outer_Syntax.local_theory' "coinductive" "define coinductive predicates" Keyword.thy_decl
wenzelm@33458
  1094
    (ind_decl true);
wenzelm@6723
  1095
wenzelm@24867
  1096
val _ =
wenzelm@36960
  1097
  Outer_Syntax.local_theory "inductive_cases"
wenzelm@36960
  1098
    "create simplified instances of elimination rules (improper)" Keyword.thy_script
wenzelm@36960
  1099
    (Parse.and_list1 Parse_Spec.specs >> (snd oo inductive_cases));
wenzelm@7107
  1100
bulwahn@37734
  1101
val _ =
bulwahn@37734
  1102
  Outer_Syntax.local_theory "inductive_simps"
bulwahn@37734
  1103
    "create simplification rules for inductive predicates" Keyword.thy_script
bulwahn@37734
  1104
    (Parse.and_list1 Parse_Spec.specs >> (snd oo inductive_simps));
bulwahn@37734
  1105
berghofe@5094
  1106
end;