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