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