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