src/HOL/Tools/inductive_package.ML
author wenzelm
Sat Nov 10 18:36:08 2007 +0100 (2007-11-10)
changeset 25380 03201004c77e
parent 25365 4e7a1dabd7ef
child 25510 38c15efe603b
permissions -rw-r--r--
put_inductives: be permissive about multiple versions
(target names are not necessarily unique);
add_inductive: store info under global (!) name -- very rough approximation of the real thing;
     1 (*  Title:      HOL/Tools/inductive_package.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Author:     Stefan Berghofer and Markus Wenzel, TU Muenchen
     5 
     6 (Co)Inductive Definition module for HOL.
     7 
     8 Features:
     9   * least or greatest fixedpoints
    10   * mutually recursive definitions
    11   * definitions involving arbitrary monotone operators
    12   * automatically proves introduction and elimination rules
    13 
    14   Introduction rules have the form
    15   [| M Pj ti, ..., Q x, ... |] ==> Pk t
    16   where M is some monotone operator (usually the identity)
    17   Q x is any side condition on the free variables
    18   ti, t are any terms
    19   Pj, Pk are two of the predicates being defined in mutual recursion
    20 *)
    21 
    22 signature BASIC_INDUCTIVE_PACKAGE =
    23 sig
    24   val quiet_mode: bool ref
    25   type inductive_result
    26   val morph_result: morphism -> inductive_result -> inductive_result
    27   type inductive_info
    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: ((bstring * Attrib.src list) * string list) list ->
    38     Proof.context -> thm list list * local_theory
    39   val inductive_cases_i: ((bstring * Attrib.src list) * term list) list ->
    40     Proof.context -> thm list list * local_theory
    41   val add_inductive_i:
    42     {verbose: bool, kind: string, alt_name: bstring, coind: bool, no_elim: bool, no_ind: bool} ->
    43     ((string * typ) * mixfix) list ->
    44     (string * typ) list -> ((bstring * Attrib.src list) * term) list -> thm list ->
    45       local_theory -> inductive_result * local_theory
    46   val add_inductive: bool -> bool -> (string * string option * mixfix) list ->
    47     (string * string option * mixfix) list ->
    48     ((bstring * Attrib.src list) * string) list -> (thmref * Attrib.src list) list ->
    49     local_theory -> inductive_result * local_theory
    50   val add_inductive_global:
    51     {verbose: bool, kind: string, alt_name: bstring, coind: bool, no_elim: bool, no_ind: bool} ->
    52     ((string * typ) * mixfix) list -> (string * typ) list ->
    53     ((bstring * Attrib.src list) * term) list -> thm list -> theory -> inductive_result * theory
    54   val arities_of: thm -> (string * int) list
    55   val params_of: thm -> term list
    56   val partition_rules: thm -> thm list -> (string * thm list) list
    57   val unpartition_rules: thm list -> (string * 'a list) list -> 'a list
    58   val infer_intro_vars: thm -> int -> thm list -> term list list
    59   val setup: theory -> theory
    60 end;
    61 
    62 signature INDUCTIVE_PACKAGE =
    63 sig
    64   include BASIC_INDUCTIVE_PACKAGE
    65   type add_ind_def
    66   val declare_rules: string -> bstring -> bool -> bool -> string list ->
    67     thm list -> bstring list -> Attrib.src list list -> (thm * string list) list ->
    68     thm -> local_theory -> thm list * thm list * thm * local_theory
    69   val add_ind_def: add_ind_def
    70   val gen_add_inductive_i: add_ind_def ->
    71     {verbose: bool, kind: string, alt_name: bstring, coind: bool, no_elim: bool, no_ind: bool} ->
    72     ((string * typ) * mixfix) list ->
    73     (string * typ) list -> ((bstring * Attrib.src list) * term) list -> thm list ->
    74       local_theory -> inductive_result * local_theory
    75   val gen_add_inductive: add_ind_def ->
    76     bool -> bool -> (string * string option * mixfix) list ->
    77     (string * string option * mixfix) list ->
    78     ((bstring * Attrib.src list) * string) list -> (thmref * Attrib.src list) list ->
    79     local_theory -> inductive_result * local_theory
    80   val gen_ind_decl: add_ind_def ->
    81     bool -> OuterParse.token list ->
    82     (Toplevel.transition -> Toplevel.transition) * OuterParse.token list
    83 end;
    84 
    85 structure InductivePackage: INDUCTIVE_PACKAGE =
    86 struct
    87 
    88 
    89 (** theory context references **)
    90 
    91 val inductive_forall_name = "HOL.induct_forall";
    92 val inductive_forall_def = thm "induct_forall_def";
    93 val inductive_conj_name = "HOL.induct_conj";
    94 val inductive_conj_def = thm "induct_conj_def";
    95 val inductive_conj = thms "induct_conj";
    96 val inductive_atomize = thms "induct_atomize";
    97 val inductive_rulify = thms "induct_rulify";
    98 val inductive_rulify_fallback = thms "induct_rulify_fallback";
    99 
   100 val notTrueE = TrueI RSN (2, notE);
   101 val notFalseI = Seq.hd (atac 1 notI);
   102 val simp_thms' = map (fn s => mk_meta_eq (the (find_first
   103   (equal (Sign.read_prop HOL.thy s) o prop_of) simp_thms)))
   104   ["(~True) = False", "(~False) = True",
   105    "(True --> ?P) = ?P", "(False --> ?P) = True",
   106    "(?P & True) = ?P", "(True & ?P) = ?P"];
   107 
   108 
   109 
   110 (** context data **)
   111 
   112 type inductive_result =
   113   {preds: term list, elims: thm list, raw_induct: thm,
   114    induct: thm, intrs: thm list};
   115 
   116 fun morph_result phi {preds, elims, raw_induct: thm, induct, intrs} =
   117   let
   118     val term = Morphism.term phi;
   119     val thm = Morphism.thm phi;
   120     val fact = Morphism.fact phi;
   121   in
   122    {preds = map term preds, elims = fact elims, raw_induct = thm raw_induct,
   123     induct = thm induct, intrs = fact intrs}
   124   end;
   125 
   126 type inductive_info =
   127   {names: string list, coind: bool} * inductive_result;
   128 
   129 structure InductiveData = GenericDataFun
   130 (
   131   type T = inductive_info Symtab.table * thm list;
   132   val empty = (Symtab.empty, []);
   133   val extend = I;
   134   fun merge _ ((tab1, monos1), (tab2, monos2)) =
   135     (Symtab.merge (K true) (tab1, tab2), Thm.merge_thms (monos1, monos2));
   136 );
   137 
   138 val get_inductives = InductiveData.get o Context.Proof;
   139 
   140 fun print_inductives ctxt =
   141   let
   142     val (tab, monos) = get_inductives ctxt;
   143     val space = Consts.space_of (ProofContext.consts_of ctxt);
   144   in
   145     [Pretty.strs ("(co)inductives:" :: map #1 (NameSpace.extern_table (space, tab))),
   146      Pretty.big_list "monotonicity rules:" (map (ProofContext.pretty_thm ctxt) monos)]
   147     |> Pretty.chunks |> Pretty.writeln
   148   end;
   149 
   150 
   151 (* get and put data *)
   152 
   153 fun the_inductive ctxt name =
   154   (case Symtab.lookup (#1 (get_inductives ctxt)) name of
   155     NONE => error ("Unknown (co)inductive predicate " ^ quote name)
   156   | SOME info => info);
   157 
   158 fun put_inductives names info = InductiveData.map
   159   (apfst (fold (fn name => Symtab.update (name, info)) names));
   160 
   161 
   162 
   163 (** monotonicity rules **)
   164 
   165 val get_monos = #2 o get_inductives;
   166 val map_monos = InductiveData.map o apsnd;
   167 
   168 fun mk_mono thm =
   169   let
   170     val concl = concl_of thm;
   171     fun eq2mono thm' = [thm' RS (thm' RS eq_to_mono)] @
   172       (case concl of
   173           (_ $ (_ $ (Const ("Not", _) $ _) $ _)) => []
   174         | _ => [thm' RS (thm' RS eq_to_mono2)]);
   175     fun dest_less_concl thm = dest_less_concl (thm RS le_funD)
   176       handle THM _ => thm RS le_boolD
   177   in
   178     case concl of
   179       Const ("==", _) $ _ $ _ => eq2mono (thm RS meta_eq_to_obj_eq)
   180     | _ $ (Const ("op =", _) $ _ $ _) => eq2mono thm
   181     | _ $ (Const ("HOL.ord_class.less_eq", _) $ _ $ _) =>
   182       [dest_less_concl (Seq.hd (REPEAT (FIRSTGOAL
   183          (resolve_tac [le_funI, le_boolI'])) thm))]
   184     | _ => [thm]
   185   end handle THM _ => error ("Bad monotonicity theorem:\n" ^ string_of_thm thm);
   186 
   187 val mono_add = Thm.declaration_attribute (map_monos o fold Thm.add_thm o mk_mono);
   188 val mono_del = Thm.declaration_attribute (map_monos o fold Thm.del_thm o mk_mono);
   189 
   190 
   191 
   192 (** misc utilities **)
   193 
   194 val quiet_mode = ref false;
   195 fun message s = if ! quiet_mode then () else writeln s;
   196 fun clean_message s = if ! quick_and_dirty then () else message s;
   197 
   198 fun coind_prefix true = "co"
   199   | coind_prefix false = "";
   200 
   201 fun log (b:int) m n = if m >= n then 0 else 1 + log b (b * m) n;
   202 
   203 fun make_bool_args f g [] i = []
   204   | make_bool_args f g (x :: xs) i =
   205       (if i mod 2 = 0 then f x else g x) :: make_bool_args f g xs (i div 2);
   206 
   207 fun make_bool_args' xs =
   208   make_bool_args (K HOLogic.false_const) (K HOLogic.true_const) xs;
   209 
   210 fun find_arg T x [] = sys_error "find_arg"
   211   | find_arg T x ((p as (_, (SOME _, _))) :: ps) =
   212       apsnd (cons p) (find_arg T x ps)
   213   | find_arg T x ((p as (U, (NONE, y))) :: ps) =
   214       if (T: typ) = U then (y, (U, (SOME x, y)) :: ps)
   215       else apsnd (cons p) (find_arg T x ps);
   216 
   217 fun make_args Ts xs =
   218   map (fn (T, (NONE, ())) => Const ("arbitrary", T) | (_, (SOME t, ())) => t)
   219     (fold (fn (t, T) => snd o find_arg T t) xs (map (rpair (NONE, ())) Ts));
   220 
   221 fun make_args' Ts xs Us =
   222   fst (fold_map (fn T => find_arg T ()) Us (Ts ~~ map (pair NONE) xs));
   223 
   224 fun dest_predicate cs params t =
   225   let
   226     val k = length params;
   227     val (c, ts) = strip_comb t;
   228     val (xs, ys) = chop k ts;
   229     val i = find_index_eq c cs;
   230   in
   231     if xs = params andalso i >= 0 then
   232       SOME (c, i, ys, chop (length ys)
   233         (List.drop (binder_types (fastype_of c), k)))
   234     else NONE
   235   end;
   236 
   237 fun mk_names a 0 = []
   238   | mk_names a 1 = [a]
   239   | mk_names a n = map (fn i => a ^ string_of_int i) (1 upto n);
   240 
   241 
   242 
   243 (** process rules **)
   244 
   245 local
   246 
   247 fun err_in_rule ctxt name t msg =
   248   error (cat_lines ["Ill-formed introduction rule " ^ quote name,
   249     Syntax.string_of_term ctxt t, msg]);
   250 
   251 fun err_in_prem ctxt name t p msg =
   252   error (cat_lines ["Ill-formed premise", Syntax.string_of_term ctxt p,
   253     "in introduction rule " ^ quote name, Syntax.string_of_term ctxt t, msg]);
   254 
   255 val bad_concl = "Conclusion of introduction rule must be an inductive predicate";
   256 
   257 val bad_ind_occ = "Inductive predicate occurs in argument of inductive predicate";
   258 
   259 val bad_app = "Inductive predicate must be applied to parameter(s) ";
   260 
   261 fun atomize_term thy = MetaSimplifier.rewrite_term thy inductive_atomize [];
   262 
   263 in
   264 
   265 fun check_rule ctxt cs params ((name, att), rule) =
   266   let
   267     val params' = Term.variant_frees rule (Logic.strip_params rule);
   268     val frees = rev (map Free params');
   269     val concl = subst_bounds (frees, Logic.strip_assums_concl rule);
   270     val prems = map (curry subst_bounds frees) (Logic.strip_assums_hyp rule);
   271     val rule' = Logic.list_implies (prems, concl);
   272     val aprems = map (atomize_term (ProofContext.theory_of ctxt)) prems;
   273     val arule = list_all_free (params', Logic.list_implies (aprems, concl));
   274 
   275     fun check_ind err t = case dest_predicate cs params t of
   276         NONE => err (bad_app ^
   277           commas (map (Syntax.string_of_term ctxt) params))
   278       | SOME (_, _, ys, _) =>
   279           if exists (fn c => exists (fn t => Logic.occs (c, t)) ys) cs
   280           then err bad_ind_occ else ();
   281 
   282     fun check_prem' prem t =
   283       if head_of t mem cs then
   284         check_ind (err_in_prem ctxt name rule prem) t
   285       else (case t of
   286           Abs (_, _, t) => check_prem' prem t
   287         | t $ u => (check_prem' prem t; check_prem' prem u)
   288         | _ => ());
   289 
   290     fun check_prem (prem, aprem) =
   291       if can HOLogic.dest_Trueprop aprem then check_prem' prem prem
   292       else err_in_prem ctxt name rule prem "Non-atomic premise";
   293   in
   294     (case concl of
   295        Const ("Trueprop", _) $ t =>
   296          if head_of t mem cs then
   297            (check_ind (err_in_rule ctxt name rule') t;
   298             List.app check_prem (prems ~~ aprems))
   299          else err_in_rule ctxt name rule' bad_concl
   300      | _ => err_in_rule ctxt name rule' bad_concl);
   301     ((name, att), arule)
   302   end;
   303 
   304 val rulify =
   305   hol_simplify inductive_conj
   306   #> hol_simplify inductive_rulify
   307   #> hol_simplify inductive_rulify_fallback
   308   #> MetaSimplifier.norm_hhf;
   309 
   310 end;
   311 
   312 
   313 
   314 (** proofs for (co)inductive predicates **)
   315 
   316 (* prove monotonicity -- NOT subject to quick_and_dirty! *)
   317 
   318 fun prove_mono predT fp_fun monos ctxt =
   319  (message "  Proving monotonicity ...";
   320   Goal.prove ctxt [] []   (*NO quick_and_dirty here!*)
   321     (HOLogic.mk_Trueprop
   322       (Const (@{const_name Orderings.mono}, (predT --> predT) --> HOLogic.boolT) $ fp_fun))
   323     (fn _ => EVERY [rtac @{thm monoI} 1,
   324       REPEAT (resolve_tac [le_funI, le_boolI'] 1),
   325       REPEAT (FIRST
   326         [atac 1,
   327          resolve_tac (List.concat (map mk_mono monos) @ get_monos ctxt) 1,
   328          etac le_funE 1, dtac le_boolD 1])]));
   329 
   330 
   331 (* prove introduction rules *)
   332 
   333 fun prove_intrs coind mono fp_def k params intr_ts rec_preds_defs ctxt =
   334   let
   335     val _ = clean_message "  Proving the introduction rules ...";
   336 
   337     val unfold = funpow k (fn th => th RS fun_cong)
   338       (mono RS (fp_def RS
   339         (if coind then def_gfp_unfold else def_lfp_unfold)));
   340 
   341     fun select_disj 1 1 = []
   342       | select_disj _ 1 = [rtac disjI1]
   343       | select_disj n i = (rtac disjI2)::(select_disj (n - 1) (i - 1));
   344 
   345     val rules = [refl, TrueI, notFalseI, exI, conjI];
   346 
   347     val intrs = map_index (fn (i, intr) => rulify
   348       (SkipProof.prove ctxt (map (fst o dest_Free) params) [] intr (fn _ => EVERY
   349        [rewrite_goals_tac rec_preds_defs,
   350         rtac (unfold RS iffD2) 1,
   351         EVERY1 (select_disj (length intr_ts) (i + 1)),
   352         (*Not ares_tac, since refl must be tried before any equality assumptions;
   353           backtracking may occur if the premises have extra variables!*)
   354         DEPTH_SOLVE_1 (resolve_tac rules 1 APPEND assume_tac 1)]))) intr_ts
   355 
   356   in (intrs, unfold) end;
   357 
   358 
   359 (* prove elimination rules *)
   360 
   361 fun prove_elims cs params intr_ts intr_names unfold rec_preds_defs ctxt =
   362   let
   363     val _ = clean_message "  Proving the elimination rules ...";
   364 
   365     val ([pname], ctxt') = ctxt |>
   366       Variable.add_fixes (map (fst o dest_Free) params) |> snd |>
   367       Variable.variant_fixes ["P"];
   368     val P = HOLogic.mk_Trueprop (Free (pname, HOLogic.boolT));
   369 
   370     fun dest_intr r =
   371       (the (dest_predicate cs params (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))),
   372        Logic.strip_assums_hyp r, Logic.strip_params r);
   373 
   374     val intrs = map dest_intr intr_ts ~~ intr_names;
   375 
   376     val rules1 = [disjE, exE, FalseE];
   377     val rules2 = [conjE, FalseE, notTrueE];
   378 
   379     fun prove_elim c =
   380       let
   381         val Ts = List.drop (binder_types (fastype_of c), length params);
   382         val (anames, ctxt'') = Variable.variant_fixes (mk_names "a" (length Ts)) ctxt';
   383         val frees = map Free (anames ~~ Ts);
   384 
   385         fun mk_elim_prem ((_, _, us, _), ts, params') =
   386           list_all (params',
   387             Logic.list_implies (map (HOLogic.mk_Trueprop o HOLogic.mk_eq)
   388               (frees ~~ us) @ ts, P));
   389         val c_intrs = (List.filter (equal c o #1 o #1 o #1) intrs);
   390         val prems = HOLogic.mk_Trueprop (list_comb (c, params @ frees)) ::
   391            map mk_elim_prem (map #1 c_intrs)
   392       in
   393         (SkipProof.prove ctxt'' [] prems P
   394           (fn {prems, ...} => EVERY
   395             [cut_facts_tac [hd prems] 1,
   396              rewrite_goals_tac rec_preds_defs,
   397              dtac (unfold RS iffD1) 1,
   398              REPEAT (FIRSTGOAL (eresolve_tac rules1)),
   399              REPEAT (FIRSTGOAL (eresolve_tac rules2)),
   400              EVERY (map (fn prem =>
   401                DEPTH_SOLVE_1 (ares_tac [rewrite_rule rec_preds_defs prem, conjI] 1)) (tl prems))])
   402           |> rulify
   403           |> singleton (ProofContext.export ctxt'' ctxt),
   404          map #2 c_intrs)
   405       end
   406 
   407    in map prove_elim cs end;
   408 
   409 
   410 (* derivation of simplified elimination rules *)
   411 
   412 local
   413 
   414 (*delete needless equality assumptions*)
   415 val refl_thin = Goal.prove_global HOL.thy [] [] @{prop "!!P. a = a ==> P ==> P"}
   416   (fn _ => assume_tac 1);
   417 val elim_rls = [asm_rl, FalseE, refl_thin, conjE, exE];
   418 val elim_tac = REPEAT o Tactic.eresolve_tac elim_rls;
   419 
   420 fun simp_case_tac ss i =
   421   EVERY' [elim_tac, asm_full_simp_tac ss, elim_tac, REPEAT o bound_hyp_subst_tac] i;
   422 
   423 in
   424 
   425 fun mk_cases ctxt prop =
   426   let
   427     val thy = ProofContext.theory_of ctxt;
   428     val ss = Simplifier.local_simpset_of ctxt;
   429 
   430     fun err msg =
   431       error (Pretty.string_of (Pretty.block
   432         [Pretty.str msg, Pretty.fbrk, Syntax.pretty_term ctxt prop]));
   433 
   434     val elims = Induct.find_casesP ctxt prop;
   435 
   436     val cprop = Thm.cterm_of thy prop;
   437     val tac = ALLGOALS (simp_case_tac ss) THEN prune_params_tac;
   438     fun mk_elim rl =
   439       Thm.implies_intr cprop (Tactic.rule_by_tactic tac (Thm.assume cprop RS rl))
   440       |> singleton (Variable.export (Variable.auto_fixes prop ctxt) ctxt);
   441   in
   442     (case get_first (try mk_elim) elims of
   443       SOME r => r
   444     | NONE => err "Proposition not an inductive predicate:")
   445   end;
   446 
   447 end;
   448 
   449 
   450 (* inductive_cases *)
   451 
   452 fun gen_inductive_cases prep_att prep_prop args lthy =
   453   let
   454     val thy = ProofContext.theory_of lthy;
   455     val facts = args |> map (fn ((a, atts), props) =>
   456       ((a, map (prep_att thy) atts),
   457         map (Thm.no_attributes o single o mk_cases lthy o prep_prop lthy) props));
   458   in lthy |> LocalTheory.notes Thm.theoremK facts |>> map snd end;
   459 
   460 val inductive_cases = gen_inductive_cases Attrib.intern_src Syntax.read_prop;
   461 val inductive_cases_i = gen_inductive_cases (K I) Syntax.check_prop;
   462 
   463 
   464 fun ind_cases src = Method.syntax (Scan.lift (Scan.repeat1 Args.name --
   465     Scan.optional (Args.$$$ "for" |-- Scan.repeat1 Args.name) [])) src
   466   #> (fn ((raw_props, fixes), ctxt) =>
   467     let
   468       val (_, ctxt') = Variable.add_fixes fixes ctxt;
   469       val props = Syntax.read_props ctxt' raw_props;
   470       val ctxt'' = fold Variable.declare_term props ctxt';
   471       val rules = ProofContext.export ctxt'' ctxt (map (mk_cases ctxt'') props)
   472     in Method.erule 0 rules end);
   473 
   474 
   475 
   476 (* prove induction rule *)
   477 
   478 fun prove_indrule cs argTs bs xs rec_const params intr_ts mono
   479     fp_def rec_preds_defs ctxt =
   480   let
   481     val _ = clean_message "  Proving the induction rule ...";
   482     val thy = ProofContext.theory_of ctxt;
   483 
   484     (* predicates for induction rule *)
   485 
   486     val (pnames, ctxt') = ctxt |>
   487       Variable.add_fixes (map (fst o dest_Free) params) |> snd |>
   488       Variable.variant_fixes (mk_names "P" (length cs));
   489     val preds = map Free (pnames ~~
   490       map (fn c => List.drop (binder_types (fastype_of c), length params) --->
   491         HOLogic.boolT) cs);
   492 
   493     (* transform an introduction rule into a premise for induction rule *)
   494 
   495     fun mk_ind_prem r =
   496       let
   497         fun subst s = (case dest_predicate cs params s of
   498             SOME (_, i, ys, (_, Ts)) =>
   499               let
   500                 val k = length Ts;
   501                 val bs = map Bound (k - 1 downto 0);
   502                 val P = list_comb (List.nth (preds, i),
   503                   map (incr_boundvars k) ys @ bs);
   504                 val Q = list_abs (mk_names "x" k ~~ Ts,
   505                   HOLogic.mk_binop inductive_conj_name
   506                     (list_comb (incr_boundvars k s, bs), P))
   507               in (Q, case Ts of [] => SOME (s, P) | _ => NONE) end
   508           | NONE => (case s of
   509               (t $ u) => (fst (subst t) $ fst (subst u), NONE)
   510             | (Abs (a, T, t)) => (Abs (a, T, fst (subst t)), NONE)
   511             | _ => (s, NONE)));
   512 
   513         fun mk_prem (s, prems) = (case subst s of
   514               (_, SOME (t, u)) => t :: u :: prems
   515             | (t, _) => t :: prems);
   516 
   517         val SOME (_, i, ys, _) = dest_predicate cs params
   518           (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))
   519 
   520       in list_all_free (Logic.strip_params r,
   521         Logic.list_implies (map HOLogic.mk_Trueprop (foldr mk_prem
   522           [] (map HOLogic.dest_Trueprop (Logic.strip_assums_hyp r))),
   523             HOLogic.mk_Trueprop (list_comb (List.nth (preds, i), ys))))
   524       end;
   525 
   526     val ind_prems = map mk_ind_prem intr_ts;
   527 
   528 
   529     (* make conclusions for induction rules *)
   530 
   531     val Tss = map (binder_types o fastype_of) preds;
   532     val (xnames, ctxt'') =
   533       Variable.variant_fixes (mk_names "x" (length (flat Tss))) ctxt';
   534     val mutual_ind_concl = HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
   535         (map (fn (((xnames, Ts), c), P) =>
   536            let val frees = map Free (xnames ~~ Ts)
   537            in HOLogic.mk_imp
   538              (list_comb (c, params @ frees), list_comb (P, frees))
   539            end) (unflat Tss xnames ~~ Tss ~~ cs ~~ preds)));
   540 
   541 
   542     (* make predicate for instantiation of abstract induction rule *)
   543 
   544     val ind_pred = fold_rev lambda (bs @ xs) (foldr1 HOLogic.mk_conj
   545       (map_index (fn (i, P) => foldr HOLogic.mk_imp
   546          (list_comb (P, make_args' argTs xs (binder_types (fastype_of P))))
   547          (make_bool_args HOLogic.mk_not I bs i)) preds));
   548 
   549     val ind_concl = HOLogic.mk_Trueprop
   550       (HOLogic.mk_binrel "HOL.ord_class.less_eq" (rec_const, ind_pred));
   551 
   552     val raw_fp_induct = (mono RS (fp_def RS def_lfp_induct));
   553 
   554     val induct = SkipProof.prove ctxt'' [] ind_prems ind_concl
   555       (fn {prems, ...} => EVERY
   556         [rewrite_goals_tac [inductive_conj_def],
   557          DETERM (rtac raw_fp_induct 1),
   558          REPEAT (resolve_tac [le_funI, le_boolI] 1),
   559          rewrite_goals_tac (inf_fun_eq :: inf_bool_eq :: simp_thms'),
   560          (*This disjE separates out the introduction rules*)
   561          REPEAT (FIRSTGOAL (eresolve_tac [disjE, exE, FalseE])),
   562          (*Now break down the individual cases.  No disjE here in case
   563            some premise involves disjunction.*)
   564          REPEAT (FIRSTGOAL (etac conjE ORELSE' bound_hyp_subst_tac)),
   565          REPEAT (FIRSTGOAL
   566            (resolve_tac [conjI, impI] ORELSE' (etac notE THEN' atac))),
   567          EVERY (map (fn prem => DEPTH_SOLVE_1 (ares_tac [rewrite_rule
   568              (inductive_conj_def :: rec_preds_defs @ simp_thms') prem,
   569            conjI, refl] 1)) prems)]);
   570 
   571     val lemma = SkipProof.prove ctxt'' [] []
   572       (Logic.mk_implies (ind_concl, mutual_ind_concl)) (fn _ => EVERY
   573         [rewrite_goals_tac rec_preds_defs,
   574          REPEAT (EVERY
   575            [REPEAT (resolve_tac [conjI, impI] 1),
   576             REPEAT (eresolve_tac [le_funE, le_boolE] 1),
   577             atac 1,
   578             rewrite_goals_tac simp_thms',
   579             atac 1])])
   580 
   581   in singleton (ProofContext.export ctxt'' ctxt) (induct RS lemma) end;
   582 
   583 
   584 
   585 (** specification of (co)inductive predicates **)
   586 
   587 fun mk_ind_def alt_name coind cs intr_ts monos
   588       params cnames_syn ctxt =
   589   let
   590     val fp_name = if coind then @{const_name Inductive.gfp} else @{const_name Inductive.lfp};
   591 
   592     val argTs = fold (fn c => fn Ts => Ts @
   593       (List.drop (binder_types (fastype_of c), length params) \\ Ts)) cs [];
   594     val k = log 2 1 (length cs);
   595     val predT = replicate k HOLogic.boolT ---> argTs ---> HOLogic.boolT;
   596     val p :: xs = map Free (Variable.variant_frees ctxt intr_ts
   597       (("p", predT) :: (mk_names "x" (length argTs) ~~ argTs)));
   598     val bs = map Free (Variable.variant_frees ctxt (p :: xs @ intr_ts)
   599       (map (rpair HOLogic.boolT) (mk_names "b" k)));
   600 
   601     fun subst t = (case dest_predicate cs params t of
   602         SOME (_, i, ts, (Ts, Us)) =>
   603           let
   604             val l = length Us;
   605             val zs = map Bound (l - 1 downto 0)
   606           in
   607             list_abs (map (pair "z") Us, list_comb (p,
   608               make_bool_args' bs i @ make_args argTs
   609                 ((map (incr_boundvars l) ts ~~ Ts) @ (zs ~~ Us))))
   610           end
   611       | NONE => (case t of
   612           t1 $ t2 => subst t1 $ subst t2
   613         | Abs (x, T, u) => Abs (x, T, subst u)
   614         | _ => t));
   615 
   616     (* transform an introduction rule into a conjunction  *)
   617     (*   [| p_i t; ... |] ==> p_j u                       *)
   618     (* is transformed into                                *)
   619     (*   b_j & x_j = u & p b_j t & ...                    *)
   620 
   621     fun transform_rule r =
   622       let
   623         val SOME (_, i, ts, (Ts, _)) = dest_predicate cs params
   624           (HOLogic.dest_Trueprop (Logic.strip_assums_concl r));
   625         val ps = make_bool_args HOLogic.mk_not I bs i @
   626           map HOLogic.mk_eq (make_args' argTs xs Ts ~~ ts) @
   627           map (subst o HOLogic.dest_Trueprop)
   628             (Logic.strip_assums_hyp r)
   629       in foldr (fn ((x, T), P) => HOLogic.exists_const T $ (Abs (x, T, P)))
   630         (if null ps then HOLogic.true_const else foldr1 HOLogic.mk_conj ps)
   631         (Logic.strip_params r)
   632       end
   633 
   634     (* make a disjunction of all introduction rules *)
   635 
   636     val fp_fun = fold_rev lambda (p :: bs @ xs)
   637       (if null intr_ts then HOLogic.false_const
   638        else foldr1 HOLogic.mk_disj (map transform_rule intr_ts));
   639 
   640     (* add definiton of recursive predicates to theory *)
   641 
   642     val rec_name = if alt_name = "" then
   643       space_implode "_" (map fst cnames_syn) else alt_name;
   644 
   645     val ((rec_const, (_, fp_def)), ctxt') = ctxt |>
   646       LocalTheory.define Thm.internalK
   647         ((rec_name, case cnames_syn of [(_, syn)] => syn | _ => NoSyn),
   648          (("", []), fold_rev lambda params
   649            (Const (fp_name, (predT --> predT) --> predT) $ fp_fun)));
   650     val fp_def' = Simplifier.rewrite (HOL_basic_ss addsimps [fp_def])
   651       (cterm_of (ProofContext.theory_of ctxt') (list_comb (rec_const, params)));
   652     val specs = if length cs < 2 then [] else
   653       map_index (fn (i, (name_mx, c)) =>
   654         let
   655           val Ts = List.drop (binder_types (fastype_of c), length params);
   656           val xs = map Free (Variable.variant_frees ctxt intr_ts
   657             (mk_names "x" (length Ts) ~~ Ts))
   658         in
   659           (name_mx, (("", []), fold_rev lambda (params @ xs)
   660             (list_comb (rec_const, params @ make_bool_args' bs i @
   661               make_args argTs (xs ~~ Ts)))))
   662         end) (cnames_syn ~~ cs);
   663     val (consts_defs, ctxt'') = fold_map (LocalTheory.define Thm.internalK) specs ctxt';
   664     val preds = (case cs of [_] => [rec_const] | _ => map #1 consts_defs);
   665 
   666     val mono = prove_mono predT fp_fun monos ctxt''
   667 
   668   in (ctxt'', rec_name, mono, fp_def', map (#2 o #2) consts_defs,
   669     list_comb (rec_const, params), preds, argTs, bs, xs)
   670   end;
   671 
   672 fun declare_rules kind rec_name coind no_ind cnames intrs intr_names intr_atts
   673       elims raw_induct ctxt =
   674   let
   675     val ind_case_names = RuleCases.case_names intr_names;
   676     val induct =
   677       if coind then
   678         (raw_induct, [RuleCases.case_names [rec_name],
   679           RuleCases.case_conclusion (rec_name, intr_names),
   680           RuleCases.consumes 1, Induct.coinduct_pred (hd cnames)])
   681       else if no_ind orelse length cnames > 1 then
   682         (raw_induct, [ind_case_names, RuleCases.consumes 0])
   683       else (raw_induct RSN (2, rev_mp), [ind_case_names, RuleCases.consumes 1]);
   684 
   685     val (intrs', ctxt1) =
   686       ctxt |>
   687       LocalTheory.notes kind
   688         (map (NameSpace.qualified rec_name) intr_names ~~
   689          intr_atts ~~ map (fn th => [([th],
   690            [Attrib.internal (K (ContextRules.intro_query NONE))])]) intrs) |>>
   691       map (hd o snd);
   692     val (((_, elims'), (_, [induct'])), ctxt2) =
   693       ctxt1 |>
   694       LocalTheory.note kind ((NameSpace.qualified rec_name "intros", []), intrs') ||>>
   695       fold_map (fn (name, (elim, cases)) =>
   696         LocalTheory.note kind ((NameSpace.qualified (Sign.base_name name) "cases",
   697           [Attrib.internal (K (RuleCases.case_names cases)),
   698            Attrib.internal (K (RuleCases.consumes 1)),
   699            Attrib.internal (K (Induct.cases_pred name)),
   700            Attrib.internal (K (ContextRules.elim_query NONE))]), [elim]) #>
   701         apfst (hd o snd)) (if null elims then [] else cnames ~~ elims) ||>>
   702       LocalTheory.note kind ((NameSpace.qualified rec_name (coind_prefix coind ^ "induct"),
   703         map (Attrib.internal o K) (#2 induct)), [rulify (#1 induct)]);
   704 
   705     val ctxt3 = if no_ind orelse coind then ctxt2 else
   706       let val inducts = cnames ~~ ProjectRule.projects ctxt2 (1 upto length cnames) induct'
   707       in
   708         ctxt2 |>
   709         LocalTheory.notes kind [((NameSpace.qualified rec_name "inducts", []),
   710           inducts |> map (fn (name, th) => ([th],
   711             [Attrib.internal (K ind_case_names),
   712              Attrib.internal (K (RuleCases.consumes 1)),
   713              Attrib.internal (K (Induct.induct_pred name))])))] |> snd
   714       end
   715   in (intrs', elims', induct', ctxt3) end;
   716 
   717 type add_ind_def =
   718   {verbose: bool, kind: string, alt_name: bstring, coind: bool, no_elim: bool, no_ind: bool} ->
   719   term list -> ((string * Attrib.src list) * term) list -> thm list ->
   720   term list -> (string * mixfix) list ->
   721   local_theory -> inductive_result * local_theory
   722 
   723 fun add_ind_def {verbose, kind, alt_name, coind, no_elim, no_ind}
   724     cs intros monos params cnames_syn ctxt =
   725   let
   726     val _ = null cnames_syn andalso error "No inductive predicates given";
   727     val _ =
   728       if verbose then message ("Proofs for " ^ coind_prefix coind ^ "inductive predicate(s) " ^
   729         commas_quote (map fst cnames_syn)) else ();
   730 
   731     val cnames = map (Sign.full_name (ProofContext.theory_of ctxt) o #1) cnames_syn;  (* FIXME *)
   732     val ((intr_names, intr_atts), intr_ts) =
   733       apfst split_list (split_list (map (check_rule ctxt cs params) intros));
   734 
   735     val (ctxt1, rec_name, mono, fp_def, rec_preds_defs, rec_const, preds,
   736       argTs, bs, xs) = mk_ind_def alt_name coind cs intr_ts
   737         monos params cnames_syn ctxt;
   738 
   739     val (intrs, unfold) = prove_intrs coind mono fp_def (length bs + length xs)
   740       params intr_ts rec_preds_defs ctxt1;
   741     val elims = if no_elim then [] else
   742       prove_elims cs params intr_ts intr_names unfold rec_preds_defs ctxt1;
   743     val raw_induct = zero_var_indexes
   744       (if no_ind then Drule.asm_rl else
   745        if coind then
   746          singleton (ProofContext.export
   747            (snd (Variable.add_fixes (map (fst o dest_Free) params) ctxt1)) ctxt1)
   748            (rotate_prems ~1 (ObjectLogic.rulify (rule_by_tactic
   749              (rewrite_tac [le_fun_def, le_bool_def, @{thm sup_fun_eq}, @{thm sup_bool_eq}] THEN
   750                fold_tac rec_preds_defs) (mono RS (fp_def RS def_coinduct)))))
   751        else
   752          prove_indrule cs argTs bs xs rec_const params intr_ts mono fp_def
   753            rec_preds_defs ctxt1);
   754 
   755     val (intrs', elims', induct, ctxt2) = declare_rules kind rec_name coind no_ind
   756       cnames intrs intr_names intr_atts elims raw_induct ctxt1;
   757 
   758     val names = map #1 cnames_syn;
   759     val result =
   760       {preds = preds,
   761        intrs = intrs',
   762        elims = elims',
   763        raw_induct = rulify raw_induct,
   764        induct = induct};
   765 
   766     val ctxt3 = ctxt2
   767       |> LocalTheory.declaration (fn phi =>
   768         let val result' = morph_result phi result;
   769         in put_inductives cnames (*global names!?*) ({names = cnames, coind = coind}, result') end);
   770   in (result, ctxt3) end;
   771 
   772 
   773 (* external interfaces *)
   774 
   775 fun gen_add_inductive_i mk_def (flags as {verbose, kind, alt_name, coind, no_elim, no_ind})
   776     cnames_syn pnames spec monos lthy =
   777   let
   778     val thy = ProofContext.theory_of lthy;
   779     val _ = Theory.requires thy "Inductive" (coind_prefix coind ^ "inductive definitions");
   780 
   781 
   782     (* abbrevs *)
   783 
   784     val (_, ctxt1) = Variable.add_fixes (map (fst o fst) cnames_syn) lthy;
   785 
   786     fun get_abbrev ((name, atts), t) =
   787       if can (Logic.strip_assums_concl #> Logic.dest_equals) t then
   788         let
   789           val _ = name = "" andalso null atts orelse
   790             error "Abbreviations may not have names or attributes";
   791           val ((x, T), rhs) = LocalDefs.abs_def (snd (LocalDefs.cert_def ctxt1 t));
   792           val mx =
   793             (case find_first (fn ((c, _), _) => c = x) cnames_syn of
   794               NONE => error ("Undeclared head of abbreviation " ^ quote x)
   795             | SOME ((_, T'), mx) =>
   796                 if T <> T' then error ("Bad type specification for abbreviation " ^ quote x)
   797                 else mx);
   798         in SOME ((x, mx), rhs) end
   799       else NONE;
   800 
   801     val abbrevs = map_filter get_abbrev spec;
   802     val bs = map (fst o fst) abbrevs;
   803 
   804 
   805     (* predicates *)
   806 
   807     val pre_intros = filter_out (is_some o get_abbrev) spec;
   808     val cnames_syn' = filter_out (member (op =) bs o fst o fst) cnames_syn;
   809     val cs = map (Free o fst) cnames_syn';
   810     val ps = map Free pnames;
   811 
   812     val (_, ctxt2) = lthy |> Variable.add_fixes (map (fst o fst) cnames_syn');
   813     val _ = map (fn abbr => LocalDefs.fixed_abbrev abbr ctxt2) abbrevs;
   814     val ctxt3 = ctxt2 |> fold (snd oo LocalDefs.fixed_abbrev) abbrevs;
   815     val expand = Assumption.export_term ctxt3 lthy #> ProofContext.cert_term lthy;
   816 
   817     fun close_rule r = list_all_free (rev (fold_aterms
   818       (fn t as Free (v as (s, _)) =>
   819           if Variable.is_fixed ctxt1 s orelse
   820             member (op =) ps t then I else insert (op =) v
   821         | _ => I) r []), r);
   822 
   823     val intros = map (apsnd (close_rule #> expand)) pre_intros;
   824     val preds = map (fn ((c, _), mx) => (c, mx)) cnames_syn';
   825   in
   826     lthy
   827     |> mk_def flags cs intros monos ps preds
   828     ||> fold (snd oo LocalTheory.abbrev Syntax.mode_default) abbrevs
   829   end;
   830 
   831 fun gen_add_inductive mk_def verbose coind cnames_syn pnames_syn intro_srcs raw_monos lthy =
   832   let
   833     val ((vars, specs), _) = lthy |> ProofContext.set_mode ProofContext.mode_abbrev
   834       |> Specification.read_specification
   835           (cnames_syn @ pnames_syn) (map (fn (a, s) => [(a, [s])]) intro_srcs);
   836     val (cs, ps) = chop (length cnames_syn) vars;
   837     val intrs = map (apsnd the_single) specs;
   838     val monos = Attrib.eval_thms lthy raw_monos;
   839     val flags = {verbose = verbose, kind = Thm.theoremK, alt_name = "",
   840       coind = coind, no_elim = false, no_ind = false};
   841   in gen_add_inductive_i mk_def flags cs (map fst ps) intrs monos lthy end;
   842 
   843 val add_inductive_i = gen_add_inductive_i add_ind_def;
   844 val add_inductive = gen_add_inductive add_ind_def;
   845 
   846 fun add_inductive_global flags cnames_syn pnames pre_intros monos thy =
   847   let
   848     val name = Sign.full_name thy (fst (fst (hd cnames_syn)));
   849     val ctxt' = thy
   850       |> TheoryTarget.init NONE
   851       |> add_inductive_i flags cnames_syn pnames pre_intros monos |> snd
   852       |> LocalTheory.exit;
   853     val info = #2 (the_inductive ctxt' name);
   854   in (info, ProofContext.theory_of ctxt') end;
   855 
   856 
   857 (* read off arities of inductive predicates from raw induction rule *)
   858 fun arities_of induct =
   859   map (fn (_ $ t $ u) =>
   860       (fst (dest_Const (head_of t)), length (snd (strip_comb u))))
   861     (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
   862 
   863 (* read off parameters of inductive predicate from raw induction rule *)
   864 fun params_of induct =
   865   let
   866     val (_ $ t $ u :: _) =
   867       HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct));
   868     val (_, ts) = strip_comb t;
   869     val (_, us) = strip_comb u
   870   in
   871     List.take (ts, length ts - length us)
   872   end;
   873 
   874 val pname_of_intr =
   875   concl_of #> HOLogic.dest_Trueprop #> head_of #> dest_Const #> fst;
   876 
   877 (* partition introduction rules according to predicate name *)
   878 fun partition_rules induct intros =
   879   fold_rev (fn r => AList.map_entry op = (pname_of_intr r) (cons r)) intros
   880     (map (rpair [] o fst) (arities_of induct));
   881 
   882 fun unpartition_rules intros xs =
   883   fold_map (fn r => AList.map_entry_yield op = (pname_of_intr r)
   884     (fn x :: xs => (x, xs)) #>> the) intros xs |> fst;
   885 
   886 (* infer order of variables in intro rules from order of quantifiers in elim rule *)
   887 fun infer_intro_vars elim arity intros =
   888   let
   889     val thy = theory_of_thm elim;
   890     val _ :: cases = prems_of elim;
   891     val used = map (fst o fst) (Term.add_vars (prop_of elim) []);
   892     fun mtch (t, u) =
   893       let
   894         val params = Logic.strip_params t;
   895         val vars = map (Var o apfst (rpair 0))
   896           (Name.variant_list used (map fst params) ~~ map snd params);
   897         val ts = map (curry subst_bounds (rev vars))
   898           (List.drop (Logic.strip_assums_hyp t, arity));
   899         val us = Logic.strip_imp_prems u;
   900         val tab = fold (Pattern.first_order_match thy) (ts ~~ us)
   901           (Vartab.empty, Vartab.empty);
   902       in
   903         map (Envir.subst_vars tab) vars
   904       end
   905   in
   906     map (mtch o apsnd prop_of) (cases ~~ intros)
   907   end;
   908 
   909 
   910 (** package setup **)
   911 
   912 (* setup theory *)
   913 
   914 val setup =
   915   Method.add_methods [("ind_cases", ind_cases,
   916     "dynamic case analysis on predicates")] #>
   917   Attrib.add_attributes [("mono", Attrib.add_del_args mono_add mono_del,
   918     "declaration of monotonicity rule")];
   919 
   920 
   921 (* outer syntax *)
   922 
   923 local structure P = OuterParse and K = OuterKeyword in
   924 
   925 val _ = OuterSyntax.keywords ["monos"];
   926 
   927 fun flatten_specification specs = specs |> maps
   928   (fn (a, (concl, [])) => concl |> map
   929         (fn ((b, atts), [B]) =>
   930               if a = "" then ((b, atts), B)
   931               else if b = "" then ((a, atts), B)
   932               else error ("Illegal nested case names " ^ quote (NameSpace.append a b))
   933           | ((b, _), _) => error ("Illegal simultaneous specification " ^ quote b))
   934     | (a, _) => error ("Illegal local specification parameters for " ^ quote a));
   935 
   936 fun gen_ind_decl mk_def coind =
   937   P.opt_target --
   938   P.fixes -- P.for_fixes --
   939   Scan.optional (P.$$$ "where" |-- P.!!! SpecParse.specification) [] --
   940   Scan.optional (P.$$$ "monos" |-- P.!!! SpecParse.xthms1) []
   941   >> (fn ((((loc, preds), params), specs), monos) =>
   942     Toplevel.local_theory loc
   943       (fn lthy => lthy |> gen_add_inductive mk_def true coind preds params
   944          (flatten_specification specs) monos |> snd));
   945 
   946 val ind_decl = gen_ind_decl add_ind_def;
   947 
   948 val _ = OuterSyntax.command "inductive" "define inductive predicates" K.thy_decl (ind_decl false);
   949 val _ = OuterSyntax.command "coinductive" "define coinductive predicates" K.thy_decl (ind_decl true);
   950 
   951 val _ =
   952   OuterSyntax.command "inductive_cases"
   953     "create simplified instances of elimination rules (improper)" K.thy_script
   954     (P.opt_target -- P.and_list1 SpecParse.spec
   955       >> (fn (loc, specs) => Toplevel.local_theory loc (snd o inductive_cases specs)));
   956 
   957 end;
   958 
   959 end;