src/HOL/Tools/inductive_set.ML
changeset 31723 f5cafe803b55
parent 30860 e5f9477aed50
child 31998 2c7a24f74db9
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/HOL/Tools/inductive_set.ML	Fri Jun 19 17:23:21 2009 +0200
     1.3 @@ -0,0 +1,566 @@
     1.4 +(*  Title:      HOL/Tools/inductive_set.ML
     1.5 +    Author:     Stefan Berghofer, TU Muenchen
     1.6 +
     1.7 +Wrapper for defining inductive sets using package for inductive predicates,
     1.8 +including infrastructure for converting between predicates and sets.
     1.9 +*)
    1.10 +
    1.11 +signature INDUCTIVE_SET =
    1.12 +sig
    1.13 +  val to_set_att: thm list -> attribute
    1.14 +  val to_pred_att: thm list -> attribute
    1.15 +  val pred_set_conv_att: attribute
    1.16 +  val add_inductive_i:
    1.17 +    Inductive.inductive_flags ->
    1.18 +    ((binding * typ) * mixfix) list ->
    1.19 +    (string * typ) list ->
    1.20 +    (Attrib.binding * term) list -> thm list ->
    1.21 +    local_theory -> Inductive.inductive_result * local_theory
    1.22 +  val add_inductive: bool -> bool ->
    1.23 +    (binding * string option * mixfix) list ->
    1.24 +    (binding * string option * mixfix) list ->
    1.25 +    (Attrib.binding * string) list -> (Facts.ref * Attrib.src list) list ->
    1.26 +    bool -> local_theory -> Inductive.inductive_result * local_theory
    1.27 +  val codegen_preproc: theory -> thm list -> thm list
    1.28 +  val setup: theory -> theory
    1.29 +end;
    1.30 +
    1.31 +structure Inductive_Set: INDUCTIVE_SET =
    1.32 +struct
    1.33 +
    1.34 +(**** simplify {(x1, ..., xn). (x1, ..., xn) : S} to S ****)
    1.35 +
    1.36 +val collect_mem_simproc =
    1.37 +  Simplifier.simproc (theory "Set") "Collect_mem" ["Collect t"] (fn thy => fn ss =>
    1.38 +    fn S as Const ("Collect", Type ("fun", [_, T])) $ t =>
    1.39 +         let val (u, Ts, ps) = HOLogic.strip_split t
    1.40 +         in case u of
    1.41 +           (c as Const ("op :", _)) $ q $ S' =>
    1.42 +             (case try (HOLogic.dest_tuple' ps) q of
    1.43 +                NONE => NONE
    1.44 +              | SOME ts =>
    1.45 +                  if not (loose_bvar (S', 0)) andalso
    1.46 +                    ts = map Bound (length ps downto 0)
    1.47 +                  then
    1.48 +                    let val simp = full_simp_tac (Simplifier.inherit_context ss
    1.49 +                      (HOL_basic_ss addsimps [split_paired_all, split_conv])) 1
    1.50 +                    in
    1.51 +                      SOME (Goal.prove (Simplifier.the_context ss) [] []
    1.52 +                        (Const ("==", T --> T --> propT) $ S $ S')
    1.53 +                        (K (EVERY
    1.54 +                          [rtac eq_reflection 1, rtac @{thm subset_antisym} 1,
    1.55 +                           rtac subsetI 1, dtac CollectD 1, simp,
    1.56 +                           rtac subsetI 1, rtac CollectI 1, simp])))
    1.57 +                    end
    1.58 +                  else NONE)
    1.59 +         | _ => NONE
    1.60 +         end
    1.61 +     | _ => NONE);
    1.62 +
    1.63 +(***********************************************************************************)
    1.64 +(* simplifies (%x y. (x, y) : S & P x y) to (%x y. (x, y) : S Int {(x, y). P x y}) *)
    1.65 +(* and        (%x y. (x, y) : S | P x y) to (%x y. (x, y) : S Un {(x, y). P x y})  *)
    1.66 +(* used for converting "strong" (co)induction rules                                *)
    1.67 +(***********************************************************************************)
    1.68 +
    1.69 +val anyt = Free ("t", TFree ("'t", []));
    1.70 +
    1.71 +fun strong_ind_simproc tab =
    1.72 +  Simplifier.simproc_i @{theory HOL} "strong_ind" [anyt] (fn thy => fn ss => fn t =>
    1.73 +    let
    1.74 +      fun close p t f =
    1.75 +        let val vs = Term.add_vars t []
    1.76 +        in Drule.instantiate' [] (rev (map (SOME o cterm_of thy o Var) vs))
    1.77 +          (p (fold (Logic.all o Var) vs t) f)
    1.78 +        end;
    1.79 +      fun mkop "op &" T x = SOME (Const (@{const_name "Int"}, T --> T --> T), x)
    1.80 +        | mkop "op |" T x = SOME (Const (@{const_name "Un"}, T --> T --> T), x)
    1.81 +        | mkop _ _ _ = NONE;
    1.82 +      fun mk_collect p T t =
    1.83 +        let val U = HOLogic.dest_setT T
    1.84 +        in HOLogic.Collect_const U $
    1.85 +          HOLogic.ap_split' (HOLogic.prod_factors p) U HOLogic.boolT t
    1.86 +        end;
    1.87 +      fun decomp (Const (s, _) $ ((m as Const ("op :",
    1.88 +            Type (_, [_, Type (_, [T, _])]))) $ p $ S) $ u) =
    1.89 +              mkop s T (m, p, S, mk_collect p T (head_of u))
    1.90 +        | decomp (Const (s, _) $ u $ ((m as Const ("op :",
    1.91 +            Type (_, [_, Type (_, [T, _])]))) $ p $ S)) =
    1.92 +              mkop s T (m, p, mk_collect p T (head_of u), S)
    1.93 +        | decomp _ = NONE;
    1.94 +      val simp = full_simp_tac (Simplifier.inherit_context ss
    1.95 +        (HOL_basic_ss addsimps [mem_Collect_eq, split_conv])) 1;
    1.96 +      fun mk_rew t = (case strip_abs_vars t of
    1.97 +          [] => NONE
    1.98 +        | xs => (case decomp (strip_abs_body t) of
    1.99 +            NONE => NONE
   1.100 +          | SOME (bop, (m, p, S, S')) =>
   1.101 +              SOME (close (Goal.prove (Simplifier.the_context ss) [] [])
   1.102 +                (Logic.mk_equals (t, list_abs (xs, m $ p $ (bop $ S $ S'))))
   1.103 +                (K (EVERY
   1.104 +                  [rtac eq_reflection 1, REPEAT (rtac ext 1), rtac iffI 1,
   1.105 +                   EVERY [etac conjE 1, rtac IntI 1, simp, simp,
   1.106 +                     etac IntE 1, rtac conjI 1, simp, simp] ORELSE
   1.107 +                   EVERY [etac disjE 1, rtac UnI1 1, simp, rtac UnI2 1, simp,
   1.108 +                     etac UnE 1, rtac disjI1 1, simp, rtac disjI2 1, simp]])))
   1.109 +                handle ERROR _ => NONE))
   1.110 +    in
   1.111 +      case strip_comb t of
   1.112 +        (h as Const (name, _), ts) => (case Symtab.lookup tab name of
   1.113 +          SOME _ =>
   1.114 +            let val rews = map mk_rew ts
   1.115 +            in
   1.116 +              if forall is_none rews then NONE
   1.117 +              else SOME (fold (fn th1 => fn th2 => combination th2 th1)
   1.118 +                (map2 (fn SOME r => K r | NONE => reflexive o cterm_of thy)
   1.119 +                   rews ts) (reflexive (cterm_of thy h)))
   1.120 +            end
   1.121 +        | NONE => NONE)
   1.122 +      | _ => NONE
   1.123 +    end);
   1.124 +
   1.125 +(* only eta contract terms occurring as arguments of functions satisfying p *)
   1.126 +fun eta_contract p =
   1.127 +  let
   1.128 +    fun eta b (Abs (a, T, body)) =
   1.129 +          (case eta b body of
   1.130 +             body' as (f $ Bound 0) =>
   1.131 +               if loose_bvar1 (f, 0) orelse not b then Abs (a, T, body')
   1.132 +               else incr_boundvars ~1 f
   1.133 +           | body' => Abs (a, T, body'))
   1.134 +      | eta b (t $ u) = eta b t $ eta (p (head_of t)) u
   1.135 +      | eta b t = t
   1.136 +  in eta false end;
   1.137 +
   1.138 +fun eta_contract_thm p =
   1.139 +  Conv.fconv_rule (Conv.then_conv (Thm.beta_conversion true, fn ct =>
   1.140 +    Thm.transitive (Thm.eta_conversion ct)
   1.141 +      (Thm.symmetric (Thm.eta_conversion
   1.142 +        (cterm_of (theory_of_cterm ct) (eta_contract p (term_of ct)))))));
   1.143 +
   1.144 +
   1.145 +(***********************************************************)
   1.146 +(* rules for converting between predicate and set notation *)
   1.147 +(*                                                         *)
   1.148 +(* rules for converting predicates to sets have the form   *)
   1.149 +(* P (%x y. (x, y) : s) = (%x y. (x, y) : S s)             *)
   1.150 +(*                                                         *)
   1.151 +(* rules for converting sets to predicates have the form   *)
   1.152 +(* S {(x, y). p x y} = {(x, y). P p x y}                   *)
   1.153 +(*                                                         *)
   1.154 +(* where s and p are parameters                            *)
   1.155 +(***********************************************************)
   1.156 +
   1.157 +structure PredSetConvData = GenericDataFun
   1.158 +(
   1.159 +  type T =
   1.160 +    {(* rules for converting predicates to sets *)
   1.161 +     to_set_simps: thm list,
   1.162 +     (* rules for converting sets to predicates *)
   1.163 +     to_pred_simps: thm list,
   1.164 +     (* arities of functions of type t set => ... => u set *)
   1.165 +     set_arities: (typ * (int list list option list * int list list option)) list Symtab.table,
   1.166 +     (* arities of functions of type (t => ... => bool) => u => ... => bool *)
   1.167 +     pred_arities: (typ * (int list list option list * int list list option)) list Symtab.table};
   1.168 +  val empty = {to_set_simps = [], to_pred_simps = [],
   1.169 +    set_arities = Symtab.empty, pred_arities = Symtab.empty};
   1.170 +  val extend = I;
   1.171 +  fun merge _
   1.172 +    ({to_set_simps = to_set_simps1, to_pred_simps = to_pred_simps1,
   1.173 +      set_arities = set_arities1, pred_arities = pred_arities1},
   1.174 +     {to_set_simps = to_set_simps2, to_pred_simps = to_pred_simps2,
   1.175 +      set_arities = set_arities2, pred_arities = pred_arities2}) : T =
   1.176 +    {to_set_simps = Thm.merge_thms (to_set_simps1, to_set_simps2),
   1.177 +     to_pred_simps = Thm.merge_thms (to_pred_simps1, to_pred_simps2),
   1.178 +     set_arities = Symtab.merge_list op = (set_arities1, set_arities2),
   1.179 +     pred_arities = Symtab.merge_list op = (pred_arities1, pred_arities2)};
   1.180 +);
   1.181 +
   1.182 +fun name_type_of (Free p) = SOME p
   1.183 +  | name_type_of (Const p) = SOME p
   1.184 +  | name_type_of _ = NONE;
   1.185 +
   1.186 +fun map_type f (Free (s, T)) = Free (s, f T)
   1.187 +  | map_type f (Var (ixn, T)) = Var (ixn, f T)
   1.188 +  | map_type f _ = error "map_type";
   1.189 +
   1.190 +fun find_most_specific is_inst f eq xs T =
   1.191 +  find_first (fn U => is_inst (T, f U)
   1.192 +    andalso forall (fn U' => eq (f U, f U') orelse not
   1.193 +      (is_inst (T, f U') andalso is_inst (f U', f U)))
   1.194 +        xs) xs;
   1.195 +
   1.196 +fun lookup_arity thy arities (s, T) = case Symtab.lookup arities s of
   1.197 +    NONE => NONE
   1.198 +  | SOME xs => find_most_specific (Sign.typ_instance thy) fst (op =) xs T;
   1.199 +
   1.200 +fun lookup_rule thy f rules = find_most_specific
   1.201 +  (swap #> Pattern.matches thy) (f #> fst) (op aconv) rules;
   1.202 +
   1.203 +fun infer_arities thy arities (optf, t) fs = case strip_comb t of
   1.204 +    (Abs (s, T, u), []) => infer_arities thy arities (NONE, u) fs
   1.205 +  | (Abs _, _) => infer_arities thy arities (NONE, Envir.beta_norm t) fs
   1.206 +  | (u, ts) => (case Option.map (lookup_arity thy arities) (name_type_of u) of
   1.207 +      SOME (SOME (_, (arity, _))) =>
   1.208 +        (fold (infer_arities thy arities) (arity ~~ List.take (ts, length arity)) fs
   1.209 +           handle Subscript => error "infer_arities: bad term")
   1.210 +    | _ => fold (infer_arities thy arities) (map (pair NONE) ts)
   1.211 +      (case optf of
   1.212 +         NONE => fs
   1.213 +       | SOME f => AList.update op = (u, the_default f
   1.214 +           (Option.map (curry op inter f) (AList.lookup op = fs u))) fs));
   1.215 +
   1.216 +
   1.217 +(**************************************************************)
   1.218 +(*    derive the to_pred equation from the to_set equation    *)
   1.219 +(*                                                            *)
   1.220 +(* 1. instantiate each set parameter with {(x, y). p x y}     *)
   1.221 +(* 2. apply %P. {(x, y). P x y} to both sides of the equation *)
   1.222 +(* 3. simplify                                                *)
   1.223 +(**************************************************************)
   1.224 +
   1.225 +fun mk_to_pred_inst thy fs =
   1.226 +  map (fn (x, ps) =>
   1.227 +    let
   1.228 +      val U = HOLogic.dest_setT (fastype_of x);
   1.229 +      val x' = map_type (K (HOLogic.prodT_factors' ps U ---> HOLogic.boolT)) x
   1.230 +    in
   1.231 +      (cterm_of thy x,
   1.232 +       cterm_of thy (HOLogic.Collect_const U $
   1.233 +         HOLogic.ap_split' ps U HOLogic.boolT x'))
   1.234 +    end) fs;
   1.235 +
   1.236 +fun mk_to_pred_eq p fs optfs' T thm =
   1.237 +  let
   1.238 +    val thy = theory_of_thm thm;
   1.239 +    val insts = mk_to_pred_inst thy fs;
   1.240 +    val thm' = Thm.instantiate ([], insts) thm;
   1.241 +    val thm'' = (case optfs' of
   1.242 +        NONE => thm' RS sym
   1.243 +      | SOME fs' =>
   1.244 +          let
   1.245 +            val (_, U) = split_last (binder_types T);
   1.246 +            val Ts = HOLogic.prodT_factors' fs' U;
   1.247 +            (* FIXME: should cterm_instantiate increment indexes? *)
   1.248 +            val arg_cong' = Thm.incr_indexes (Thm.maxidx_of thm + 1) arg_cong;
   1.249 +            val (arg_cong_f, _) = arg_cong' |> cprop_of |> Drule.strip_imp_concl |>
   1.250 +              Thm.dest_comb |> snd |> Drule.strip_comb |> snd |> hd |> Thm.dest_comb
   1.251 +          in
   1.252 +            thm' RS (Drule.cterm_instantiate [(arg_cong_f,
   1.253 +              cterm_of thy (Abs ("P", Ts ---> HOLogic.boolT,
   1.254 +                HOLogic.Collect_const U $ HOLogic.ap_split' fs' U
   1.255 +                  HOLogic.boolT (Bound 0))))] arg_cong' RS sym)
   1.256 +          end)
   1.257 +  in
   1.258 +    Simplifier.simplify (HOL_basic_ss addsimps [mem_Collect_eq, split_conv]
   1.259 +      addsimprocs [collect_mem_simproc]) thm'' |>
   1.260 +        zero_var_indexes |> eta_contract_thm (equal p)
   1.261 +  end;
   1.262 +
   1.263 +
   1.264 +(**** declare rules for converting predicates to sets ****)
   1.265 +
   1.266 +fun add ctxt thm (tab as {to_set_simps, to_pred_simps, set_arities, pred_arities}) =
   1.267 +  case prop_of thm of
   1.268 +    Const ("Trueprop", _) $ (Const ("op =", Type (_, [T, _])) $ lhs $ rhs) =>
   1.269 +      (case body_type T of
   1.270 +         Type ("bool", []) =>
   1.271 +           let
   1.272 +             val thy = Context.theory_of ctxt;
   1.273 +             fun factors_of t fs = case strip_abs_body t of
   1.274 +                 Const ("op :", _) $ u $ S =>
   1.275 +                   if is_Free S orelse is_Var S then
   1.276 +                     let val ps = HOLogic.prod_factors u
   1.277 +                     in (SOME ps, (S, ps) :: fs) end
   1.278 +                   else (NONE, fs)
   1.279 +               | _ => (NONE, fs);
   1.280 +             val (h, ts) = strip_comb lhs
   1.281 +             val (pfs, fs) = fold_map factors_of ts [];
   1.282 +             val ((h', ts'), fs') = (case rhs of
   1.283 +                 Abs _ => (case strip_abs_body rhs of
   1.284 +                     Const ("op :", _) $ u $ S =>
   1.285 +                       (strip_comb S, SOME (HOLogic.prod_factors u))
   1.286 +                   | _ => error "member symbol on right-hand side expected")
   1.287 +               | _ => (strip_comb rhs, NONE))
   1.288 +           in
   1.289 +             case (name_type_of h, name_type_of h') of
   1.290 +               (SOME (s, T), SOME (s', T')) =>
   1.291 +                 if exists (fn (U, _) =>
   1.292 +                   Sign.typ_instance thy (T', U) andalso
   1.293 +                   Sign.typ_instance thy (U, T'))
   1.294 +                     (Symtab.lookup_list set_arities s')
   1.295 +                 then
   1.296 +                   (warning ("Ignoring conversion rule for operator " ^ s'); tab)
   1.297 +                 else
   1.298 +                   {to_set_simps = thm :: to_set_simps,
   1.299 +                    to_pred_simps =
   1.300 +                      mk_to_pred_eq h fs fs' T' thm :: to_pred_simps,
   1.301 +                    set_arities = Symtab.insert_list op = (s',
   1.302 +                      (T', (map (AList.lookup op = fs) ts', fs'))) set_arities,
   1.303 +                    pred_arities = Symtab.insert_list op = (s,
   1.304 +                      (T, (pfs, fs'))) pred_arities}
   1.305 +             | _ => error "set / predicate constant expected"
   1.306 +           end
   1.307 +       | _ => error "equation between predicates expected")
   1.308 +  | _ => error "equation expected";
   1.309 +
   1.310 +val pred_set_conv_att = Thm.declaration_attribute
   1.311 +  (fn thm => fn ctxt => PredSetConvData.map (add ctxt thm) ctxt);
   1.312 +
   1.313 +
   1.314 +(**** convert theorem in set notation to predicate notation ****)
   1.315 +
   1.316 +fun is_pred tab t =
   1.317 +  case Option.map (Symtab.lookup tab o fst) (name_type_of t) of
   1.318 +    SOME (SOME _) => true | _ => false;
   1.319 +
   1.320 +fun to_pred_simproc rules =
   1.321 +  let val rules' = map mk_meta_eq rules
   1.322 +  in
   1.323 +    Simplifier.simproc_i @{theory HOL} "to_pred" [anyt]
   1.324 +      (fn thy => K (lookup_rule thy (prop_of #> Logic.dest_equals) rules'))
   1.325 +  end;
   1.326 +
   1.327 +fun to_pred_proc thy rules t = case lookup_rule thy I rules t of
   1.328 +    NONE => NONE
   1.329 +  | SOME (lhs, rhs) =>
   1.330 +      SOME (Envir.subst_vars
   1.331 +        (Pattern.match thy (lhs, t) (Vartab.empty, Vartab.empty)) rhs);
   1.332 +
   1.333 +fun to_pred thms ctxt thm =
   1.334 +  let
   1.335 +    val thy = Context.theory_of ctxt;
   1.336 +    val {to_pred_simps, set_arities, pred_arities, ...} =
   1.337 +      fold (add ctxt) thms (PredSetConvData.get ctxt);
   1.338 +    val fs = filter (is_Var o fst)
   1.339 +      (infer_arities thy set_arities (NONE, prop_of thm) []);
   1.340 +    (* instantiate each set parameter with {(x, y). p x y} *)
   1.341 +    val insts = mk_to_pred_inst thy fs
   1.342 +  in
   1.343 +    thm |>
   1.344 +    Thm.instantiate ([], insts) |>
   1.345 +    Simplifier.full_simplify (HOL_basic_ss addsimprocs
   1.346 +      [to_pred_simproc (mem_Collect_eq :: split_conv :: to_pred_simps)]) |>
   1.347 +    eta_contract_thm (is_pred pred_arities) |>
   1.348 +    RuleCases.save thm
   1.349 +  end;
   1.350 +
   1.351 +val to_pred_att = Thm.rule_attribute o to_pred;
   1.352 +    
   1.353 +
   1.354 +(**** convert theorem in predicate notation to set notation ****)
   1.355 +
   1.356 +fun to_set thms ctxt thm =
   1.357 +  let
   1.358 +    val thy = Context.theory_of ctxt;
   1.359 +    val {to_set_simps, pred_arities, ...} =
   1.360 +      fold (add ctxt) thms (PredSetConvData.get ctxt);
   1.361 +    val fs = filter (is_Var o fst)
   1.362 +      (infer_arities thy pred_arities (NONE, prop_of thm) []);
   1.363 +    (* instantiate each predicate parameter with %x y. (x, y) : s *)
   1.364 +    val insts = map (fn (x, ps) =>
   1.365 +      let
   1.366 +        val Ts = binder_types (fastype_of x);
   1.367 +        val T = HOLogic.mk_tupleT ps Ts;
   1.368 +        val x' = map_type (K (HOLogic.mk_setT T)) x
   1.369 +      in
   1.370 +        (cterm_of thy x,
   1.371 +         cterm_of thy (list_abs (map (pair "x") Ts, HOLogic.mk_mem
   1.372 +           (HOLogic.mk_tuple' ps T (map Bound (length ps downto 0)), x'))))
   1.373 +      end) fs
   1.374 +  in
   1.375 +    thm |>
   1.376 +    Thm.instantiate ([], insts) |>
   1.377 +    Simplifier.full_simplify (HOL_basic_ss addsimps to_set_simps
   1.378 +        addsimprocs [strong_ind_simproc pred_arities, collect_mem_simproc]) |>
   1.379 +    RuleCases.save thm
   1.380 +  end;
   1.381 +
   1.382 +val to_set_att = Thm.rule_attribute o to_set;
   1.383 +
   1.384 +
   1.385 +(**** preprocessor for code generator ****)
   1.386 +
   1.387 +fun codegen_preproc thy =
   1.388 +  let
   1.389 +    val {to_pred_simps, set_arities, pred_arities, ...} =
   1.390 +      PredSetConvData.get (Context.Theory thy);
   1.391 +    fun preproc thm =
   1.392 +      if exists_Const (fn (s, _) => case Symtab.lookup set_arities s of
   1.393 +          NONE => false
   1.394 +        | SOME arities => exists (fn (_, (xs, _)) =>
   1.395 +            forall is_none xs) arities) (prop_of thm)
   1.396 +      then
   1.397 +        thm |>
   1.398 +        Simplifier.full_simplify (HOL_basic_ss addsimprocs
   1.399 +          [to_pred_simproc (mem_Collect_eq :: split_conv :: to_pred_simps)]) |>
   1.400 +        eta_contract_thm (is_pred pred_arities)
   1.401 +      else thm
   1.402 +  in map preproc end;
   1.403 +
   1.404 +fun code_ind_att optmod = to_pred_att [] #> InductiveCodegen.add optmod NONE;
   1.405 +
   1.406 +
   1.407 +(**** definition of inductive sets ****)
   1.408 +
   1.409 +fun add_ind_set_def
   1.410 +    {quiet_mode, verbose, kind, alt_name, coind, no_elim, no_ind, skip_mono, fork_mono}
   1.411 +    cs intros monos params cnames_syn ctxt =
   1.412 +  let
   1.413 +    val thy = ProofContext.theory_of ctxt;
   1.414 +    val {set_arities, pred_arities, to_pred_simps, ...} =
   1.415 +      PredSetConvData.get (Context.Proof ctxt);
   1.416 +    fun infer (Abs (_, _, t)) = infer t
   1.417 +      | infer (Const ("op :", _) $ t $ u) =
   1.418 +          infer_arities thy set_arities (SOME (HOLogic.prod_factors t), u)
   1.419 +      | infer (t $ u) = infer t #> infer u
   1.420 +      | infer _ = I;
   1.421 +    val new_arities = filter_out
   1.422 +      (fn (x as Free (_, T), _) => x mem params andalso length (binder_types T) > 1
   1.423 +        | _ => false) (fold (snd #> infer) intros []);
   1.424 +    val params' = map (fn x => (case AList.lookup op = new_arities x of
   1.425 +        SOME fs =>
   1.426 +          let
   1.427 +            val T = HOLogic.dest_setT (fastype_of x);
   1.428 +            val Ts = HOLogic.prodT_factors' fs T;
   1.429 +            val x' = map_type (K (Ts ---> HOLogic.boolT)) x
   1.430 +          in
   1.431 +            (x, (x',
   1.432 +              (HOLogic.Collect_const T $
   1.433 +                 HOLogic.ap_split' fs T HOLogic.boolT x',
   1.434 +               list_abs (map (pair "x") Ts, HOLogic.mk_mem
   1.435 +                 (HOLogic.mk_tuple' fs T (map Bound (length fs downto 0)),
   1.436 +                  x)))))
   1.437 +          end
   1.438 +       | NONE => (x, (x, (x, x))))) params;
   1.439 +    val (params1, (params2, params3)) =
   1.440 +      params' |> map snd |> split_list ||> split_list;
   1.441 +    val paramTs = map fastype_of params;
   1.442 +
   1.443 +    (* equations for converting sets to predicates *)
   1.444 +    val ((cs', cs_info), eqns) = cs |> map (fn c as Free (s, T) =>
   1.445 +      let
   1.446 +        val fs = the_default [] (AList.lookup op = new_arities c);
   1.447 +        val (Us, U) = split_last (binder_types T);
   1.448 +        val _ = Us = paramTs orelse error (Pretty.string_of (Pretty.chunks
   1.449 +          [Pretty.str "Argument types",
   1.450 +           Pretty.block (Pretty.commas (map (Syntax.pretty_typ ctxt) Us)),
   1.451 +           Pretty.str ("of " ^ s ^ " do not agree with types"),
   1.452 +           Pretty.block (Pretty.commas (map (Syntax.pretty_typ ctxt) paramTs)),
   1.453 +           Pretty.str "of declared parameters"]));
   1.454 +        val Ts = HOLogic.prodT_factors' fs U;
   1.455 +        val c' = Free (s ^ "p",
   1.456 +          map fastype_of params1 @ Ts ---> HOLogic.boolT)
   1.457 +      in
   1.458 +        ((c', (fs, U, Ts)),
   1.459 +         (list_comb (c, params2),
   1.460 +          HOLogic.Collect_const U $ HOLogic.ap_split' fs U HOLogic.boolT
   1.461 +            (list_comb (c', params1))))
   1.462 +      end) |> split_list |>> split_list;
   1.463 +    val eqns' = eqns @
   1.464 +      map (prop_of #> HOLogic.dest_Trueprop #> HOLogic.dest_eq)
   1.465 +        (mem_Collect_eq :: split_conv :: to_pred_simps);
   1.466 +
   1.467 +    (* predicate version of the introduction rules *)
   1.468 +    val intros' =
   1.469 +      map (fn (name_atts, t) => (name_atts,
   1.470 +        t |>
   1.471 +        map_aterms (fn u =>
   1.472 +          (case AList.lookup op = params' u of
   1.473 +             SOME (_, (u', _)) => u'
   1.474 +           | NONE => u)) |>
   1.475 +        Pattern.rewrite_term thy [] [to_pred_proc thy eqns'] |>
   1.476 +        eta_contract (member op = cs' orf is_pred pred_arities))) intros;
   1.477 +    val cnames_syn' = map (fn (b, _) => (Binding.suffix_name "p" b, NoSyn)) cnames_syn;
   1.478 +    val monos' = map (to_pred [] (Context.Proof ctxt)) monos;
   1.479 +    val ({preds, intrs, elims, raw_induct, ...}, ctxt1) =
   1.480 +      Inductive.add_ind_def
   1.481 +        {quiet_mode = quiet_mode, verbose = verbose, kind = kind, alt_name = Binding.empty,
   1.482 +          coind = coind, no_elim = no_elim, no_ind = no_ind,
   1.483 +          skip_mono = skip_mono, fork_mono = fork_mono}
   1.484 +        cs' intros' monos' params1 cnames_syn' ctxt;
   1.485 +
   1.486 +    (* define inductive sets using previously defined predicates *)
   1.487 +    val (defs, ctxt2) = fold_map (LocalTheory.define Thm.internalK)
   1.488 +      (map (fn ((c_syn, (fs, U, _)), p) => (c_syn, (Attrib.empty_binding,
   1.489 +         fold_rev lambda params (HOLogic.Collect_const U $
   1.490 +           HOLogic.ap_split' fs U HOLogic.boolT (list_comb (p, params3))))))
   1.491 +         (cnames_syn ~~ cs_info ~~ preds)) ctxt1;
   1.492 +
   1.493 +    (* prove theorems for converting predicate to set notation *)
   1.494 +    val ctxt3 = fold
   1.495 +      (fn (((p, c as Free (s, _)), (fs, U, Ts)), (_, (_, def))) => fn ctxt =>
   1.496 +        let val conv_thm =
   1.497 +          Goal.prove ctxt (map (fst o dest_Free) params) []
   1.498 +            (HOLogic.mk_Trueprop (HOLogic.mk_eq
   1.499 +              (list_comb (p, params3),
   1.500 +               list_abs (map (pair "x") Ts, HOLogic.mk_mem
   1.501 +                 (HOLogic.mk_tuple' fs U (map Bound (length fs downto 0)),
   1.502 +                  list_comb (c, params))))))
   1.503 +            (K (REPEAT (rtac ext 1) THEN simp_tac (HOL_basic_ss addsimps
   1.504 +              [def, mem_Collect_eq, split_conv]) 1))
   1.505 +        in
   1.506 +          ctxt |> LocalTheory.note kind ((Binding.name (s ^ "p_" ^ s ^ "_eq"),
   1.507 +            [Attrib.internal (K pred_set_conv_att)]),
   1.508 +              [conv_thm]) |> snd
   1.509 +        end) (preds ~~ cs ~~ cs_info ~~ defs) ctxt2;
   1.510 +
   1.511 +    (* convert theorems to set notation *)
   1.512 +    val rec_name =
   1.513 +      if Binding.is_empty alt_name then
   1.514 +        Binding.name (space_implode "_" (map (Binding.name_of o fst) cnames_syn))
   1.515 +      else alt_name;
   1.516 +    val cnames = map (LocalTheory.full_name ctxt3 o #1) cnames_syn;  (* FIXME *)
   1.517 +    val (intr_names, intr_atts) = split_list (map fst intros);
   1.518 +    val raw_induct' = to_set [] (Context.Proof ctxt3) raw_induct;
   1.519 +    val (intrs', elims', induct, ctxt4) =
   1.520 +      Inductive.declare_rules kind rec_name coind no_ind cnames
   1.521 +      (map (to_set [] (Context.Proof ctxt3)) intrs) intr_names intr_atts
   1.522 +      (map (fn th => (to_set [] (Context.Proof ctxt3) th,
   1.523 +         map fst (fst (RuleCases.get th)))) elims)
   1.524 +      raw_induct' ctxt3
   1.525 +  in
   1.526 +    ({intrs = intrs', elims = elims', induct = induct,
   1.527 +      raw_induct = raw_induct', preds = map fst defs},
   1.528 +     ctxt4)
   1.529 +  end;
   1.530 +
   1.531 +val add_inductive_i = Inductive.gen_add_inductive_i add_ind_set_def;
   1.532 +val add_inductive = Inductive.gen_add_inductive add_ind_set_def;
   1.533 +
   1.534 +val mono_add_att = to_pred_att [] #> Inductive.mono_add;
   1.535 +val mono_del_att = to_pred_att [] #> Inductive.mono_del;
   1.536 +
   1.537 +
   1.538 +(** package setup **)
   1.539 +
   1.540 +(* setup theory *)
   1.541 +
   1.542 +val setup =
   1.543 +  Attrib.setup @{binding pred_set_conv} (Scan.succeed pred_set_conv_att)
   1.544 +    "declare rules for converting between predicate and set notation" #>
   1.545 +  Attrib.setup @{binding to_set} (Attrib.thms >> to_set_att) "convert rule to set notation" #>
   1.546 +  Attrib.setup @{binding to_pred} (Attrib.thms >> to_pred_att) "convert rule to predicate notation" #>
   1.547 +  Code.add_attribute ("ind_set",
   1.548 +    Scan.option (Args.$$$ "target" |-- Args.colon |-- Args.name) >> code_ind_att) #>
   1.549 +  Codegen.add_preprocessor codegen_preproc #>
   1.550 +  Attrib.setup @{binding mono_set} (Attrib.add_del mono_add_att mono_del_att)
   1.551 +    "declaration of monotonicity rule for set operators" #>
   1.552 +  Context.theory_map (Simplifier.map_ss (fn ss => ss addsimprocs [collect_mem_simproc]));
   1.553 +
   1.554 +
   1.555 +(* outer syntax *)
   1.556 +
   1.557 +local structure P = OuterParse and K = OuterKeyword in
   1.558 +
   1.559 +val ind_set_decl = Inductive.gen_ind_decl add_ind_set_def;
   1.560 +
   1.561 +val _ =
   1.562 +  OuterSyntax.local_theory' "inductive_set" "define inductive sets" K.thy_decl (ind_set_decl false);
   1.563 +
   1.564 +val _ =
   1.565 +  OuterSyntax.local_theory' "coinductive_set" "define coinductive sets" K.thy_decl (ind_set_decl true);
   1.566 +
   1.567 +end;
   1.568 +
   1.569 +end;