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