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