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