src/HOL/Tools/inductive_realizer.ML
author wenzelm
Fri Oct 21 18:14:38 2005 +0200 (2005-10-21)
changeset 17959 8db36a108213
parent 17485 c39871c52977
child 18008 f193815cab2c
permissions -rw-r--r--
OldGoals;
berghofe@13710
     1
(*  Title:      HOL/Tools/inductive_realizer.ML
berghofe@13710
     2
    ID:         $Id$
berghofe@13710
     3
    Author:     Stefan Berghofer, TU Muenchen
berghofe@13710
     4
berghofe@13710
     5
Porgram extraction from proofs involving inductive predicates:
berghofe@13710
     6
Realizers for induction and elimination rules
berghofe@13710
     7
*)
berghofe@13710
     8
berghofe@13710
     9
signature INDUCTIVE_REALIZER =
berghofe@13710
    10
sig
berghofe@13710
    11
  val add_ind_realizers: string -> string list -> theory -> theory
berghofe@13710
    12
  val setup: (theory -> theory) list
berghofe@13710
    13
end;
berghofe@13710
    14
berghofe@13710
    15
structure InductiveRealizer : INDUCTIVE_REALIZER =
berghofe@13710
    16
struct
berghofe@13710
    17
berghofe@13710
    18
val all_simps = map (symmetric o mk_meta_eq) (thms "HOL.all_simps");
berghofe@13710
    19
berghofe@13710
    20
fun prf_of thm =
berghofe@13710
    21
  let val {sign, prop, der = (_, prf), ...} = rep_thm thm
berghofe@13710
    22
  in Reconstruct.reconstruct_proof sign prop prf end;
berghofe@13710
    23
berghofe@13710
    24
fun forall_intr_prf (t, prf) =
berghofe@13710
    25
  let val (a, T) = (case t of Var ((a, _), T) => (a, T) | Free p => p)
skalberg@15531
    26
  in Abst (a, SOME T, Proofterm.prf_abstract_over t prf) end;
berghofe@13710
    27
berghofe@13710
    28
fun subsets [] = [[]]
berghofe@13710
    29
  | subsets (x::xs) =
berghofe@13710
    30
      let val ys = subsets xs
berghofe@13710
    31
      in ys @ map (cons x) ys end;
berghofe@13710
    32
berghofe@13710
    33
val set_of = fst o dest_Const o head_of o snd o HOLogic.dest_mem;
berghofe@13710
    34
berghofe@13710
    35
fun strip_all t =
berghofe@13710
    36
  let
berghofe@13710
    37
    fun strip used (Const ("all", _) $ Abs (s, T, t)) =
berghofe@13710
    38
          let val s' = variant used s
berghofe@13710
    39
          in strip (s'::used) (subst_bound (Free (s', T), t)) end
berghofe@13710
    40
      | strip used ((t as Const ("==>", _) $ P) $ Q) = t $ strip used Q
berghofe@13710
    41
      | strip _ t = t;
berghofe@13710
    42
  in strip (add_term_free_names (t, [])) t end;
berghofe@13710
    43
skalberg@15574
    44
fun relevant_vars prop = foldr (fn
berghofe@13710
    45
      (Var ((a, i), T), vs) => (case strip_type T of
berghofe@13710
    46
        (_, Type (s, _)) => if s mem ["bool", "set"] then (a, T) :: vs else vs
berghofe@13710
    47
      | _ => vs)
skalberg@15574
    48
    | (_, vs) => vs) [] (term_vars prop);
berghofe@13710
    49
berghofe@13710
    50
fun params_of intr = map (fst o fst o dest_Var) (term_vars
berghofe@13710
    51
  (snd (HOLogic.dest_mem (HOLogic.dest_Trueprop
berghofe@13710
    52
    (Logic.strip_imp_concl intr)))));
berghofe@13710
    53
berghofe@13710
    54
fun dt_of_intrs thy vs intrs =
berghofe@13710
    55
  let
berghofe@13710
    56
    val iTs = term_tvars (prop_of (hd intrs));
berghofe@13710
    57
    val Tvs = map TVar iTs;
berghofe@13710
    58
    val (_ $ (_ $ _ $ S)) = Logic.strip_imp_concl (prop_of (hd intrs));
berghofe@13710
    59
    val (Const (s, _), ts) = strip_comb S;
berghofe@13710
    60
    val params = map dest_Var ts;
berghofe@13710
    61
    val tname = space_implode "_" (Sign.base_name s ^ "T" :: vs);
berghofe@13710
    62
    fun constr_of_intr intr = (Sign.base_name (Thm.name_of_thm intr),
wenzelm@16861
    63
      map (Type.unvarifyT o snd) (rev (Term.add_vars (prop_of intr) []) \\ params) @
berghofe@13710
    64
        filter_out (equal Extraction.nullT) (map
berghofe@13710
    65
          (Type.unvarifyT o Extraction.etype_of thy vs []) (prems_of intr)),
berghofe@13710
    66
            NoSyn);
berghofe@13710
    67
  in (map (fn a => "'" ^ a) vs @ map (fst o fst) iTs, tname, NoSyn,
berghofe@13710
    68
    map constr_of_intr intrs)
berghofe@13710
    69
  end;
berghofe@13710
    70
berghofe@13710
    71
fun mk_rlz T = Const ("realizes", [T, HOLogic.boolT] ---> HOLogic.boolT);
berghofe@13710
    72
berghofe@13710
    73
(** turn "P" into "%r x. realizes r (P x)" or "%r x. realizes r (x : P)" **)
berghofe@13710
    74
berghofe@13710
    75
fun gen_rvar vs (t as Var ((a, 0), T)) =
berghofe@13710
    76
      let val U = TVar (("'" ^ a, 0), HOLogic.typeS)
berghofe@13710
    77
      in case try HOLogic.dest_setT T of
skalberg@15531
    78
          NONE => if body_type T <> HOLogic.boolT then t else
berghofe@13710
    79
            let
berghofe@13710
    80
              val Ts = binder_types T;
berghofe@13710
    81
              val i = length Ts;
berghofe@13710
    82
              val xs = map (pair "x") Ts;
berghofe@13710
    83
              val u = list_comb (t, map Bound (i - 1 downto 0))
berghofe@13710
    84
            in 
berghofe@13710
    85
              if a mem vs then
berghofe@13710
    86
                list_abs (("r", U) :: xs, mk_rlz U $ Bound i $ u)
berghofe@13710
    87
              else list_abs (xs, mk_rlz Extraction.nullT $ Extraction.nullt $ u)
berghofe@13710
    88
            end
skalberg@15531
    89
        | SOME T' => if a mem vs then
berghofe@13710
    90
              Abs ("r", U, Abs ("x", T', mk_rlz U $ Bound 1 $
berghofe@13710
    91
                (HOLogic.mk_mem (Bound 0, t))))
berghofe@13710
    92
            else Abs ("x", T', mk_rlz Extraction.nullT $ Extraction.nullt $
berghofe@13710
    93
              (HOLogic.mk_mem (Bound 0, t)))
berghofe@13710
    94
      end
berghofe@13710
    95
  | gen_rvar _ t = t;
berghofe@13710
    96
berghofe@13710
    97
fun mk_realizes_eqn n vs intrs =
berghofe@13710
    98
  let
berghofe@13710
    99
    val iTs = term_tvars (prop_of (hd intrs));
berghofe@13710
   100
    val Tvs = map TVar iTs;
berghofe@13710
   101
    val _ $ (_ $ _ $ S) = concl_of (hd intrs);
berghofe@13710
   102
    val (Const (s, T), ts') = strip_comb S;
berghofe@13710
   103
    val setT = body_type T;
berghofe@13710
   104
    val elT = HOLogic.dest_setT setT;
berghofe@13710
   105
    val x = Var (("x", 0), elT);
berghofe@13710
   106
    val rT = if n then Extraction.nullT
berghofe@13710
   107
      else Type (space_implode "_" (s ^ "T" :: vs),
berghofe@13710
   108
        map (fn a => TVar (("'" ^ a, 0), HOLogic.typeS)) vs @ Tvs);
berghofe@13710
   109
    val r = if n then Extraction.nullt else Var ((Sign.base_name s, 0), rT);
berghofe@13710
   110
    val rvs = relevant_vars S;
berghofe@13710
   111
    val vs' = map fst rvs \\ vs;
berghofe@13710
   112
    val rname = space_implode "_" (s ^ "R" :: vs);
berghofe@13710
   113
berghofe@13710
   114
    fun mk_Tprem n v =
haftmann@17485
   115
      let val T = (the o AList.lookup (op =) rvs) v
berghofe@13710
   116
      in (Const ("typeof", T --> Type ("Type", [])) $ Var ((v, 0), T),
berghofe@13710
   117
        Extraction.mk_typ (if n then Extraction.nullT
berghofe@13710
   118
          else TVar (("'" ^ v, 0), HOLogic.typeS)))
berghofe@13710
   119
      end;
berghofe@13710
   120
berghofe@13710
   121
    val prems = map (mk_Tprem true) vs' @ map (mk_Tprem false) vs;
berghofe@13710
   122
    val ts = map (gen_rvar vs) ts';
berghofe@13710
   123
    val argTs = map fastype_of ts;
berghofe@13710
   124
berghofe@13710
   125
  in ((prems, (Const ("typeof", setT --> Type ("Type", [])) $ S,
berghofe@13710
   126
       Extraction.mk_typ rT)),
berghofe@13710
   127
    (prems, (mk_rlz rT $ r $ HOLogic.mk_mem (x, S),
berghofe@13710
   128
       if n then
berghofe@13710
   129
         HOLogic.mk_mem (x, list_comb (Const (rname, argTs ---> setT), ts))
berghofe@13710
   130
       else HOLogic.mk_mem (HOLogic.mk_prod (r, x), list_comb (Const (rname,
berghofe@13710
   131
         argTs ---> HOLogic.mk_setT (HOLogic.mk_prodT (rT, elT))), ts)))))
berghofe@13710
   132
  end;
berghofe@13710
   133
berghofe@13710
   134
fun fun_of_prem thy rsets vs params rule intr =
berghofe@13710
   135
  let
berghofe@13710
   136
    (* add_term_vars and Term.add_vars may return variables in different order *)
berghofe@13710
   137
    val args = map (Free o apfst fst o dest_Var)
berghofe@13710
   138
      (add_term_vars (prop_of intr, []) \\ map Var params);
berghofe@13710
   139
    val args' = map (Free o apfst fst)
wenzelm@16861
   140
      (Term.add_vars (prop_of intr) [] \\ params);
berghofe@13710
   141
    val rule' = strip_all rule;
berghofe@13710
   142
    val conclT = Extraction.etype_of thy vs [] (Logic.strip_imp_concl rule');
berghofe@13710
   143
    val used = map (fst o dest_Free) args;
berghofe@13710
   144
berghofe@13710
   145
    fun is_rec t = not (null (term_consts t inter rsets));
berghofe@13710
   146
berghofe@13710
   147
    fun is_meta (Const ("all", _) $ Abs (s, _, P)) = is_meta P
berghofe@13710
   148
      | is_meta (Const ("==>", _) $ _ $ Q) = is_meta Q
berghofe@13710
   149
      | is_meta (Const ("Trueprop", _) $ (Const ("op :", _) $ _ $ _)) = true
berghofe@13710
   150
      | is_meta _ = false;
berghofe@13710
   151
berghofe@13710
   152
    fun fun_of ts rts args used (prem :: prems) =
berghofe@13710
   153
          let
berghofe@13710
   154
            val T = Extraction.etype_of thy vs [] prem;
berghofe@13710
   155
            val [x, r] = variantlist (["x", "r"], used)
berghofe@13710
   156
          in if T = Extraction.nullT
berghofe@13710
   157
            then fun_of ts rts args used prems
berghofe@13710
   158
            else if is_rec prem then
berghofe@13710
   159
              if is_meta prem then
berghofe@13710
   160
                let
berghofe@13710
   161
                  val prem' :: prems' = prems;
berghofe@13710
   162
                  val U = Extraction.etype_of thy vs [] prem';
berghofe@13710
   163
                in if U = Extraction.nullT
berghofe@13710
   164
                  then fun_of (Free (x, T) :: ts)
berghofe@13710
   165
                    (Free (r, binder_types T ---> HOLogic.unitT) :: rts)
berghofe@13710
   166
                    (Free (x, T) :: args) (x :: r :: used) prems'
berghofe@13710
   167
                  else fun_of (Free (x, T) :: ts) (Free (r, U) :: rts)
berghofe@13710
   168
                    (Free (r, U) :: Free (x, T) :: args) (x :: r :: used) prems'
berghofe@13710
   169
                end
berghofe@13710
   170
              else (case strip_type T of
berghofe@13710
   171
                  (Ts, Type ("*", [T1, T2])) =>
berghofe@13710
   172
                    let
berghofe@13710
   173
                      val fx = Free (x, Ts ---> T1);
berghofe@13710
   174
                      val fr = Free (r, Ts ---> T2);
berghofe@13710
   175
                      val bs = map Bound (length Ts - 1 downto 0);
berghofe@13710
   176
                      val t = list_abs (map (pair "z") Ts,
berghofe@13710
   177
                        HOLogic.mk_prod (list_comb (fx, bs), list_comb (fr, bs)))
berghofe@13710
   178
                    in fun_of (fx :: ts) (fr :: rts) (t::args)
berghofe@13710
   179
                      (x :: r :: used) prems
berghofe@13710
   180
                    end
berghofe@13710
   181
                | (Ts, U) => fun_of (Free (x, T) :: ts)
berghofe@13710
   182
                    (Free (r, binder_types T ---> HOLogic.unitT) :: rts)
berghofe@13710
   183
                    (Free (x, T) :: args) (x :: r :: used) prems)
berghofe@13710
   184
            else fun_of (Free (x, T) :: ts) rts (Free (x, T) :: args)
berghofe@13710
   185
              (x :: used) prems
berghofe@13710
   186
          end
berghofe@13710
   187
      | fun_of ts rts args used [] =
berghofe@13710
   188
          let val xs = rev (rts @ ts)
berghofe@13710
   189
          in if conclT = Extraction.nullT
berghofe@13710
   190
            then list_abs_free (map dest_Free xs, HOLogic.unit)
berghofe@13710
   191
            else list_abs_free (map dest_Free xs, list_comb
berghofe@13710
   192
              (Free ("r" ^ Sign.base_name (Thm.name_of_thm intr),
berghofe@13710
   193
                map fastype_of (rev args) ---> conclT), rev args))
berghofe@13710
   194
          end
berghofe@13710
   195
berghofe@13921
   196
  in fun_of args' [] (rev args) used (Logic.strip_imp_prems rule') end;
berghofe@13710
   197
berghofe@13710
   198
fun indrule_realizer thy induct raw_induct rsets params vs rec_names rss intrs dummies =
berghofe@13710
   199
  let
berghofe@13710
   200
    val concls = HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of raw_induct));
skalberg@15570
   201
    val premss = List.mapPartial (fn (s, rs) => if s mem rsets then
skalberg@15570
   202
      SOME (map (fn r => List.nth (prems_of raw_induct,
skalberg@15570
   203
        find_index_eq (prop_of r) (map prop_of intrs))) rs) else NONE) rss;
skalberg@15570
   204
    val concls' = List.mapPartial (fn (s, _) => if s mem rsets then
berghofe@13710
   205
        find_first (fn concl => s mem term_consts concl) concls
skalberg@15531
   206
      else NONE) rss;
skalberg@15570
   207
    val fs = List.concat (snd (foldl_map (fn (intrs, (prems, dummy)) =>
berghofe@13710
   208
      let
berghofe@13710
   209
        val (intrs1, intrs2) = splitAt (length prems, intrs);
berghofe@13710
   210
        val fs = map (fn (rule, intr) =>
berghofe@13710
   211
          fun_of_prem thy rsets vs params rule intr) (prems ~~ intrs1)
berghofe@13710
   212
      in (intrs2, if dummy then Const ("arbitrary",
berghofe@13710
   213
          HOLogic.unitT --> body_type (fastype_of (hd fs))) :: fs
berghofe@13710
   214
        else fs)
berghofe@13710
   215
      end) (intrs, (premss ~~ dummies))));
wenzelm@16861
   216
    val frees = fold Term.add_frees fs [];
berghofe@13710
   217
    val Ts = map fastype_of fs;
skalberg@15570
   218
    val rlzs = List.mapPartial (fn (a, concl) =>
berghofe@13710
   219
      let val T = Extraction.etype_of thy vs [] concl
skalberg@15531
   220
      in if T = Extraction.nullT then NONE
skalberg@15531
   221
        else SOME (list_comb (Const (a, Ts ---> T), fs))
berghofe@13710
   222
      end) (rec_names ~~ concls')
berghofe@13710
   223
  in if null rlzs then Extraction.nullt else
berghofe@13710
   224
    let
berghofe@13710
   225
      val r = foldr1 HOLogic.mk_prod rlzs;
berghofe@13710
   226
      val x = Free ("x", Extraction.etype_of thy vs [] (hd (prems_of induct)));
berghofe@13710
   227
      fun name_of_fn intr = "r" ^ Sign.base_name (Thm.name_of_thm intr);
skalberg@15570
   228
      val r' = list_abs_free (List.mapPartial (fn intr =>
haftmann@17485
   229
        Option.map (pair (name_of_fn intr)) (AList.lookup (op =) frees (name_of_fn intr))) intrs,
berghofe@13710
   230
          if length concls = 1 then r $ x else r)
berghofe@13710
   231
    in
berghofe@13710
   232
      if length concls = 1 then lambda x r' else r'
berghofe@13710
   233
    end
berghofe@13710
   234
  end;
berghofe@13710
   235
berghofe@13710
   236
fun add_dummy name dname (x as (_, (vs, s, mfx, cs))) =
berghofe@13710
   237
  if name = s then (true, (vs, s, mfx, (dname, [HOLogic.unitT], NoSyn) :: cs))
berghofe@13710
   238
  else x;
berghofe@13710
   239
berghofe@13710
   240
fun add_dummies f dts used thy =
berghofe@14888
   241
  apsnd (pair (map fst dts)) (f (map snd dts) thy)
berghofe@14888
   242
  handle DatatypeAux.Datatype_Empty name' =>
berghofe@13710
   243
      let
berghofe@14888
   244
        val name = Sign.base_name name';
berghofe@13710
   245
        val dname = variant used "Dummy"
berghofe@13710
   246
      in add_dummies f (map (add_dummy name dname) dts) (dname :: used) thy
berghofe@14888
   247
      end;
berghofe@13710
   248
berghofe@13710
   249
fun mk_realizer thy vs params ((rule, rrule), rt) =
berghofe@13710
   250
  let
berghofe@13725
   251
    val prems = prems_of rule ~~ prems_of rrule;
berghofe@13725
   252
    val rvs = map fst (relevant_vars (prop_of rule));
wenzelm@16861
   253
    val xs = rev (Term.add_vars (prop_of rule) []);
berghofe@13725
   254
    val vs1 = map Var (filter_out (fn ((a, _), _) => a mem rvs) xs);
wenzelm@16861
   255
    val rlzvs = rev (Term.add_vars (prop_of rrule) []);
haftmann@17485
   256
    val vs2 = map (fn (ixn, _) => Var (ixn, (the o AList.lookup (op =) rlzvs) ixn)) xs;
berghofe@13725
   257
    val rs = gen_rems (op = o pairself fst) (rlzvs, xs);
berghofe@13710
   258
berghofe@13710
   259
    fun mk_prf _ [] prf = prf
berghofe@13725
   260
      | mk_prf rs ((prem, rprem) :: prems) prf =
berghofe@13725
   261
          if Extraction.etype_of thy vs [] prem = Extraction.nullT
skalberg@15531
   262
          then AbsP ("H", SOME rprem, mk_prf rs prems prf)
skalberg@15531
   263
          else forall_intr_prf (Var (hd rs), AbsP ("H", SOME rprem,
berghofe@13725
   264
            mk_prf (tl rs) prems prf));
berghofe@13710
   265
berghofe@13710
   266
  in (Thm.name_of_thm rule, (vs,
berghofe@13710
   267
    if rt = Extraction.nullt then rt else
skalberg@15574
   268
      foldr (uncurry lambda) rt vs1,
skalberg@15574
   269
    foldr forall_intr_prf (mk_prf rs prems (Proofterm.proof_combP
skalberg@15574
   270
      (prf_of rrule, map PBound (length prems - 1 downto 0)))) vs2))
berghofe@13710
   271
  end;
berghofe@13710
   272
haftmann@17485
   273
fun add_rule r rss =
berghofe@13710
   274
  let
berghofe@13710
   275
    val _ $ (_ $ _ $ S) = concl_of r;
berghofe@13710
   276
    val (Const (s, _), _) = strip_comb S;
haftmann@17485
   277
  in
haftmann@17485
   278
    rss
haftmann@17485
   279
    |> AList.default (op =) (s, [])
haftmann@17485
   280
    |> AList.map_entry (op =) s (fn rs => rs @ [r])
haftmann@17485
   281
  end;
berghofe@13710
   282
berghofe@13710
   283
fun add_ind_realizer rsets intrs induct raw_induct elims (thy, vs) =
berghofe@13710
   284
  let
berghofe@13710
   285
    val iTs = term_tvars (prop_of (hd intrs));
berghofe@13710
   286
    val ar = length vs + length iTs;
berghofe@13710
   287
    val (_ $ (_ $ _ $ S)) = Logic.strip_imp_concl (prop_of (hd intrs));
berghofe@13710
   288
    val (_, params) = strip_comb S;
berghofe@13710
   289
    val params' = map dest_Var params;
haftmann@17485
   290
    val rss = [] |> Library.fold add_rule intrs;
berghofe@13710
   291
    val (prfx, _) = split_last (NameSpace.unpack (fst (hd rss)));
berghofe@13710
   292
    val tnames = map (fn s => space_implode "_" (s ^ "T" :: vs)) rsets;
wenzelm@16123
   293
berghofe@13710
   294
    val thy1 = thy |>
berghofe@13710
   295
      Theory.root_path |>
berghofe@13710
   296
      Theory.add_path (NameSpace.pack prfx);
berghofe@13710
   297
    val (ty_eqs, rlz_eqs) = split_list
berghofe@13710
   298
      (map (fn (s, rs) => mk_realizes_eqn (not (s mem rsets)) vs rs) rss);
berghofe@13710
   299
berghofe@13710
   300
    val thy1' = thy1 |>
berghofe@13710
   301
      Theory.copy |>
berghofe@13710
   302
      Theory.add_types (map (fn s => (Sign.base_name s, ar, NoSyn)) tnames) |>
berghofe@13710
   303
      Theory.add_arities_i (map (fn s =>
berghofe@13710
   304
        (s, replicate ar HOLogic.typeS, HOLogic.typeS)) tnames) |>
berghofe@13710
   305
        Extraction.add_typeof_eqns_i ty_eqs;
skalberg@15570
   306
    val dts = List.mapPartial (fn (s, rs) => if s mem rsets then
skalberg@15531
   307
      SOME (dt_of_intrs thy1' vs rs) else NONE) rss;
berghofe@13710
   308
berghofe@13710
   309
    (** datatype representing computational content of inductive set **)
berghofe@13710
   310
berghofe@13710
   311
    val (thy2, (dummies, dt_info)) = thy1 |>
skalberg@15531
   312
      (if null dts then rpair ([], NONE) else
skalberg@15531
   313
        apsnd (apsnd SOME) o add_dummies (DatatypePackage.add_datatype_i false false
berghofe@13710
   314
          (map #2 dts)) (map (pair false) dts) []) |>>
berghofe@13710
   315
      Extraction.add_typeof_eqns_i ty_eqs |>>
berghofe@13710
   316
      Extraction.add_realizes_eqns_i rlz_eqs;
skalberg@15570
   317
    fun get f x = getOpt (Option.map f x, []);
berghofe@13710
   318
    val rec_names = distinct (map (fst o dest_Const o head_of o fst o
berghofe@13710
   319
      HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) (get #rec_thms dt_info));
berghofe@13710
   320
    val (_, constrss) = foldl_map (fn ((recs, dummies), (s, rs)) =>
berghofe@13710
   321
      if s mem rsets then
berghofe@13710
   322
        let
berghofe@13710
   323
          val (d :: dummies') = dummies;
berghofe@13710
   324
          val (recs1, recs2) = splitAt (length rs, if d then tl recs else recs)
berghofe@13710
   325
        in ((recs2, dummies'), map (head_of o hd o rev o snd o strip_comb o
berghofe@13710
   326
          fst o HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) recs1)
berghofe@13710
   327
        end
berghofe@13710
   328
      else ((recs, dummies), replicate (length rs) Extraction.nullt))
berghofe@13710
   329
        ((get #rec_thms dt_info, dummies), rss);
berghofe@13725
   330
    val rintrs = map (fn (intr, c) => Pattern.eta_contract
berghofe@13710
   331
      (Extraction.realizes_of thy2 vs
berghofe@13710
   332
        c (prop_of (forall_intr_list (map (cterm_of (sign_of thy2) o Var)
wenzelm@16861
   333
          (rev (Term.add_vars (prop_of intr) []) \\ params')) intr))))
skalberg@15570
   334
            (intrs ~~ List.concat constrss);
berghofe@13710
   335
    val rlzsets = distinct (map (fn rintr => snd (HOLogic.dest_mem
berghofe@13710
   336
      (HOLogic.dest_Trueprop (Logic.strip_assums_concl rintr)))) rintrs);
berghofe@13710
   337
berghofe@13710
   338
    (** realizability predicate **)
berghofe@13710
   339
berghofe@13710
   340
    val (thy3', ind_info) = thy2 |>
berghofe@13710
   341
      InductivePackage.add_inductive_i false true "" false false false
berghofe@13710
   342
        (map Logic.unvarify rlzsets) (map (fn (rintr, intr) =>
berghofe@13710
   343
          ((Sign.base_name (Thm.name_of_thm intr), strip_all
berghofe@13710
   344
            (Logic.unvarify rintr)), [])) (rintrs ~~ intrs)) [] |>>
berghofe@13710
   345
      Theory.absolute_path;
berghofe@13710
   346
    val thy3 = PureThy.hide_thms false
berghofe@13710
   347
      (map Thm.name_of_thm (#intrs ind_info)) thy3';
berghofe@13710
   348
berghofe@13710
   349
    (** realizer for induction rule **)
berghofe@13710
   350
skalberg@15570
   351
    val Ps = List.mapPartial (fn _ $ M $ P => if set_of M mem rsets then
skalberg@15531
   352
      SOME (fst (fst (dest_Var (head_of P)))) else NONE)
berghofe@13710
   353
        (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of raw_induct)));
berghofe@13710
   354
berghofe@13710
   355
    fun add_ind_realizer (thy, Ps) =
berghofe@13710
   356
      let
berghofe@13710
   357
        val r = indrule_realizer thy induct raw_induct rsets params'
berghofe@13710
   358
          (vs @ Ps) rec_names rss intrs dummies;
berghofe@13725
   359
        val rlz = strip_all (Logic.unvarify
berghofe@13725
   360
          (Extraction.realizes_of thy (vs @ Ps) r (prop_of induct)));
berghofe@13710
   361
        val rews = map mk_meta_eq
berghofe@13710
   362
          (fst_conv :: snd_conv :: get #rec_thms dt_info);
wenzelm@17959
   363
        val thm = OldGoals.simple_prove_goal_cterm (cterm_of (sign_of thy) rlz) (fn prems =>
berghofe@13710
   364
          [if length rss = 1 then
berghofe@13710
   365
             cut_facts_tac [hd prems] 1 THEN etac (#induct ind_info) 1
berghofe@13710
   366
           else EVERY [rewrite_goals_tac (rews @ all_simps),
berghofe@13710
   367
             REPEAT (rtac allI 1), rtac (#induct ind_info) 1],
berghofe@13710
   368
           rewrite_goals_tac rews,
berghofe@13710
   369
           REPEAT ((resolve_tac prems THEN_ALL_NEW EVERY'
berghofe@13710
   370
             [K (rewrite_goals_tac rews), ObjectLogic.atomize_tac,
berghofe@13710
   371
              DEPTH_SOLVE_1 o FIRST' [atac, etac allE, etac impE]]) 1)]);
berghofe@13710
   372
        val (thy', thm') = PureThy.store_thm ((space_implode "_"
berghofe@13710
   373
          (Thm.name_of_thm induct :: vs @ Ps @ ["correctness"]), thm), []) thy
berghofe@13710
   374
      in
berghofe@13710
   375
        Extraction.add_realizers_i
berghofe@13710
   376
          [mk_realizer thy' (vs @ Ps) params' ((induct, thm'), r)] thy'
berghofe@13710
   377
      end;
berghofe@13710
   378
berghofe@13710
   379
    (** realizer for elimination rules **)
berghofe@13710
   380
berghofe@13710
   381
    val case_names = map (fst o dest_Const o head_of o fst o HOLogic.dest_eq o
berghofe@13710
   382
      HOLogic.dest_Trueprop o prop_of o hd) (get #case_thms dt_info);
berghofe@13710
   383
berghofe@13921
   384
    fun add_elim_realizer Ps
berghofe@13921
   385
      (((((elim, elimR), intrs), case_thms), case_name), dummy) thy =
berghofe@13710
   386
      let
berghofe@13710
   387
        val (prem :: prems) = prems_of elim;
berghofe@13921
   388
        fun reorder1 (p, intr) =
skalberg@15570
   389
          Library.foldl (fn (t, ((s, _), T)) => all T $ lambda (Free (s, T)) t)
wenzelm@16861
   390
            (strip_all p, Term.add_vars (prop_of intr) [] \\ params');
berghofe@13921
   391
        fun reorder2 (intr, i) =
berghofe@13921
   392
          let
berghofe@13928
   393
            val fs1 = term_vars (prop_of intr) \\ params;
wenzelm@16861
   394
            val fs2 = Term.add_vars (prop_of intr) [] \\ params'
skalberg@15570
   395
          in Library.foldl (fn (t, x) => lambda (Var x) t)
berghofe@13921
   396
            (list_comb (Bound (i + length fs1), fs1), fs2)
berghofe@13921
   397
          end;
berghofe@13921
   398
        val p = Logic.list_implies
berghofe@13921
   399
          (map reorder1 (prems ~~ intrs) @ [prem], concl_of elim);
berghofe@13710
   400
        val T' = Extraction.etype_of thy (vs @ Ps) [] p;
berghofe@13710
   401
        val T = if dummy then (HOLogic.unitT --> body_type T') --> T' else T';
berghofe@13921
   402
        val Ts = map (Extraction.etype_of thy (vs @ Ps) []) (prems_of elim);
berghofe@13710
   403
        val r = if null Ps then Extraction.nullt
berghofe@13710
   404
          else list_abs (map (pair "x") Ts, list_comb (Const (case_name, T),
berghofe@13710
   405
            (if dummy then
berghofe@13710
   406
               [Abs ("x", HOLogic.unitT, Const ("arbitrary", body_type T))]
berghofe@13710
   407
             else []) @
berghofe@13921
   408
            map reorder2 (intrs ~~ (length prems - 1 downto 0)) @
berghofe@13921
   409
            [Bound (length prems)]));
berghofe@13725
   410
        val rlz = strip_all (Logic.unvarify
berghofe@13725
   411
          (Extraction.realizes_of thy (vs @ Ps) r (prop_of elim)));
berghofe@13710
   412
        val rews = map mk_meta_eq case_thms;
wenzelm@17959
   413
        val thm = OldGoals.simple_prove_goal_cterm (cterm_of (sign_of thy) rlz) (fn prems =>
berghofe@13710
   414
          [cut_facts_tac [hd prems] 1,
berghofe@13710
   415
           etac elimR 1,
berghofe@13710
   416
           ALLGOALS (EVERY' [etac Pair_inject, asm_simp_tac HOL_basic_ss]),
berghofe@13710
   417
           rewrite_goals_tac rews,
berghofe@13710
   418
           REPEAT ((resolve_tac prems THEN_ALL_NEW (ObjectLogic.atomize_tac THEN'
berghofe@13710
   419
             DEPTH_SOLVE_1 o FIRST' [atac, etac allE, etac impE])) 1)]);
berghofe@13710
   420
        val (thy', thm') = PureThy.store_thm ((space_implode "_"
berghofe@13710
   421
          (Thm.name_of_thm elim :: vs @ Ps @ ["correctness"]), thm), []) thy
berghofe@13710
   422
      in
berghofe@13710
   423
        Extraction.add_realizers_i
berghofe@13710
   424
          [mk_realizer thy' (vs @ Ps) params' ((elim, thm'), r)] thy'
berghofe@13710
   425
      end;
berghofe@13710
   426
berghofe@13710
   427
    (** add realizers to theory **)
berghofe@13710
   428
skalberg@15570
   429
    val rintr_thms = List.concat (map (fn (_, rs) => map (fn r => List.nth
skalberg@15570
   430
      (#intrs ind_info, find_index_eq r intrs)) rs) rss);
skalberg@15570
   431
    val thy4 = Library.foldl add_ind_realizer (thy3, subsets Ps);
berghofe@13710
   432
    val thy5 = Extraction.add_realizers_i
berghofe@13710
   433
      (map (mk_realizer thy4 vs params')
berghofe@13710
   434
         (map (fn ((rule, rrule), c) => ((rule, rrule), list_comb (c,
wenzelm@16861
   435
            map Var (rev (Term.add_vars (prop_of rule) []) \\ params')))) 
skalberg@15570
   436
              (List.concat (map snd rss) ~~ rintr_thms ~~ List.concat constrss))) thy4;
skalberg@15570
   437
    val elimps = List.mapPartial (fn (s, intrs) => if s mem rsets then
skalberg@15570
   438
        Option.map (rpair intrs) (find_first (fn (thm, _) =>
berghofe@13921
   439
          s mem term_consts (hd (prems_of thm))) (elims ~~ #elims ind_info))
skalberg@15531
   440
      else NONE) rss;
skalberg@15570
   441
    val thy6 = Library.foldl (fn (thy, p as (((((elim, _), _), _), _), _)) => thy |>
berghofe@13710
   442
      add_elim_realizer [] p |> add_elim_realizer [fst (fst (dest_Var
berghofe@13710
   443
        (HOLogic.dest_Trueprop (concl_of elim))))] p) (thy5,
berghofe@13710
   444
           elimps ~~ get #case_thms dt_info ~~ case_names ~~ dummies)
berghofe@13710
   445
wenzelm@16123
   446
  in Theory.restore_naming thy thy6 end;
berghofe@13710
   447
berghofe@13710
   448
fun add_ind_realizers name rsets thy =
berghofe@13710
   449
  let
berghofe@13710
   450
    val (_, {intrs, induct, raw_induct, elims, ...}) =
berghofe@13710
   451
      (case InductivePackage.get_inductive thy name of
skalberg@15531
   452
         NONE => error ("Unknown inductive set " ^ quote name)
skalberg@15531
   453
       | SOME info => info);
berghofe@13710
   454
    val _ $ (_ $ _ $ S) = concl_of (hd intrs);
berghofe@13710
   455
    val vss = sort (int_ord o pairself length)
berghofe@13710
   456
      (subsets (map fst (relevant_vars S)))
berghofe@13710
   457
  in
skalberg@15570
   458
    Library.foldl (add_ind_realizer rsets intrs induct raw_induct elims) (thy, vss)
berghofe@13710
   459
  end
berghofe@13710
   460
berghofe@13710
   461
fun rlz_attrib arg (thy, thm) =
berghofe@13710
   462
  let
berghofe@13710
   463
    fun err () = error "ind_realizer: bad rule";
berghofe@13710
   464
    val sets =
berghofe@13710
   465
      (case HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of thm)) of
berghofe@13710
   466
           [_] => [set_of (HOLogic.dest_Trueprop (hd (prems_of thm)))]
berghofe@13710
   467
         | xs => map (set_of o fst o HOLogic.dest_imp) xs)
skalberg@15570
   468
         handle TERM _ => err () | Empty => err ();
berghofe@13710
   469
  in 
berghofe@13710
   470
    (add_ind_realizers (hd sets) (case arg of
skalberg@15531
   471
        NONE => sets | SOME NONE => []
wenzelm@15703
   472
      | SOME (SOME sets') => sets \\ sets')
berghofe@13710
   473
      thy, thm)
berghofe@13710
   474
  end;
berghofe@13710
   475
wenzelm@15703
   476
val rlz_attrib_global = Attrib.syntax
wenzelm@15703
   477
 ((Scan.option (Scan.lift (Args.$$$ "irrelevant") |--
wenzelm@15703
   478
    Scan.option (Scan.lift (Args.colon) |--
wenzelm@15703
   479
      Scan.repeat1 Args.global_const))) >> rlz_attrib);
berghofe@13710
   480
berghofe@13710
   481
val setup = [Attrib.add_attributes [("ind_realizer",
berghofe@13710
   482
  (rlz_attrib_global, K Attrib.undef_local_attribute),
berghofe@13710
   483
  "add realizers for inductive set")]];
berghofe@13710
   484
berghofe@13710
   485
end;
wenzelm@15706
   486