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