src/HOL/Tools/inductive_set.ML
author haftmann
Tue Oct 20 16:13:01 2009 +0200 (2009-10-20)
changeset 33037 b22e44496dc2
parent 32683 7c1fe854ca6a
child 33038 8f9594c31de4
permissions -rw-r--r--
replaced old_style infixes eq_set, subset, union, inter and variants by generic versions
     1 (*  Title:      HOL/Tools/inductive_set.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Wrapper for defining inductive sets using package for inductive predicates,
     5 including infrastructure for converting between predicates and sets.
     6 *)
     7 
     8 signature INDUCTIVE_SET =
     9 sig
    10   val to_set_att: thm list -> attribute
    11   val to_pred_att: thm list -> attribute
    12   val to_pred : thm list -> Context.generic -> thm -> thm
    13   val pred_set_conv_att: attribute
    14   val add_inductive_i:
    15     Inductive.inductive_flags ->
    16     ((binding * typ) * mixfix) list ->
    17     (string * typ) list ->
    18     (Attrib.binding * term) list -> thm list ->
    19     local_theory -> Inductive.inductive_result * local_theory
    20   val add_inductive: bool -> bool ->
    21     (binding * string option * mixfix) list ->
    22     (binding * string option * mixfix) list ->
    23     (Attrib.binding * string) list -> (Facts.ref * Attrib.src list) list ->
    24     bool -> local_theory -> Inductive.inductive_result * local_theory
    25   val codegen_preproc: theory -> thm list -> thm list
    26   val setup: theory -> theory
    27 end;
    28 
    29 structure Inductive_Set: INDUCTIVE_SET =
    30 struct
    31 
    32 (**** simplify {(x1, ..., xn). (x1, ..., xn) : S} to S ****)
    33 
    34 val collect_mem_simproc =
    35   Simplifier.simproc (theory "Set") "Collect_mem" ["Collect t"] (fn thy => fn ss =>
    36     fn S as Const ("Collect", Type ("fun", [_, T])) $ t =>
    37          let val (u, Ts, ps) = HOLogic.strip_psplits t
    38          in case u of
    39            (c as Const ("op :", _)) $ q $ S' =>
    40              (case try (HOLogic.strip_ptuple ps) q of
    41                 NONE => NONE
    42               | SOME ts =>
    43                   if not (loose_bvar (S', 0)) andalso
    44                     ts = map Bound (length ps downto 0)
    45                   then
    46                     let val simp = full_simp_tac (Simplifier.inherit_context ss
    47                       (HOL_basic_ss addsimps [split_paired_all, split_conv])) 1
    48                     in
    49                       SOME (Goal.prove (Simplifier.the_context ss) [] []
    50                         (Const ("==", T --> T --> propT) $ S $ S')
    51                         (K (EVERY
    52                           [rtac eq_reflection 1, rtac @{thm subset_antisym} 1,
    53                            rtac subsetI 1, dtac CollectD 1, simp,
    54                            rtac subsetI 1, rtac CollectI 1, simp])))
    55                     end
    56                   else NONE)
    57          | _ => NONE
    58          end
    59      | _ => NONE);
    60 
    61 (***********************************************************************************)
    62 (* simplifies (%x y. (x, y) : S & P x y) to (%x y. (x, y) : S Int {(x, y). P x y}) *)
    63 (* and        (%x y. (x, y) : S | P x y) to (%x y. (x, y) : S Un {(x, y). P x y})  *)
    64 (* used for converting "strong" (co)induction rules                                *)
    65 (***********************************************************************************)
    66 
    67 val anyt = Free ("t", TFree ("'t", []));
    68 
    69 fun strong_ind_simproc tab =
    70   Simplifier.simproc_i @{theory HOL} "strong_ind" [anyt] (fn thy => fn ss => fn t =>
    71     let
    72       fun close p t f =
    73         let val vs = Term.add_vars t []
    74         in Drule.instantiate' [] (rev (map (SOME o cterm_of thy o Var) vs))
    75           (p (fold (Logic.all o Var) vs t) f)
    76         end;
    77       fun mkop "op &" T x = SOME (Const (@{const_name Lattices.inf}, T --> T --> T), x)
    78         | mkop "op |" T x = SOME (Const (@{const_name Lattices.sup}, T --> T --> T), x)
    79         | mkop _ _ _ = NONE;
    80       fun mk_collect p T t =
    81         let val U = HOLogic.dest_setT T
    82         in HOLogic.Collect_const U $
    83           HOLogic.mk_psplits (HOLogic.flat_tuple_paths p) U HOLogic.boolT t
    84         end;
    85       fun decomp (Const (s, _) $ ((m as Const ("op :",
    86             Type (_, [_, Type (_, [T, _])]))) $ p $ S) $ u) =
    87               mkop s T (m, p, S, mk_collect p T (head_of u))
    88         | decomp (Const (s, _) $ u $ ((m as Const ("op :",
    89             Type (_, [_, Type (_, [T, _])]))) $ p $ S)) =
    90               mkop s T (m, p, mk_collect p T (head_of u), S)
    91         | decomp _ = NONE;
    92       val simp = full_simp_tac (Simplifier.inherit_context ss
    93         (HOL_basic_ss addsimps [mem_Collect_eq, split_conv])) 1;
    94       fun mk_rew t = (case strip_abs_vars t of
    95           [] => NONE
    96         | xs => (case decomp (strip_abs_body t) of
    97             NONE => NONE
    98           | SOME (bop, (m, p, S, S')) =>
    99               SOME (close (Goal.prove (Simplifier.the_context ss) [] [])
   100                 (Logic.mk_equals (t, list_abs (xs, m $ p $ (bop $ S $ S'))))
   101                 (K (EVERY
   102                   [rtac eq_reflection 1, REPEAT (rtac ext 1), rtac iffI 1,
   103                    EVERY [etac conjE 1, rtac IntI 1, simp, simp,
   104                      etac IntE 1, rtac conjI 1, simp, simp] ORELSE
   105                    EVERY [etac disjE 1, rtac UnI1 1, simp, rtac UnI2 1, simp,
   106                      etac UnE 1, rtac disjI1 1, simp, rtac disjI2 1, simp]])))
   107                 handle ERROR _ => NONE))
   108     in
   109       case strip_comb t of
   110         (h as Const (name, _), ts) => (case Symtab.lookup tab name of
   111           SOME _ =>
   112             let val rews = map mk_rew ts
   113             in
   114               if forall is_none rews then NONE
   115               else SOME (fold (fn th1 => fn th2 => combination th2 th1)
   116                 (map2 (fn SOME r => K r | NONE => reflexive o cterm_of thy)
   117                    rews ts) (reflexive (cterm_of thy h)))
   118             end
   119         | NONE => NONE)
   120       | _ => NONE
   121     end);
   122 
   123 (* only eta contract terms occurring as arguments of functions satisfying p *)
   124 fun eta_contract p =
   125   let
   126     fun eta b (Abs (a, T, body)) =
   127           (case eta b body of
   128              body' as (f $ Bound 0) =>
   129                if loose_bvar1 (f, 0) orelse not b then Abs (a, T, body')
   130                else incr_boundvars ~1 f
   131            | body' => Abs (a, T, body'))
   132       | eta b (t $ u) = eta b t $ eta (p (head_of t)) u
   133       | eta b t = t
   134   in eta false end;
   135 
   136 fun eta_contract_thm p =
   137   Conv.fconv_rule (Conv.then_conv (Thm.beta_conversion true, fn ct =>
   138     Thm.transitive (Thm.eta_conversion ct)
   139       (Thm.symmetric (Thm.eta_conversion
   140         (cterm_of (theory_of_cterm ct) (eta_contract p (term_of ct)))))));
   141 
   142 
   143 (***********************************************************)
   144 (* rules for converting between predicate and set notation *)
   145 (*                                                         *)
   146 (* rules for converting predicates to sets have the form   *)
   147 (* P (%x y. (x, y) : s) = (%x y. (x, y) : S s)             *)
   148 (*                                                         *)
   149 (* rules for converting sets to predicates have the form   *)
   150 (* S {(x, y). p x y} = {(x, y). P p x y}                   *)
   151 (*                                                         *)
   152 (* where s and p are parameters                            *)
   153 (***********************************************************)
   154 
   155 structure PredSetConvData = GenericDataFun
   156 (
   157   type T =
   158     {(* rules for converting predicates to sets *)
   159      to_set_simps: thm list,
   160      (* rules for converting sets to predicates *)
   161      to_pred_simps: thm list,
   162      (* arities of functions of type t set => ... => u set *)
   163      set_arities: (typ * (int list list option list * int list list option)) list Symtab.table,
   164      (* arities of functions of type (t => ... => bool) => u => ... => bool *)
   165      pred_arities: (typ * (int list list option list * int list list option)) list Symtab.table};
   166   val empty = {to_set_simps = [], to_pred_simps = [],
   167     set_arities = Symtab.empty, pred_arities = Symtab.empty};
   168   val extend = I;
   169   fun merge _
   170     ({to_set_simps = to_set_simps1, to_pred_simps = to_pred_simps1,
   171       set_arities = set_arities1, pred_arities = pred_arities1},
   172      {to_set_simps = to_set_simps2, to_pred_simps = to_pred_simps2,
   173       set_arities = set_arities2, pred_arities = pred_arities2}) : T =
   174     {to_set_simps = Thm.merge_thms (to_set_simps1, to_set_simps2),
   175      to_pred_simps = Thm.merge_thms (to_pred_simps1, to_pred_simps2),
   176      set_arities = Symtab.merge_list op = (set_arities1, set_arities2),
   177      pred_arities = Symtab.merge_list op = (pred_arities1, pred_arities2)};
   178 );
   179 
   180 fun name_type_of (Free p) = SOME p
   181   | name_type_of (Const p) = SOME p
   182   | name_type_of _ = NONE;
   183 
   184 fun map_type f (Free (s, T)) = Free (s, f T)
   185   | map_type f (Var (ixn, T)) = Var (ixn, f T)
   186   | map_type f _ = error "map_type";
   187 
   188 fun find_most_specific is_inst f eq xs T =
   189   find_first (fn U => is_inst (T, f U)
   190     andalso forall (fn U' => eq (f U, f U') orelse not
   191       (is_inst (T, f U') andalso is_inst (f U', f U)))
   192         xs) xs;
   193 
   194 fun lookup_arity thy arities (s, T) = case Symtab.lookup arities s of
   195     NONE => NONE
   196   | SOME xs => find_most_specific (Sign.typ_instance thy) fst (op =) xs T;
   197 
   198 fun lookup_rule thy f rules = find_most_specific
   199   (swap #> Pattern.matches thy) (f #> fst) (op aconv) rules;
   200 
   201 fun infer_arities thy arities (optf, t) fs = case strip_comb t of
   202     (Abs (s, T, u), []) => infer_arities thy arities (NONE, u) fs
   203   | (Abs _, _) => infer_arities thy arities (NONE, Envir.beta_norm t) fs
   204   | (u, ts) => (case Option.map (lookup_arity thy arities) (name_type_of u) of
   205       SOME (SOME (_, (arity, _))) =>
   206         (fold (infer_arities thy arities) (arity ~~ List.take (ts, length arity)) fs
   207            handle Subscript => error "infer_arities: bad term")
   208     | _ => fold (infer_arities thy arities) (map (pair NONE) ts)
   209       (case optf of
   210          NONE => fs
   211        | SOME f => AList.update op = (u, the_default f
   212            (Option.map (curry (gen_inter (op =)) f) (AList.lookup op = fs u))) fs));
   213 
   214 
   215 (**************************************************************)
   216 (*    derive the to_pred equation from the to_set equation    *)
   217 (*                                                            *)
   218 (* 1. instantiate each set parameter with {(x, y). p x y}     *)
   219 (* 2. apply %P. {(x, y). P x y} to both sides of the equation *)
   220 (* 3. simplify                                                *)
   221 (**************************************************************)
   222 
   223 fun mk_to_pred_inst thy fs =
   224   map (fn (x, ps) =>
   225     let
   226       val U = HOLogic.dest_setT (fastype_of x);
   227       val x' = map_type (K (HOLogic.strip_ptupleT ps U ---> HOLogic.boolT)) x
   228     in
   229       (cterm_of thy x,
   230        cterm_of thy (HOLogic.Collect_const U $
   231          HOLogic.mk_psplits ps U HOLogic.boolT x'))
   232     end) fs;
   233 
   234 fun mk_to_pred_eq p fs optfs' T thm =
   235   let
   236     val thy = theory_of_thm thm;
   237     val insts = mk_to_pred_inst thy fs;
   238     val thm' = Thm.instantiate ([], insts) thm;
   239     val thm'' = (case optfs' of
   240         NONE => thm' RS sym
   241       | SOME fs' =>
   242           let
   243             val (_, U) = split_last (binder_types T);
   244             val Ts = HOLogic.strip_ptupleT fs' U;
   245             (* FIXME: should cterm_instantiate increment indexes? *)
   246             val arg_cong' = Thm.incr_indexes (Thm.maxidx_of thm + 1) arg_cong;
   247             val (arg_cong_f, _) = arg_cong' |> cprop_of |> Drule.strip_imp_concl |>
   248               Thm.dest_comb |> snd |> Drule.strip_comb |> snd |> hd |> Thm.dest_comb
   249           in
   250             thm' RS (Drule.cterm_instantiate [(arg_cong_f,
   251               cterm_of thy (Abs ("P", Ts ---> HOLogic.boolT,
   252                 HOLogic.Collect_const U $ HOLogic.mk_psplits fs' U
   253                   HOLogic.boolT (Bound 0))))] arg_cong' RS sym)
   254           end)
   255   in
   256     Simplifier.simplify (HOL_basic_ss addsimps [mem_Collect_eq, split_conv]
   257       addsimprocs [collect_mem_simproc]) thm'' |>
   258         zero_var_indexes |> eta_contract_thm (equal p)
   259   end;
   260 
   261 
   262 (**** declare rules for converting predicates to sets ****)
   263 
   264 fun add ctxt thm (tab as {to_set_simps, to_pred_simps, set_arities, pred_arities}) =
   265   case prop_of thm of
   266     Const ("Trueprop", _) $ (Const ("op =", Type (_, [T, _])) $ lhs $ rhs) =>
   267       (case body_type T of
   268          Type ("bool", []) =>
   269            let
   270              val thy = Context.theory_of ctxt;
   271              fun factors_of t fs = case strip_abs_body t of
   272                  Const ("op :", _) $ u $ S =>
   273                    if is_Free S orelse is_Var S then
   274                      let val ps = HOLogic.flat_tuple_paths u
   275                      in (SOME ps, (S, ps) :: fs) end
   276                    else (NONE, fs)
   277                | _ => (NONE, fs);
   278              val (h, ts) = strip_comb lhs
   279              val (pfs, fs) = fold_map factors_of ts [];
   280              val ((h', ts'), fs') = (case rhs of
   281                  Abs _ => (case strip_abs_body rhs of
   282                      Const ("op :", _) $ u $ S =>
   283                        (strip_comb S, SOME (HOLogic.flat_tuple_paths u))
   284                    | _ => error "member symbol on right-hand side expected")
   285                | _ => (strip_comb rhs, NONE))
   286            in
   287              case (name_type_of h, name_type_of h') of
   288                (SOME (s, T), SOME (s', T')) =>
   289                  if exists (fn (U, _) =>
   290                    Sign.typ_instance thy (T', U) andalso
   291                    Sign.typ_instance thy (U, T'))
   292                      (Symtab.lookup_list set_arities s')
   293                  then
   294                    (warning ("Ignoring conversion rule for operator " ^ s'); tab)
   295                  else
   296                    {to_set_simps = thm :: to_set_simps,
   297                     to_pred_simps =
   298                       mk_to_pred_eq h fs fs' T' thm :: to_pred_simps,
   299                     set_arities = Symtab.insert_list op = (s',
   300                       (T', (map (AList.lookup op = fs) ts', fs'))) set_arities,
   301                     pred_arities = Symtab.insert_list op = (s,
   302                       (T, (pfs, fs'))) pred_arities}
   303              | _ => error "set / predicate constant expected"
   304            end
   305        | _ => error "equation between predicates expected")
   306   | _ => error "equation expected";
   307 
   308 val pred_set_conv_att = Thm.declaration_attribute
   309   (fn thm => fn ctxt => PredSetConvData.map (add ctxt thm) ctxt);
   310 
   311 
   312 (**** convert theorem in set notation to predicate notation ****)
   313 
   314 fun is_pred tab t =
   315   case Option.map (Symtab.lookup tab o fst) (name_type_of t) of
   316     SOME (SOME _) => true | _ => false;
   317 
   318 fun to_pred_simproc rules =
   319   let val rules' = map mk_meta_eq rules
   320   in
   321     Simplifier.simproc_i @{theory HOL} "to_pred" [anyt]
   322       (fn thy => K (lookup_rule thy (prop_of #> Logic.dest_equals) rules'))
   323   end;
   324 
   325 fun to_pred_proc thy rules t = case lookup_rule thy I rules t of
   326     NONE => NONE
   327   | SOME (lhs, rhs) =>
   328       SOME (Envir.subst_term
   329         (Pattern.match thy (lhs, t) (Vartab.empty, Vartab.empty)) rhs);
   330 
   331 fun to_pred thms ctxt thm =
   332   let
   333     val thy = Context.theory_of ctxt;
   334     val {to_pred_simps, set_arities, pred_arities, ...} =
   335       fold (add ctxt) thms (PredSetConvData.get ctxt);
   336     val fs = filter (is_Var o fst)
   337       (infer_arities thy set_arities (NONE, prop_of thm) []);
   338     (* instantiate each set parameter with {(x, y). p x y} *)
   339     val insts = mk_to_pred_inst thy fs
   340   in
   341     thm |>
   342     Thm.instantiate ([], insts) |>
   343     Simplifier.full_simplify (HOL_basic_ss addsimprocs
   344       [to_pred_simproc (mem_Collect_eq :: split_conv :: to_pred_simps)]) |>
   345     eta_contract_thm (is_pred pred_arities) |>
   346     RuleCases.save thm
   347   end;
   348 
   349 val to_pred_att = Thm.rule_attribute o to_pred;
   350     
   351 
   352 (**** convert theorem in predicate notation to set notation ****)
   353 
   354 fun to_set thms ctxt thm =
   355   let
   356     val thy = Context.theory_of ctxt;
   357     val {to_set_simps, pred_arities, ...} =
   358       fold (add ctxt) thms (PredSetConvData.get ctxt);
   359     val fs = filter (is_Var o fst)
   360       (infer_arities thy pred_arities (NONE, prop_of thm) []);
   361     (* instantiate each predicate parameter with %x y. (x, y) : s *)
   362     val insts = map (fn (x, ps) =>
   363       let
   364         val Ts = binder_types (fastype_of x);
   365         val T = HOLogic.mk_ptupleT ps Ts;
   366         val x' = map_type (K (HOLogic.mk_setT T)) x
   367       in
   368         (cterm_of thy x,
   369          cterm_of thy (list_abs (map (pair "x") Ts, HOLogic.mk_mem
   370            (HOLogic.mk_ptuple ps T (map Bound (length ps downto 0)), x'))))
   371       end) fs
   372   in
   373     thm |>
   374     Thm.instantiate ([], insts) |>
   375     Simplifier.full_simplify (HOL_basic_ss addsimps to_set_simps
   376         addsimprocs [strong_ind_simproc pred_arities, collect_mem_simproc]) |>
   377     RuleCases.save thm
   378   end;
   379 
   380 val to_set_att = Thm.rule_attribute o to_set;
   381 
   382 
   383 (**** preprocessor for code generator ****)
   384 
   385 fun codegen_preproc thy =
   386   let
   387     val {to_pred_simps, set_arities, pred_arities, ...} =
   388       PredSetConvData.get (Context.Theory thy);
   389     fun preproc thm =
   390       if exists_Const (fn (s, _) => case Symtab.lookup set_arities s of
   391           NONE => false
   392         | SOME arities => exists (fn (_, (xs, _)) =>
   393             forall is_none xs) arities) (prop_of thm)
   394       then
   395         thm |>
   396         Simplifier.full_simplify (HOL_basic_ss addsimprocs
   397           [to_pred_simproc (mem_Collect_eq :: split_conv :: to_pred_simps)]) |>
   398         eta_contract_thm (is_pred pred_arities)
   399       else thm
   400   in map preproc end;
   401 
   402 fun code_ind_att optmod = to_pred_att [] #> InductiveCodegen.add optmod NONE;
   403 
   404 
   405 (**** definition of inductive sets ****)
   406 
   407 fun add_ind_set_def
   408     {quiet_mode, verbose, kind, alt_name, coind, no_elim, no_ind, skip_mono, fork_mono}
   409     cs intros monos params cnames_syn ctxt =
   410   let
   411     val thy = ProofContext.theory_of ctxt;
   412     val {set_arities, pred_arities, to_pred_simps, ...} =
   413       PredSetConvData.get (Context.Proof ctxt);
   414     fun infer (Abs (_, _, t)) = infer t
   415       | infer (Const ("op :", _) $ t $ u) =
   416           infer_arities thy set_arities (SOME (HOLogic.flat_tuple_paths t), u)
   417       | infer (t $ u) = infer t #> infer u
   418       | infer _ = I;
   419     val new_arities = filter_out
   420       (fn (x as Free (_, T), _) => x mem params andalso length (binder_types T) > 1
   421         | _ => false) (fold (snd #> infer) intros []);
   422     val params' = map (fn x => (case AList.lookup op = new_arities x of
   423         SOME fs =>
   424           let
   425             val T = HOLogic.dest_setT (fastype_of x);
   426             val Ts = HOLogic.strip_ptupleT fs T;
   427             val x' = map_type (K (Ts ---> HOLogic.boolT)) x
   428           in
   429             (x, (x',
   430               (HOLogic.Collect_const T $
   431                  HOLogic.mk_psplits fs T HOLogic.boolT x',
   432                list_abs (map (pair "x") Ts, HOLogic.mk_mem
   433                  (HOLogic.mk_ptuple fs T (map Bound (length fs downto 0)),
   434                   x)))))
   435           end
   436        | NONE => (x, (x, (x, x))))) params;
   437     val (params1, (params2, params3)) =
   438       params' |> map snd |> split_list ||> split_list;
   439     val paramTs = map fastype_of params;
   440 
   441     (* equations for converting sets to predicates *)
   442     val ((cs', cs_info), eqns) = cs |> map (fn c as Free (s, T) =>
   443       let
   444         val fs = the_default [] (AList.lookup op = new_arities c);
   445         val (Us, U) = split_last (binder_types T);
   446         val _ = Us = paramTs orelse error (Pretty.string_of (Pretty.chunks
   447           [Pretty.str "Argument types",
   448            Pretty.block (Pretty.commas (map (Syntax.pretty_typ ctxt) Us)),
   449            Pretty.str ("of " ^ s ^ " do not agree with types"),
   450            Pretty.block (Pretty.commas (map (Syntax.pretty_typ ctxt) paramTs)),
   451            Pretty.str "of declared parameters"]));
   452         val Ts = HOLogic.strip_ptupleT fs U;
   453         val c' = Free (s ^ "p",
   454           map fastype_of params1 @ Ts ---> HOLogic.boolT)
   455       in
   456         ((c', (fs, U, Ts)),
   457          (list_comb (c, params2),
   458           HOLogic.Collect_const U $ HOLogic.mk_psplits fs U HOLogic.boolT
   459             (list_comb (c', params1))))
   460       end) |> split_list |>> split_list;
   461     val eqns' = eqns @
   462       map (prop_of #> HOLogic.dest_Trueprop #> HOLogic.dest_eq)
   463         (mem_Collect_eq :: split_conv :: to_pred_simps);
   464 
   465     (* predicate version of the introduction rules *)
   466     val intros' =
   467       map (fn (name_atts, t) => (name_atts,
   468         t |>
   469         map_aterms (fn u =>
   470           (case AList.lookup op = params' u of
   471              SOME (_, (u', _)) => u'
   472            | NONE => u)) |>
   473         Pattern.rewrite_term thy [] [to_pred_proc thy eqns'] |>
   474         eta_contract (member op = cs' orf is_pred pred_arities))) intros;
   475     val cnames_syn' = map (fn (b, _) => (Binding.suffix_name "p" b, NoSyn)) cnames_syn;
   476     val monos' = map (to_pred [] (Context.Proof ctxt)) monos;
   477     val ({preds, intrs, elims, raw_induct, ...}, ctxt1) =
   478       Inductive.add_ind_def
   479         {quiet_mode = quiet_mode, verbose = verbose, kind = kind, alt_name = Binding.empty,
   480           coind = coind, no_elim = no_elim, no_ind = no_ind,
   481           skip_mono = skip_mono, fork_mono = fork_mono}
   482         cs' intros' monos' params1 cnames_syn' ctxt;
   483 
   484     (* define inductive sets using previously defined predicates *)
   485     val (defs, ctxt2) = fold_map (LocalTheory.define Thm.internalK)
   486       (map (fn ((c_syn, (fs, U, _)), p) => (c_syn, (Attrib.empty_binding,
   487          fold_rev lambda params (HOLogic.Collect_const U $
   488            HOLogic.mk_psplits fs U HOLogic.boolT (list_comb (p, params3))))))
   489          (cnames_syn ~~ cs_info ~~ preds)) ctxt1;
   490 
   491     (* prove theorems for converting predicate to set notation *)
   492     val ctxt3 = fold
   493       (fn (((p, c as Free (s, _)), (fs, U, Ts)), (_, (_, def))) => fn ctxt =>
   494         let val conv_thm =
   495           Goal.prove ctxt (map (fst o dest_Free) params) []
   496             (HOLogic.mk_Trueprop (HOLogic.mk_eq
   497               (list_comb (p, params3),
   498                list_abs (map (pair "x") Ts, HOLogic.mk_mem
   499                  (HOLogic.mk_ptuple fs U (map Bound (length fs downto 0)),
   500                   list_comb (c, params))))))
   501             (K (REPEAT (rtac ext 1) THEN simp_tac (HOL_basic_ss addsimps
   502               [def, mem_Collect_eq, split_conv]) 1))
   503         in
   504           ctxt |> LocalTheory.note kind ((Binding.name (s ^ "p_" ^ s ^ "_eq"),
   505             [Attrib.internal (K pred_set_conv_att)]),
   506               [conv_thm]) |> snd
   507         end) (preds ~~ cs ~~ cs_info ~~ defs) ctxt2;
   508 
   509     (* convert theorems to set notation *)
   510     val rec_name =
   511       if Binding.is_empty alt_name then
   512         Binding.name (space_implode "_" (map (Binding.name_of o fst) cnames_syn))
   513       else alt_name;
   514     val cnames = map (LocalTheory.full_name ctxt3 o #1) cnames_syn;  (* FIXME *)
   515     val (intr_names, intr_atts) = split_list (map fst intros);
   516     val raw_induct' = to_set [] (Context.Proof ctxt3) raw_induct;
   517     val (intrs', elims', induct, ctxt4) =
   518       Inductive.declare_rules kind rec_name coind no_ind cnames
   519       (map (to_set [] (Context.Proof ctxt3)) intrs) intr_names intr_atts
   520       (map (fn th => (to_set [] (Context.Proof ctxt3) th,
   521          map fst (fst (RuleCases.get th)))) elims)
   522       raw_induct' ctxt3
   523   in
   524     ({intrs = intrs', elims = elims', induct = induct,
   525       raw_induct = raw_induct', preds = map fst defs},
   526      ctxt4)
   527   end;
   528 
   529 val add_inductive_i = Inductive.gen_add_inductive_i add_ind_set_def;
   530 val add_inductive = Inductive.gen_add_inductive add_ind_set_def;
   531 
   532 val mono_add_att = to_pred_att [] #> Inductive.mono_add;
   533 val mono_del_att = to_pred_att [] #> Inductive.mono_del;
   534 
   535 
   536 (** package setup **)
   537 
   538 (* setup theory *)
   539 
   540 val setup =
   541   Attrib.setup @{binding pred_set_conv} (Scan.succeed pred_set_conv_att)
   542     "declare rules for converting between predicate and set notation" #>
   543   Attrib.setup @{binding to_set} (Attrib.thms >> to_set_att) "convert rule to set notation" #>
   544   Attrib.setup @{binding to_pred} (Attrib.thms >> to_pred_att) "convert rule to predicate notation" #>
   545   Attrib.setup @{binding code_ind_set}
   546     (Scan.lift (Scan.option (Args.$$$ "target" |-- Args.colon |-- Args.name) >> code_ind_att))
   547     "introduction rules for executable predicates" #>
   548   Codegen.add_preprocessor codegen_preproc #>
   549   Attrib.setup @{binding mono_set} (Attrib.add_del mono_add_att mono_del_att)
   550     "declaration of monotonicity rule for set operators" #>
   551   Context.theory_map (Simplifier.map_ss (fn ss => ss addsimprocs [collect_mem_simproc]));
   552 
   553 
   554 (* outer syntax *)
   555 
   556 local structure P = OuterParse and K = OuterKeyword in
   557 
   558 val ind_set_decl = Inductive.gen_ind_decl add_ind_set_def;
   559 
   560 val _ =
   561   OuterSyntax.local_theory' "inductive_set" "define inductive sets" K.thy_decl (ind_set_decl false);
   562 
   563 val _ =
   564   OuterSyntax.local_theory' "coinductive_set" "define coinductive sets" K.thy_decl (ind_set_decl true);
   565 
   566 end;
   567 
   568 end;