src/HOL/Tools/inductive_realizer.ML
author wenzelm
Tue, 23 Sep 2008 15:48:50 +0200
changeset 28328 9a647179c1e6
parent 28083 103d9282a946
child 28800 48f7bfebd31d
permissions -rw-r--r--
Thm.proof_of;
     1 (*  Title:      HOL/Tools/inductive_realizer.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, TU Muenchen
     4 
     5 Porgram extraction from proofs involving inductive predicates:
     6 Realizers for induction and elimination rules
     7 *)
     8 
     9 signature INDUCTIVE_REALIZER =
    10 sig
    11   val add_ind_realizers: string -> string list -> theory -> theory
    12   val setup: theory -> theory
    13 end;
    14 
    15 structure InductiveRealizer : INDUCTIVE_REALIZER =
    16 struct
    17 
    18 (* FIXME: LocalTheory.note should return theorems with proper names! *)
    19 fun name_of_thm thm =
    20   (case Symtab.dest (Proofterm.thms_of_proof' (Thm.proof_of thm) Symtab.empty) of
    21      [(name, _)] => name
    22    | _ => error ("name_of_thm: bad proof of theorem\n" ^ Display.string_of_thm thm));
    23 
    24 val all_simps = map (symmetric o mk_meta_eq) (thms "HOL.all_simps");
    25 
    26 fun prf_of thm =
    27   let
    28     val thy = Thm.theory_of_thm thm;
    29     val thm' = Reconstruct.reconstruct_proof thy (Thm.prop_of thm) (Thm.proof_of thm);
    30   in Reconstruct.expand_proof thy [("", NONE)] thm' end; (* FIXME *)
    31 
    32 fun forall_intr_prf t prf =
    33   let val (a, T) = (case t of Var ((a, _), T) => (a, T) | Free p => p)
    34   in Abst (a, SOME T, Proofterm.prf_abstract_over t prf) end;
    35 
    36 fun subsets [] = [[]]
    37   | subsets (x::xs) =
    38       let val ys = subsets xs
    39       in ys @ map (cons x) ys end;
    40 
    41 val pred_of = fst o dest_Const o head_of;
    42 
    43 fun strip_all' used names (Const ("all", _) $ Abs (s, T, t)) =
    44       let val (s', names') = (case names of
    45           [] => (Name.variant used s, [])
    46         | name :: names' => (name, names'))
    47       in strip_all' (s'::used) names' (subst_bound (Free (s', T), t)) end
    48   | strip_all' used names ((t as Const ("==>", _) $ P) $ Q) =
    49       t $ strip_all' used names Q
    50   | strip_all' _ _ t = t;
    51 
    52 fun strip_all t = strip_all' (add_term_free_names (t, [])) [] t;
    53 
    54 fun strip_one name (Const ("all", _) $ Abs (s, T, Const ("==>", _) $ P $ Q)) =
    55       (subst_bound (Free (name, T), P), subst_bound (Free (name, T), Q))
    56   | strip_one _ (Const ("==>", _) $ P $ Q) = (P, Q);
    57 
    58 fun relevant_vars prop = foldr (fn
    59       (Var ((a, i), T), vs) => (case strip_type T of
    60         (_, Type (s, _)) => if s mem ["bool"] then (a, T) :: vs else vs
    61       | _ => vs)
    62     | (_, vs) => vs) [] (term_vars prop);
    63 
    64 fun dt_of_intrs thy vs nparms intrs =
    65   let
    66     val iTs = term_tvars (prop_of (hd intrs));
    67     val Tvs = map TVar iTs;
    68     val (Const (s, _), ts) = strip_comb (HOLogic.dest_Trueprop
    69       (Logic.strip_imp_concl (prop_of (hd intrs))));
    70     val params = map dest_Var (Library.take (nparms, ts));
    71     val tname = space_implode "_" (Sign.base_name s ^ "T" :: vs);
    72     fun constr_of_intr intr = (Sign.base_name (name_of_thm intr),
    73       map (Logic.unvarifyT o snd) (rev (Term.add_vars (prop_of intr) []) \\ params) @
    74         filter_out (equal Extraction.nullT) (map
    75           (Logic.unvarifyT o Extraction.etype_of thy vs []) (prems_of intr)),
    76             NoSyn);
    77   in (map (fn a => "'" ^ a) vs @ map (fst o fst) iTs, tname, NoSyn,
    78     map constr_of_intr intrs)
    79   end;
    80 
    81 fun mk_rlz T = Const ("realizes", [T, HOLogic.boolT] ---> HOLogic.boolT);
    82 
    83 (** turn "P" into "%r x. realizes r (P x)" **)
    84 
    85 fun gen_rvar vs (t as Var ((a, 0), T)) =
    86       if body_type T <> HOLogic.boolT then t else
    87         let
    88           val U = TVar (("'" ^ a, 0), HOLogic.typeS)
    89           val Ts = binder_types T;
    90           val i = length Ts;
    91           val xs = map (pair "x") Ts;
    92           val u = list_comb (t, map Bound (i - 1 downto 0))
    93         in 
    94           if a mem vs then
    95             list_abs (("r", U) :: xs, mk_rlz U $ Bound i $ u)
    96           else list_abs (xs, mk_rlz Extraction.nullT $ Extraction.nullt $ u)
    97         end
    98   | gen_rvar _ t = t;
    99 
   100 fun mk_realizes_eqn n vs nparms intrs =
   101   let
   102     val concl = HOLogic.dest_Trueprop (concl_of (hd intrs));
   103     val iTs = term_tvars concl;
   104     val Tvs = map TVar iTs;
   105     val (h as Const (s, T), us) = strip_comb concl;
   106     val params = List.take (us, nparms);
   107     val elTs = List.drop (binder_types T, nparms);
   108     val predT = elTs ---> HOLogic.boolT;
   109     val used = map (fst o fst o dest_Var) params;
   110     val xs = map (Var o apfst (rpair 0))
   111       (Name.variant_list used (replicate (length elTs) "x") ~~ elTs);
   112     val rT = if n then Extraction.nullT
   113       else Type (space_implode "_" (s ^ "T" :: vs),
   114         map (fn a => TVar (("'" ^ a, 0), HOLogic.typeS)) vs @ Tvs);
   115     val r = if n then Extraction.nullt else Var ((Sign.base_name s, 0), rT);
   116     val S = list_comb (h, params @ xs);
   117     val rvs = relevant_vars S;
   118     val vs' = map fst rvs \\ vs;
   119     val rname = space_implode "_" (s ^ "R" :: vs);
   120 
   121     fun mk_Tprem n v =
   122       let val T = (the o AList.lookup (op =) rvs) v
   123       in (Const ("typeof", T --> Type ("Type", [])) $ Var ((v, 0), T),
   124         Extraction.mk_typ (if n then Extraction.nullT
   125           else TVar (("'" ^ v, 0), HOLogic.typeS)))
   126       end;
   127 
   128     val prems = map (mk_Tprem true) vs' @ map (mk_Tprem false) vs;
   129     val ts = map (gen_rvar vs) params;
   130     val argTs = map fastype_of ts;
   131 
   132   in ((prems, (Const ("typeof", HOLogic.boolT --> Type ("Type", [])) $ S,
   133        Extraction.mk_typ rT)),
   134     (prems, (mk_rlz rT $ r $ S,
   135        if n then list_comb (Const (rname, argTs ---> predT), ts @ xs)
   136        else list_comb (Const (rname, argTs @ [rT] ---> predT), ts @ [r] @ xs))))
   137   end;
   138 
   139 fun fun_of_prem thy rsets vs params rule ivs intr =
   140   let
   141     val ctxt = ProofContext.init thy
   142     val args = map (Free o apfst fst o dest_Var) ivs;
   143     val args' = map (Free o apfst fst)
   144       (Term.add_vars (prop_of intr) [] \\ params);
   145     val rule' = strip_all rule;
   146     val conclT = Extraction.etype_of thy vs [] (Logic.strip_imp_concl rule');
   147     val used = map (fst o dest_Free) args;
   148 
   149     fun is_rec t = not (null (term_consts t inter rsets));
   150 
   151     fun is_meta (Const ("all", _) $ Abs (s, _, P)) = is_meta P
   152       | is_meta (Const ("==>", _) $ _ $ Q) = is_meta Q
   153       | is_meta (Const ("Trueprop", _) $ t) = (case head_of t of
   154           Const (s, _) => can (InductivePackage.the_inductive ctxt) s
   155         | _ => true)
   156       | is_meta _ = false;
   157 
   158     fun fun_of ts rts args used (prem :: prems) =
   159           let
   160             val T = Extraction.etype_of thy vs [] prem;
   161             val [x, r] = Name.variant_list used ["x", "r"]
   162           in if T = Extraction.nullT
   163             then fun_of ts rts args used prems
   164             else if is_rec prem then
   165               if is_meta prem then
   166                 let
   167                   val prem' :: prems' = prems;
   168                   val U = Extraction.etype_of thy vs [] prem';
   169                 in if U = Extraction.nullT
   170                   then fun_of (Free (x, T) :: ts)
   171                     (Free (r, binder_types T ---> HOLogic.unitT) :: rts)
   172                     (Free (x, T) :: args) (x :: r :: used) prems'
   173                   else fun_of (Free (x, T) :: ts) (Free (r, U) :: rts)
   174                     (Free (r, U) :: Free (x, T) :: args) (x :: r :: used) prems'
   175                 end
   176               else (case strip_type T of
   177                   (Ts, Type ("*", [T1, T2])) =>
   178                     let
   179                       val fx = Free (x, Ts ---> T1);
   180                       val fr = Free (r, Ts ---> T2);
   181                       val bs = map Bound (length Ts - 1 downto 0);
   182                       val t = list_abs (map (pair "z") Ts,
   183                         HOLogic.mk_prod (list_comb (fx, bs), list_comb (fr, bs)))
   184                     in fun_of (fx :: ts) (fr :: rts) (t::args)
   185                       (x :: r :: used) prems
   186                     end
   187                 | (Ts, U) => fun_of (Free (x, T) :: ts)
   188                     (Free (r, binder_types T ---> HOLogic.unitT) :: rts)
   189                     (Free (x, T) :: args) (x :: r :: used) prems)
   190             else fun_of (Free (x, T) :: ts) rts (Free (x, T) :: args)
   191               (x :: used) prems
   192           end
   193       | fun_of ts rts args used [] =
   194           let val xs = rev (rts @ ts)
   195           in if conclT = Extraction.nullT
   196             then list_abs_free (map dest_Free xs, HOLogic.unit)
   197             else list_abs_free (map dest_Free xs, list_comb
   198               (Free ("r" ^ Sign.base_name (name_of_thm intr),
   199                 map fastype_of (rev args) ---> conclT), rev args))
   200           end
   201 
   202   in fun_of args' [] (rev args) used (Logic.strip_imp_prems rule') end;
   203 
   204 fun indrule_realizer thy induct raw_induct rsets params vs rec_names rss intrs dummies =
   205   let
   206     val concls = HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of raw_induct));
   207     val premss = List.mapPartial (fn (s, rs) => if s mem rsets then
   208       SOME (rs, map (fn (_, r) => List.nth (prems_of raw_induct,
   209         find_index_eq (prop_of r) (map prop_of intrs))) rs) else NONE) rss;
   210     val fs = maps (fn ((intrs, prems), dummy) =>
   211       let
   212         val fs = map (fn (rule, (ivs, intr)) =>
   213           fun_of_prem thy rsets vs params rule ivs intr) (prems ~~ intrs)
   214       in if dummy then Const ("HOL.default_class.default",
   215           HOLogic.unitT --> body_type (fastype_of (hd fs))) :: fs
   216         else fs
   217       end) (premss ~~ dummies);
   218     val frees = fold Term.add_frees fs [];
   219     val Ts = map fastype_of fs;
   220     fun name_of_fn intr = "r" ^ Sign.base_name (name_of_thm intr)
   221   in
   222     fst (fold_map (fn concl => fn names =>
   223       let val T = Extraction.etype_of thy vs [] concl
   224       in if T = Extraction.nullT then (Extraction.nullt, names) else
   225         let
   226           val Type ("fun", [U, _]) = T;
   227           val a :: names' = names
   228         in (list_abs_free (("x", U) :: List.mapPartial (fn intr =>
   229           Option.map (pair (name_of_fn intr))
   230             (AList.lookup (op =) frees (name_of_fn intr))) intrs,
   231           list_comb (Const (a, Ts ---> T), fs) $ Free ("x", U)), names')
   232         end
   233       end) concls rec_names)
   234   end;
   235 
   236 fun add_dummy name dname (x as (_, (vs, s, mfx, cs))) =
   237   if (name: string) = s then (true, (vs, s, mfx, (dname, [HOLogic.unitT], NoSyn) :: cs))
   238   else x;
   239 
   240 fun add_dummies f [] _ thy =
   241       (([], NONE), thy)
   242   | add_dummies f dts used thy =
   243       thy
   244       |> f (map snd dts)
   245       |-> (fn dtinfo => pair ((map fst dts), SOME dtinfo))
   246     handle DatatypeAux.Datatype_Empty name' =>
   247       let
   248         val name = Sign.base_name name';
   249         val dname = Name.variant used "Dummy"
   250       in
   251         thy
   252         |> add_dummies f (map (add_dummy name dname) dts) (dname :: used)
   253       end;
   254 
   255 fun mk_realizer thy vs (name, rule, rrule, rlz, rt) =
   256   let
   257     val rvs = map fst (relevant_vars (prop_of rule));
   258     val xs = rev (Term.add_vars (prop_of rule) []);
   259     val vs1 = map Var (filter_out (fn ((a, _), _) => a mem rvs) xs);
   260     val rlzvs = rev (Term.add_vars (prop_of rrule) []);
   261     val vs2 = map (fn (ixn, _) => Var (ixn, (the o AList.lookup (op =) rlzvs) ixn)) xs;
   262     val rs = map Var (subtract (op = o pairself fst) xs rlzvs);
   263     val rlz' = fold_rev Logic.all (vs2 @ rs) (prop_of rrule);
   264     val rlz'' = fold_rev Logic.all vs2 rlz
   265   in (name, (vs,
   266     if rt = Extraction.nullt then rt else
   267       foldr (uncurry lambda) rt vs1,
   268     ProofRewriteRules.un_hhf_proof rlz' rlz''
   269       (fold_rev forall_intr_prf (vs2 @ rs) (prf_of rrule))))
   270   end;
   271 
   272 fun rename tab = map (fn x => the_default x (AList.lookup op = tab x));
   273 
   274 fun add_ind_realizer rsets intrs induct raw_induct elims (thy, vs) =
   275   let
   276     val qualifier = NameSpace.qualifier (name_of_thm induct);
   277     val inducts = PureThy.get_thms thy (NameSpace.qualified qualifier "inducts");
   278     val iTs = term_tvars (prop_of (hd intrs));
   279     val ar = length vs + length iTs;
   280     val params = InductivePackage.params_of raw_induct;
   281     val arities = InductivePackage.arities_of raw_induct;
   282     val nparms = length params;
   283     val params' = map dest_Var params;
   284     val rss = InductivePackage.partition_rules raw_induct intrs;
   285     val rss' = map (fn (((s, rs), (_, arity)), elim) =>
   286       (s, (InductivePackage.infer_intro_vars elim arity rs ~~ rs)))
   287         (rss ~~ arities ~~ elims);
   288     val (prfx, _) = split_last (NameSpace.explode (fst (hd rss)));
   289     val tnames = map (fn s => space_implode "_" (s ^ "T" :: vs)) rsets;
   290 
   291     val thy1 = thy |>
   292       Sign.root_path |>
   293       Sign.add_path (NameSpace.implode prfx);
   294     val (ty_eqs, rlz_eqs) = split_list
   295       (map (fn (s, rs) => mk_realizes_eqn (not (s mem rsets)) vs nparms rs) rss);
   296 
   297     val thy1' = thy1 |>
   298       Theory.copy |>
   299       Sign.add_types (map (fn s => (Sign.base_name s, ar, NoSyn)) tnames) |>
   300       fold (fn s => AxClass.axiomatize_arity
   301         (s, replicate ar HOLogic.typeS, HOLogic.typeS)) tnames |>
   302         Extraction.add_typeof_eqns_i ty_eqs;
   303     val dts = List.mapPartial (fn (s, rs) => if s mem rsets then
   304       SOME (dt_of_intrs thy1' vs nparms rs) else NONE) rss;
   305 
   306     (** datatype representing computational content of inductive set **)
   307 
   308     val ((dummies, dt_info), thy2) =
   309       thy1
   310       |> add_dummies
   311            (DatatypePackage.add_datatype false false (map #2 dts))
   312            (map (pair false) dts) []
   313       ||> Extraction.add_typeof_eqns_i ty_eqs
   314       ||> Extraction.add_realizes_eqns_i rlz_eqs;
   315     fun get f = (these oo Option.map) f;
   316     val rec_names = distinct (op =) (map (fst o dest_Const o head_of o fst o
   317       HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) (get #rec_thms dt_info));
   318     val (_, constrss) = foldl_map (fn ((recs, dummies), (s, rs)) =>
   319       if s mem rsets then
   320         let
   321           val (d :: dummies') = dummies;
   322           val (recs1, recs2) = chop (length rs) (if d then tl recs else recs)
   323         in ((recs2, dummies'), map (head_of o hd o rev o snd o strip_comb o
   324           fst o HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) recs1)
   325         end
   326       else ((recs, dummies), replicate (length rs) Extraction.nullt))
   327         ((get #rec_thms dt_info, dummies), rss);
   328     val rintrs = map (fn (intr, c) => Envir.eta_contract
   329       (Extraction.realizes_of thy2 vs
   330         (if c = Extraction.nullt then c else list_comb (c, map Var (rev
   331           (Term.add_vars (prop_of intr) []) \\ params'))) (prop_of intr)))
   332             (maps snd rss ~~ List.concat constrss);
   333     val (rlzpreds, rlzpreds') = split_list
   334       (distinct (op = o pairself (#1 o #1)) (map (fn rintr =>
   335         let
   336           val Const (s, T) = head_of (HOLogic.dest_Trueprop
   337             (Logic.strip_assums_concl rintr));
   338           val s' = Sign.base_name s;
   339           val T' = Logic.unvarifyT T
   340         in (((Name.binding s', T'), NoSyn), (Const (s, T'), Free (s', T'))) end) rintrs));
   341     val rlzparams = map (fn Var ((s, _), T) => (s, Logic.unvarifyT T))
   342       (List.take (snd (strip_comb
   343         (HOLogic.dest_Trueprop (Logic.strip_assums_concl (hd rintrs)))), nparms));
   344 
   345     (** realizability predicate **)
   346 
   347     val (ind_info, thy3') = thy2 |>
   348       InductivePackage.add_inductive_global (serial_string ())
   349         {quiet_mode = false, verbose = false, kind = Thm.theoremK, alt_name = Name.no_binding,
   350           coind = false, no_elim = false, no_ind = false, skip_mono = false}
   351         rlzpreds rlzparams (map (fn (rintr, intr) =>
   352           ((Name.binding (Sign.base_name (name_of_thm intr)), []),
   353            subst_atomic rlzpreds' (Logic.unvarify rintr)))
   354              (rintrs ~~ maps snd rss)) [] ||>
   355       Sign.absolute_path;
   356     val thy3 = fold (PureThy.hide_fact false o name_of_thm) (#intrs ind_info) thy3';
   357 
   358     (** realizer for induction rule **)
   359 
   360     val Ps = List.mapPartial (fn _ $ M $ P => if pred_of M mem rsets then
   361       SOME (fst (fst (dest_Var (head_of P)))) else NONE)
   362         (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of raw_induct)));
   363 
   364     fun add_ind_realizer (thy, Ps) =
   365       let
   366         val vs' = rename (map (pairself (fst o fst o dest_Var))
   367           (params ~~ List.take (snd (strip_comb (HOLogic.dest_Trueprop
   368             (hd (prems_of (hd inducts))))), nparms))) vs;
   369         val rs = indrule_realizer thy induct raw_induct rsets params'
   370           (vs' @ Ps) rec_names rss' intrs dummies;
   371         val rlzs = map (fn (r, ind) => Extraction.realizes_of thy (vs' @ Ps) r
   372           (prop_of ind)) (rs ~~ inducts);
   373         val used = foldr add_term_free_names [] rlzs;
   374         val rnames = Name.variant_list used (replicate (length inducts) "r");
   375         val rnames' = Name.variant_list
   376           (used @ rnames) (replicate (length intrs) "s");
   377         val rlzs' as (prems, _, _) :: _ = map (fn (rlz, name) =>
   378           let
   379             val (P, Q) = strip_one name (Logic.unvarify rlz);
   380             val Q' = strip_all' [] rnames' Q
   381           in
   382             (Logic.strip_imp_prems Q', P, Logic.strip_imp_concl Q')
   383           end) (rlzs ~~ rnames);
   384         val concl = HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj (map
   385           (fn (_, _ $ P, _ $ Q) => HOLogic.mk_imp (P, Q)) rlzs'));
   386         val rews = map mk_meta_eq
   387           (fst_conv :: snd_conv :: get #rec_thms dt_info);
   388         val thm = Goal.prove_global thy [] prems concl (fn {prems, ...} => EVERY
   389           [rtac (#raw_induct ind_info) 1,
   390            rewrite_goals_tac rews,
   391            REPEAT ((resolve_tac prems THEN_ALL_NEW EVERY'
   392              [K (rewrite_goals_tac rews), ObjectLogic.atomize_prems_tac,
   393               DEPTH_SOLVE_1 o FIRST' [atac, etac allE, etac impE]]) 1)]);
   394         val (thm', thy') = PureThy.store_thm (space_implode "_"
   395           (NameSpace.qualified qualifier "induct" :: vs' @ Ps @ ["correctness"]), thm) thy;
   396         val thms = map (fn th => zero_var_indexes (rotate_prems ~1 (th RS mp)))
   397           (DatatypeAux.split_conj_thm thm');
   398         val ([thms'], thy'') = PureThy.add_thmss
   399           [((space_implode "_"
   400              (NameSpace.qualified qualifier "inducts" :: vs' @ Ps @
   401                ["correctness"]), thms), [])] thy';
   402         val realizers = inducts ~~ thms' ~~ rlzs ~~ rs;
   403       in
   404         Extraction.add_realizers_i
   405           (map (fn (((ind, corr), rlz), r) =>
   406               mk_realizer thy' (vs' @ Ps) (Thm.get_name ind, ind, corr, rlz, r))
   407             realizers @ (case realizers of
   408              [(((ind, corr), rlz), r)] =>
   409                [mk_realizer thy' (vs' @ Ps) (NameSpace.qualified qualifier "induct",
   410                   ind, corr, rlz, r)]
   411            | _ => [])) thy''
   412       end;
   413 
   414     (** realizer for elimination rules **)
   415 
   416     val case_names = map (fst o dest_Const o head_of o fst o HOLogic.dest_eq o
   417       HOLogic.dest_Trueprop o prop_of o hd) (get #case_thms dt_info);
   418 
   419     fun add_elim_realizer Ps
   420       (((((elim, elimR), intrs), case_thms), case_name), dummy) thy =
   421       let
   422         val (prem :: prems) = prems_of elim;
   423         fun reorder1 (p, (_, intr)) =
   424           Library.foldl (fn (t, ((s, _), T)) => Logic.all (Free (s, T)) t)
   425             (strip_all p, Term.add_vars (prop_of intr) [] \\ params');
   426         fun reorder2 ((ivs, intr), i) =
   427           let val fs = Term.add_vars (prop_of intr) [] \\ params'
   428           in Library.foldl (fn (t, x) => lambda (Var x) t)
   429             (list_comb (Bound (i + length ivs), ivs), fs)
   430           end;
   431         val p = Logic.list_implies
   432           (map reorder1 (prems ~~ intrs) @ [prem], concl_of elim);
   433         val T' = Extraction.etype_of thy (vs @ Ps) [] p;
   434         val T = if dummy then (HOLogic.unitT --> body_type T') --> T' else T';
   435         val Ts = map (Extraction.etype_of thy (vs @ Ps) []) (prems_of elim);
   436         val r = if null Ps then Extraction.nullt
   437           else list_abs (map (pair "x") Ts, list_comb (Const (case_name, T),
   438             (if dummy then
   439                [Abs ("x", HOLogic.unitT, Const ("HOL.default_class.default", body_type T))]
   440              else []) @
   441             map reorder2 (intrs ~~ (length prems - 1 downto 0)) @
   442             [Bound (length prems)]));
   443         val rlz = Extraction.realizes_of thy (vs @ Ps) r (prop_of elim);
   444         val rlz' = strip_all (Logic.unvarify rlz);
   445         val rews = map mk_meta_eq case_thms;
   446         val thm = Goal.prove_global thy []
   447           (Logic.strip_imp_prems rlz') (Logic.strip_imp_concl rlz') (fn {prems, ...} => EVERY
   448           [cut_facts_tac [hd prems] 1,
   449            etac elimR 1,
   450            ALLGOALS (asm_simp_tac HOL_basic_ss),
   451            rewrite_goals_tac rews,
   452            REPEAT ((resolve_tac prems THEN_ALL_NEW (ObjectLogic.atomize_prems_tac THEN'
   453              DEPTH_SOLVE_1 o FIRST' [atac, etac allE, etac impE])) 1)]);
   454         val (thm', thy') = PureThy.store_thm (space_implode "_"
   455           (name_of_thm elim :: vs @ Ps @ ["correctness"]), thm) thy
   456       in
   457         Extraction.add_realizers_i
   458           [mk_realizer thy' (vs @ Ps) (name_of_thm elim, elim, thm', rlz, r)] thy'
   459       end;
   460 
   461     (** add realizers to theory **)
   462 
   463     val thy4 = Library.foldl add_ind_realizer (thy3, subsets Ps);
   464     val thy5 = Extraction.add_realizers_i
   465       (map (mk_realizer thy4 vs) (map (fn (((rule, rrule), rlz), c) =>
   466          (name_of_thm rule, rule, rrule, rlz,
   467             list_comb (c, map Var (rev (Term.add_vars (prop_of rule) []) \\ params'))))
   468               (List.concat (map snd rss) ~~ #intrs ind_info ~~ rintrs ~~
   469                  List.concat constrss))) thy4;
   470     val elimps = List.mapPartial (fn ((s, intrs), p) =>
   471       if s mem rsets then SOME (p, intrs) else NONE)
   472         (rss' ~~ (elims ~~ #elims ind_info));
   473     val thy6 = Library.foldl (fn (thy, p as (((((elim, _), _), _), _), _)) => thy |>
   474       add_elim_realizer [] p |> add_elim_realizer [fst (fst (dest_Var
   475         (HOLogic.dest_Trueprop (concl_of elim))))] p) (thy5,
   476            elimps ~~ get #case_thms dt_info ~~ case_names ~~ dummies)
   477 
   478   in Sign.restore_naming thy thy6 end;
   479 
   480 fun add_ind_realizers name rsets thy =
   481   let
   482     val (_, {intrs, induct, raw_induct, elims, ...}) =
   483       InductivePackage.the_inductive (ProofContext.init thy) name;
   484     val vss = sort (int_ord o pairself length)
   485       (subsets (map fst (relevant_vars (concl_of (hd intrs)))))
   486   in
   487     Library.foldl (add_ind_realizer rsets intrs induct raw_induct elims) (thy, vss)
   488   end
   489 
   490 fun rlz_attrib arg = Thm.declaration_attribute (fn thm => Context.mapping
   491   let
   492     fun err () = error "ind_realizer: bad rule";
   493     val sets =
   494       (case HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of thm)) of
   495            [_] => [pred_of (HOLogic.dest_Trueprop (hd (prems_of thm)))]
   496          | xs => map (pred_of o fst o HOLogic.dest_imp) xs)
   497          handle TERM _ => err () | Empty => err ();
   498   in 
   499     add_ind_realizers (hd sets)
   500       (case arg of
   501         NONE => sets | SOME NONE => []
   502       | SOME (SOME sets') => sets \\ sets')
   503   end I);
   504 
   505 val ind_realizer = Attrib.syntax
   506  ((Scan.option (Scan.lift (Args.$$$ "irrelevant") |--
   507     Scan.option (Scan.lift (Args.colon) |--
   508       Scan.repeat1 Args.const))) >> rlz_attrib);
   509 
   510 val setup =
   511   Attrib.add_attributes [("ind_realizer", ind_realizer, "add realizers for inductive set")];
   512 
   513 end;
   514