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