src/HOL/Tools/inductive_realizer.ML
author wenzelm
Tue Dec 05 00:30:38 2006 +0100 (2006-12-05)
changeset 21646 c07b5b0e8492
parent 21395 f34ac19659ae
child 21858 05f57309170c
permissions -rw-r--r--
thm/prf: separate official name vs. additional tags;
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
wenzelm@18708
    12
  val setup: theory -> theory
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)) =
wenzelm@20071
    38
          let val s' = Name.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);
wenzelm@21646
    62
    fun constr_of_intr intr = (Sign.base_name (Thm.get_name intr),
wenzelm@19806
    63
      map (Logic.unvarifyT o snd) (rev (Term.add_vars (prop_of intr) []) \\ params) @
berghofe@13710
    64
        filter_out (equal Extraction.nullT) (map
wenzelm@19806
    65
          (Logic.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;
wenzelm@20071
   155
            val [x, r] = Name.variant_list used ["x", "r"]
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
wenzelm@21646
   192
              (Free ("r" ^ Sign.base_name (Thm.get_name 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
haftmann@18008
   198
fun find_first f = Library.find_first f;
haftmann@18008
   199
berghofe@13710
   200
fun indrule_realizer thy induct raw_induct rsets params vs rec_names rss intrs dummies =
berghofe@13710
   201
  let
berghofe@13710
   202
    val concls = HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of raw_induct));
skalberg@15570
   203
    val premss = List.mapPartial (fn (s, rs) => if s mem rsets then
skalberg@15570
   204
      SOME (map (fn r => List.nth (prems_of raw_induct,
skalberg@15570
   205
        find_index_eq (prop_of r) (map prop_of intrs))) rs) else NONE) rss;
skalberg@15570
   206
    val concls' = List.mapPartial (fn (s, _) => if s mem rsets then
berghofe@13710
   207
        find_first (fn concl => s mem term_consts concl) concls
skalberg@15531
   208
      else NONE) rss;
skalberg@15570
   209
    val fs = List.concat (snd (foldl_map (fn (intrs, (prems, dummy)) =>
berghofe@13710
   210
      let
wenzelm@19473
   211
        val (intrs1, intrs2) = chop (length prems) intrs;
berghofe@13710
   212
        val fs = map (fn (rule, intr) =>
berghofe@13710
   213
          fun_of_prem thy rsets vs params rule intr) (prems ~~ intrs1)
berghofe@13710
   214
      in (intrs2, if dummy then Const ("arbitrary",
berghofe@13710
   215
          HOLogic.unitT --> body_type (fastype_of (hd fs))) :: fs
berghofe@13710
   216
        else fs)
berghofe@13710
   217
      end) (intrs, (premss ~~ dummies))));
wenzelm@16861
   218
    val frees = fold Term.add_frees fs [];
berghofe@13710
   219
    val Ts = map fastype_of fs;
skalberg@15570
   220
    val rlzs = List.mapPartial (fn (a, concl) =>
berghofe@13710
   221
      let val T = Extraction.etype_of thy vs [] concl
skalberg@15531
   222
      in if T = Extraction.nullT then NONE
skalberg@15531
   223
        else SOME (list_comb (Const (a, Ts ---> T), fs))
berghofe@13710
   224
      end) (rec_names ~~ concls')
berghofe@13710
   225
  in if null rlzs then Extraction.nullt else
berghofe@13710
   226
    let
berghofe@13710
   227
      val r = foldr1 HOLogic.mk_prod rlzs;
berghofe@13710
   228
      val x = Free ("x", Extraction.etype_of thy vs [] (hd (prems_of induct)));
wenzelm@21646
   229
      fun name_of_fn intr = "r" ^ Sign.base_name (Thm.get_name intr);
skalberg@15570
   230
      val r' = list_abs_free (List.mapPartial (fn intr =>
haftmann@17485
   231
        Option.map (pair (name_of_fn intr)) (AList.lookup (op =) frees (name_of_fn intr))) intrs,
berghofe@13710
   232
          if length concls = 1 then r $ x else r)
berghofe@13710
   233
    in
berghofe@13710
   234
      if length concls = 1 then lambda x r' else r'
berghofe@13710
   235
    end
berghofe@13710
   236
  end;
berghofe@13710
   237
berghofe@13710
   238
fun add_dummy name dname (x as (_, (vs, s, mfx, cs))) =
berghofe@13710
   239
  if name = s then (true, (vs, s, mfx, (dname, [HOLogic.unitT], NoSyn) :: cs))
berghofe@13710
   240
  else x;
berghofe@13710
   241
haftmann@18314
   242
fun add_dummies f [] _ thy =
haftmann@18314
   243
      (([], NONE), thy)
haftmann@18314
   244
  | add_dummies f dts used thy =
haftmann@18314
   245
      thy
haftmann@18314
   246
      |> f (map snd dts)
haftmann@18314
   247
      |-> (fn dtinfo => pair ((map fst dts), SOME dtinfo))
haftmann@18314
   248
    handle DatatypeAux.Datatype_Empty name' =>
berghofe@13710
   249
      let
berghofe@14888
   250
        val name = Sign.base_name name';
wenzelm@20071
   251
        val dname = Name.variant used "Dummy"
haftmann@18314
   252
      in
haftmann@18314
   253
        thy
haftmann@18314
   254
        |> add_dummies f (map (add_dummy name dname) dts) (dname :: used)
berghofe@14888
   255
      end;
berghofe@13710
   256
berghofe@13710
   257
fun mk_realizer thy vs params ((rule, rrule), rt) =
berghofe@13710
   258
  let
berghofe@13725
   259
    val prems = prems_of rule ~~ prems_of rrule;
berghofe@13725
   260
    val rvs = map fst (relevant_vars (prop_of rule));
wenzelm@16861
   261
    val xs = rev (Term.add_vars (prop_of rule) []);
berghofe@13725
   262
    val vs1 = map Var (filter_out (fn ((a, _), _) => a mem rvs) xs);
wenzelm@16861
   263
    val rlzvs = rev (Term.add_vars (prop_of rrule) []);
haftmann@17485
   264
    val vs2 = map (fn (ixn, _) => Var (ixn, (the o AList.lookup (op =) rlzvs) ixn)) xs;
haftmann@20951
   265
    val rs = subtract (op = o pairself fst) xs rlzvs;
berghofe@13710
   266
berghofe@13710
   267
    fun mk_prf _ [] prf = prf
berghofe@13725
   268
      | mk_prf rs ((prem, rprem) :: prems) prf =
berghofe@13725
   269
          if Extraction.etype_of thy vs [] prem = Extraction.nullT
skalberg@15531
   270
          then AbsP ("H", SOME rprem, mk_prf rs prems prf)
skalberg@15531
   271
          else forall_intr_prf (Var (hd rs), AbsP ("H", SOME rprem,
berghofe@13725
   272
            mk_prf (tl rs) prems prf));
berghofe@13710
   273
wenzelm@21646
   274
  in (Thm.get_name rule, (vs,
berghofe@13710
   275
    if rt = Extraction.nullt then rt else
skalberg@15574
   276
      foldr (uncurry lambda) rt vs1,
skalberg@15574
   277
    foldr forall_intr_prf (mk_prf rs prems (Proofterm.proof_combP
skalberg@15574
   278
      (prf_of rrule, map PBound (length prems - 1 downto 0)))) vs2))
berghofe@13710
   279
  end;
berghofe@13710
   280
haftmann@17485
   281
fun add_rule r rss =
berghofe@13710
   282
  let
berghofe@13710
   283
    val _ $ (_ $ _ $ S) = concl_of r;
berghofe@13710
   284
    val (Const (s, _), _) = strip_comb S;
haftmann@17485
   285
  in
haftmann@17485
   286
    rss
haftmann@17485
   287
    |> AList.default (op =) (s, [])
haftmann@17485
   288
    |> AList.map_entry (op =) s (fn rs => rs @ [r])
haftmann@17485
   289
  end;
berghofe@13710
   290
berghofe@13710
   291
fun add_ind_realizer rsets intrs induct raw_induct elims (thy, vs) =
berghofe@13710
   292
  let
berghofe@13710
   293
    val iTs = term_tvars (prop_of (hd intrs));
berghofe@13710
   294
    val ar = length vs + length iTs;
berghofe@13710
   295
    val (_ $ (_ $ _ $ S)) = Logic.strip_imp_concl (prop_of (hd intrs));
berghofe@13710
   296
    val (_, params) = strip_comb S;
berghofe@13710
   297
    val params' = map dest_Var params;
wenzelm@21395
   298
    val rss = [] |> fold add_rule intrs;
berghofe@13710
   299
    val (prfx, _) = split_last (NameSpace.unpack (fst (hd rss)));
berghofe@13710
   300
    val tnames = map (fn s => space_implode "_" (s ^ "T" :: vs)) rsets;
wenzelm@16123
   301
berghofe@13710
   302
    val thy1 = thy |>
berghofe@13710
   303
      Theory.root_path |>
berghofe@13710
   304
      Theory.add_path (NameSpace.pack prfx);
berghofe@13710
   305
    val (ty_eqs, rlz_eqs) = split_list
berghofe@13710
   306
      (map (fn (s, rs) => mk_realizes_eqn (not (s mem rsets)) vs rs) rss);
berghofe@13710
   307
berghofe@13710
   308
    val thy1' = thy1 |>
berghofe@13710
   309
      Theory.copy |>
berghofe@13710
   310
      Theory.add_types (map (fn s => (Sign.base_name s, ar, NoSyn)) tnames) |>
wenzelm@19510
   311
      fold (fn s => AxClass.axiomatize_arity_i
wenzelm@19510
   312
        (s, replicate ar HOLogic.typeS, HOLogic.typeS)) tnames |>
berghofe@13710
   313
        Extraction.add_typeof_eqns_i ty_eqs;
skalberg@15570
   314
    val dts = List.mapPartial (fn (s, rs) => if s mem rsets then
skalberg@15531
   315
      SOME (dt_of_intrs thy1' vs rs) else NONE) rss;
berghofe@13710
   316
berghofe@13710
   317
    (** datatype representing computational content of inductive set **)
berghofe@13710
   318
haftmann@18314
   319
    val ((dummies, dt_info), thy2) =
haftmann@18008
   320
      thy1
haftmann@18314
   321
      |> add_dummies
haftmann@18314
   322
           (DatatypePackage.add_datatype_i false false (map #2 dts))
haftmann@18314
   323
           (map (pair false) dts) []
haftmann@18314
   324
      ||> Extraction.add_typeof_eqns_i ty_eqs
haftmann@18314
   325
      ||> Extraction.add_realizes_eqns_i rlz_eqs;
haftmann@18314
   326
    fun get f = (these oo Option.map) f;
wenzelm@19046
   327
    val rec_names = distinct (op =) (map (fst o dest_Const o head_of o fst o
berghofe@13710
   328
      HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) (get #rec_thms dt_info));
berghofe@13710
   329
    val (_, constrss) = foldl_map (fn ((recs, dummies), (s, rs)) =>
berghofe@13710
   330
      if s mem rsets then
berghofe@13710
   331
        let
berghofe@13710
   332
          val (d :: dummies') = dummies;
wenzelm@19473
   333
          val (recs1, recs2) = chop (length rs) (if d then tl recs else recs)
berghofe@13710
   334
        in ((recs2, dummies'), map (head_of o hd o rev o snd o strip_comb o
berghofe@13710
   335
          fst o HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) recs1)
berghofe@13710
   336
        end
berghofe@13710
   337
      else ((recs, dummies), replicate (length rs) Extraction.nullt))
berghofe@13710
   338
        ((get #rec_thms dt_info, dummies), rss);
wenzelm@18929
   339
    val rintrs = map (fn (intr, c) => Envir.eta_contract
berghofe@13710
   340
      (Extraction.realizes_of thy2 vs
berghofe@13710
   341
        c (prop_of (forall_intr_list (map (cterm_of (sign_of thy2) o Var)
wenzelm@16861
   342
          (rev (Term.add_vars (prop_of intr) []) \\ params')) intr))))
skalberg@15570
   343
            (intrs ~~ List.concat constrss);
wenzelm@19046
   344
    val rlzsets = distinct (op =) (map (fn rintr => snd (HOLogic.dest_mem
berghofe@13710
   345
      (HOLogic.dest_Trueprop (Logic.strip_assums_concl rintr)))) rintrs);
berghofe@13710
   346
berghofe@13710
   347
    (** realizability predicate **)
berghofe@13710
   348
berghofe@13710
   349
    val (thy3', ind_info) = thy2 |>
berghofe@21022
   350
      OldInductivePackage.add_inductive_i false true "" false false false
berghofe@13710
   351
        (map Logic.unvarify rlzsets) (map (fn (rintr, intr) =>
wenzelm@21646
   352
          ((Sign.base_name (Thm.get_name intr), strip_all
berghofe@13710
   353
            (Logic.unvarify rintr)), [])) (rintrs ~~ intrs)) [] |>>
berghofe@13710
   354
      Theory.absolute_path;
berghofe@13710
   355
    val thy3 = PureThy.hide_thms false
wenzelm@21646
   356
      (map Thm.get_name (#intrs ind_info)) thy3';
berghofe@13710
   357
berghofe@13710
   358
    (** realizer for induction rule **)
berghofe@13710
   359
skalberg@15570
   360
    val Ps = List.mapPartial (fn _ $ M $ P => if set_of M mem rsets then
skalberg@15531
   361
      SOME (fst (fst (dest_Var (head_of P)))) else NONE)
berghofe@13710
   362
        (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of raw_induct)));
berghofe@13710
   363
berghofe@13710
   364
    fun add_ind_realizer (thy, Ps) =
berghofe@13710
   365
      let
berghofe@13710
   366
        val r = indrule_realizer thy induct raw_induct rsets params'
berghofe@13710
   367
          (vs @ Ps) rec_names rss intrs dummies;
berghofe@13725
   368
        val rlz = strip_all (Logic.unvarify
berghofe@13725
   369
          (Extraction.realizes_of thy (vs @ Ps) r (prop_of induct)));
berghofe@13710
   370
        val rews = map mk_meta_eq
berghofe@13710
   371
          (fst_conv :: snd_conv :: get #rec_thms dt_info);
wenzelm@17959
   372
        val thm = OldGoals.simple_prove_goal_cterm (cterm_of (sign_of thy) rlz) (fn prems =>
berghofe@13710
   373
          [if length rss = 1 then
berghofe@13710
   374
             cut_facts_tac [hd prems] 1 THEN etac (#induct ind_info) 1
berghofe@13710
   375
           else EVERY [rewrite_goals_tac (rews @ all_simps),
berghofe@13710
   376
             REPEAT (rtac allI 1), rtac (#induct ind_info) 1],
berghofe@13710
   377
           rewrite_goals_tac rews,
berghofe@13710
   378
           REPEAT ((resolve_tac prems THEN_ALL_NEW EVERY'
berghofe@13710
   379
             [K (rewrite_goals_tac rews), ObjectLogic.atomize_tac,
berghofe@13710
   380
              DEPTH_SOLVE_1 o FIRST' [atac, etac allE, etac impE]]) 1)]);
haftmann@18358
   381
        val (thm', thy') = PureThy.store_thm ((space_implode "_"
wenzelm@21646
   382
          (Thm.get_name induct :: vs @ Ps @ ["correctness"]), thm), []) thy
berghofe@13710
   383
      in
berghofe@13710
   384
        Extraction.add_realizers_i
berghofe@13710
   385
          [mk_realizer thy' (vs @ Ps) params' ((induct, thm'), r)] thy'
berghofe@13710
   386
      end;
berghofe@13710
   387
berghofe@13710
   388
    (** realizer for elimination rules **)
berghofe@13710
   389
berghofe@13710
   390
    val case_names = map (fst o dest_Const o head_of o fst o HOLogic.dest_eq o
berghofe@13710
   391
      HOLogic.dest_Trueprop o prop_of o hd) (get #case_thms dt_info);
berghofe@13710
   392
berghofe@13921
   393
    fun add_elim_realizer Ps
berghofe@13921
   394
      (((((elim, elimR), intrs), case_thms), case_name), dummy) thy =
berghofe@13710
   395
      let
berghofe@13710
   396
        val (prem :: prems) = prems_of elim;
berghofe@13921
   397
        fun reorder1 (p, intr) =
skalberg@15570
   398
          Library.foldl (fn (t, ((s, _), T)) => all T $ lambda (Free (s, T)) t)
wenzelm@16861
   399
            (strip_all p, Term.add_vars (prop_of intr) [] \\ params');
berghofe@13921
   400
        fun reorder2 (intr, i) =
berghofe@13921
   401
          let
berghofe@13928
   402
            val fs1 = term_vars (prop_of intr) \\ params;
wenzelm@16861
   403
            val fs2 = Term.add_vars (prop_of intr) [] \\ params'
skalberg@15570
   404
          in Library.foldl (fn (t, x) => lambda (Var x) t)
berghofe@13921
   405
            (list_comb (Bound (i + length fs1), fs1), fs2)
berghofe@13921
   406
          end;
berghofe@13921
   407
        val p = Logic.list_implies
berghofe@13921
   408
          (map reorder1 (prems ~~ intrs) @ [prem], concl_of elim);
berghofe@13710
   409
        val T' = Extraction.etype_of thy (vs @ Ps) [] p;
berghofe@13710
   410
        val T = if dummy then (HOLogic.unitT --> body_type T') --> T' else T';
berghofe@13921
   411
        val Ts = map (Extraction.etype_of thy (vs @ Ps) []) (prems_of elim);
berghofe@13710
   412
        val r = if null Ps then Extraction.nullt
berghofe@13710
   413
          else list_abs (map (pair "x") Ts, list_comb (Const (case_name, T),
berghofe@13710
   414
            (if dummy then
berghofe@13710
   415
               [Abs ("x", HOLogic.unitT, Const ("arbitrary", body_type T))]
berghofe@13710
   416
             else []) @
berghofe@13921
   417
            map reorder2 (intrs ~~ (length prems - 1 downto 0)) @
berghofe@13921
   418
            [Bound (length prems)]));
berghofe@13725
   419
        val rlz = strip_all (Logic.unvarify
berghofe@13725
   420
          (Extraction.realizes_of thy (vs @ Ps) r (prop_of elim)));
berghofe@13710
   421
        val rews = map mk_meta_eq case_thms;
wenzelm@17959
   422
        val thm = OldGoals.simple_prove_goal_cterm (cterm_of (sign_of thy) rlz) (fn prems =>
berghofe@13710
   423
          [cut_facts_tac [hd prems] 1,
berghofe@13710
   424
           etac elimR 1,
berghofe@13710
   425
           ALLGOALS (EVERY' [etac Pair_inject, asm_simp_tac HOL_basic_ss]),
berghofe@13710
   426
           rewrite_goals_tac rews,
berghofe@13710
   427
           REPEAT ((resolve_tac prems THEN_ALL_NEW (ObjectLogic.atomize_tac THEN'
berghofe@13710
   428
             DEPTH_SOLVE_1 o FIRST' [atac, etac allE, etac impE])) 1)]);
haftmann@18358
   429
        val (thm', thy') = PureThy.store_thm ((space_implode "_"
wenzelm@21646
   430
          (Thm.get_name elim :: vs @ Ps @ ["correctness"]), thm), []) thy
berghofe@13710
   431
      in
berghofe@13710
   432
        Extraction.add_realizers_i
berghofe@13710
   433
          [mk_realizer thy' (vs @ Ps) params' ((elim, thm'), r)] thy'
berghofe@13710
   434
      end;
berghofe@13710
   435
berghofe@13710
   436
    (** add realizers to theory **)
berghofe@13710
   437
skalberg@15570
   438
    val rintr_thms = List.concat (map (fn (_, rs) => map (fn r => List.nth
wenzelm@19617
   439
      (#intrs ind_info, find_index (fn th => eq_thm (th, r)) intrs)) rs) rss);
skalberg@15570
   440
    val thy4 = Library.foldl add_ind_realizer (thy3, subsets Ps);
berghofe@13710
   441
    val thy5 = Extraction.add_realizers_i
berghofe@13710
   442
      (map (mk_realizer thy4 vs params')
berghofe@13710
   443
         (map (fn ((rule, rrule), c) => ((rule, rrule), list_comb (c,
wenzelm@16861
   444
            map Var (rev (Term.add_vars (prop_of rule) []) \\ params')))) 
skalberg@15570
   445
              (List.concat (map snd rss) ~~ rintr_thms ~~ List.concat constrss))) thy4;
skalberg@15570
   446
    val elimps = List.mapPartial (fn (s, intrs) => if s mem rsets then
skalberg@15570
   447
        Option.map (rpair intrs) (find_first (fn (thm, _) =>
berghofe@13921
   448
          s mem term_consts (hd (prems_of thm))) (elims ~~ #elims ind_info))
skalberg@15531
   449
      else NONE) rss;
skalberg@15570
   450
    val thy6 = Library.foldl (fn (thy, p as (((((elim, _), _), _), _), _)) => thy |>
berghofe@13710
   451
      add_elim_realizer [] p |> add_elim_realizer [fst (fst (dest_Var
berghofe@13710
   452
        (HOLogic.dest_Trueprop (concl_of elim))))] p) (thy5,
berghofe@13710
   453
           elimps ~~ get #case_thms dt_info ~~ case_names ~~ dummies)
berghofe@13710
   454
wenzelm@16123
   455
  in Theory.restore_naming thy thy6 end;
berghofe@13710
   456
berghofe@13710
   457
fun add_ind_realizers name rsets thy =
berghofe@13710
   458
  let
berghofe@13710
   459
    val (_, {intrs, induct, raw_induct, elims, ...}) =
berghofe@21022
   460
      (case OldInductivePackage.get_inductive thy name of
skalberg@15531
   461
         NONE => error ("Unknown inductive set " ^ quote name)
skalberg@15531
   462
       | SOME info => info);
berghofe@13710
   463
    val _ $ (_ $ _ $ S) = concl_of (hd intrs);
berghofe@13710
   464
    val vss = sort (int_ord o pairself length)
berghofe@13710
   465
      (subsets (map fst (relevant_vars S)))
berghofe@13710
   466
  in
skalberg@15570
   467
    Library.foldl (add_ind_realizer rsets intrs induct raw_induct elims) (thy, vss)
berghofe@13710
   468
  end
berghofe@13710
   469
wenzelm@20897
   470
fun rlz_attrib arg = Thm.declaration_attribute (fn thm => Context.mapping
berghofe@13710
   471
  let
berghofe@13710
   472
    fun err () = error "ind_realizer: bad rule";
berghofe@13710
   473
    val sets =
berghofe@13710
   474
      (case HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of thm)) of
berghofe@13710
   475
           [_] => [set_of (HOLogic.dest_Trueprop (hd (prems_of thm)))]
berghofe@13710
   476
         | xs => map (set_of o fst o HOLogic.dest_imp) xs)
skalberg@15570
   477
         handle TERM _ => err () | Empty => err ();
berghofe@13710
   478
  in 
wenzelm@18728
   479
    add_ind_realizers (hd sets)
wenzelm@18728
   480
      (case arg of
skalberg@15531
   481
        NONE => sets | SOME NONE => []
wenzelm@15703
   482
      | SOME (SOME sets') => sets \\ sets')
wenzelm@20897
   483
  end I);
berghofe@13710
   484
wenzelm@18728
   485
val ind_realizer = Attrib.syntax
wenzelm@15703
   486
 ((Scan.option (Scan.lift (Args.$$$ "irrelevant") |--
wenzelm@15703
   487
    Scan.option (Scan.lift (Args.colon) |--
wenzelm@18728
   488
      Scan.repeat1 Args.const))) >> rlz_attrib);
berghofe@13710
   489
wenzelm@18708
   490
val setup =
wenzelm@18728
   491
  Attrib.add_attributes [("ind_realizer", ind_realizer, "add realizers for inductive set")];
berghofe@13710
   492
berghofe@13710
   493
end;
wenzelm@15706
   494