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