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