src/HOL/Tools/inductive_realizer.ML
author wenzelm
Sat Mar 20 17:33:11 2010 +0100 (2010-03-20)
changeset 35845 e5980f0ad025
parent 35625 9c818cab0dd0
child 36043 d149c3886e7e
permissions -rw-r--r--
renamed varify/unvarify operations to varify_global/unvarify_global to emphasize that these only work in a global situation;
     1 (*  Title:      HOL/Tools/inductive_realizer.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Porgram extraction from proofs involving inductive predicates:
     5 Realizers for induction and elimination rules.
     6 *)
     7 
     8 signature INDUCTIVE_REALIZER =
     9 sig
    10   val add_ind_realizers: string -> string list -> theory -> theory
    11   val setup: theory -> theory
    12 end;
    13 
    14 structure InductiveRealizer : INDUCTIVE_REALIZER =
    15 struct
    16 
    17 (* FIXME: Local_Theory.note should return theorems with proper names! *)  (* FIXME ?? *)
    18 fun name_of_thm thm =
    19   (case Proofterm.fold_proof_atoms false (fn PThm (_, ((name, _, _), _)) => cons name | _ => I)
    20       [Thm.proof_of thm] [] of
    21     [name] => name
    22   | _ => error ("name_of_thm: bad proof of theorem\n" ^ Display.string_of_thm_without_context 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' (Term.add_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 = List.foldr (fn
    59       (Var ((a, i), T), vs) => (case strip_type T of
    60         (_, Type (s, _)) => if s mem [@{type_name bool}] then (a, T) :: vs else vs
    61       | _ => vs)
    62     | (_, vs) => vs) [] (OldTerm.term_vars prop);
    63 
    64 fun dt_of_intrs thy vs nparms intrs =
    65   let
    66     val iTs = OldTerm.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 (take nparms ts);
    71     val tname = Binding.name (space_implode "_" (Long_Name.base_name s ^ "T" :: vs));
    72     fun constr_of_intr intr = (Binding.name (Long_Name.base_name (name_of_thm intr)),
    73       map (Logic.unvarifyT_global o snd) (subtract (op =) params (rev (Term.add_vars (prop_of intr) []))) @
    74         filter_out (equal Extraction.nullT) (map
    75           (Logic.unvarifyT_global 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 = OldTerm.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 ((Long_Name.base_name s, 0), rT);
   116     val S = list_comb (h, params @ xs);
   117     val rvs = relevant_vars S;
   118     val vs' = subtract (op =) vs (map fst rvs);
   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       (subtract (op =) params (Term.add_vars (prop_of intr) []));
   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     val is_rec = exists_Const (fn (c, _) => member (op =) rsets c);
   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 (@{const_name Trueprop}, _) $ t) =
   154           (case head_of t of
   155             Const (s, _) => can (Inductive.the_inductive ctxt) s
   156           | _ => true)
   157       | is_meta _ = false;
   158 
   159     fun fun_of ts rts args used (prem :: prems) =
   160           let
   161             val T = Extraction.etype_of thy vs [] prem;
   162             val [x, r] = Name.variant_list used ["x", "r"]
   163           in if T = Extraction.nullT
   164             then fun_of ts rts args used prems
   165             else if is_rec prem then
   166               if is_meta prem then
   167                 let
   168                   val prem' :: prems' = prems;
   169                   val U = Extraction.etype_of thy vs [] prem';
   170                 in if U = Extraction.nullT
   171                   then fun_of (Free (x, T) :: ts)
   172                     (Free (r, binder_types T ---> HOLogic.unitT) :: rts)
   173                     (Free (x, T) :: args) (x :: r :: used) prems'
   174                   else fun_of (Free (x, T) :: ts) (Free (r, U) :: rts)
   175                     (Free (r, U) :: Free (x, T) :: args) (x :: r :: used) prems'
   176                 end
   177               else (case strip_type T of
   178                   (Ts, Type (@{type_name "*"}, [T1, T2])) =>
   179                     let
   180                       val fx = Free (x, Ts ---> T1);
   181                       val fr = Free (r, Ts ---> T2);
   182                       val bs = map Bound (length Ts - 1 downto 0);
   183                       val t = list_abs (map (pair "z") Ts,
   184                         HOLogic.mk_prod (list_comb (fx, bs), list_comb (fr, bs)))
   185                     in fun_of (fx :: ts) (fr :: rts) (t::args)
   186                       (x :: r :: used) prems
   187                     end
   188                 | (Ts, U) => fun_of (Free (x, T) :: ts)
   189                     (Free (r, binder_types T ---> HOLogic.unitT) :: rts)
   190                     (Free (x, T) :: args) (x :: r :: used) prems)
   191             else fun_of (Free (x, T) :: ts) rts (Free (x, T) :: args)
   192               (x :: used) prems
   193           end
   194       | fun_of ts rts args used [] =
   195           let val xs = rev (rts @ ts)
   196           in if conclT = Extraction.nullT
   197             then list_abs_free (map dest_Free xs, HOLogic.unit)
   198             else list_abs_free (map dest_Free xs, list_comb
   199               (Free ("r" ^ Long_Name.base_name (name_of_thm intr),
   200                 map fastype_of (rev args) ---> conclT), rev args))
   201           end
   202 
   203   in fun_of args' [] (rev args) used (Logic.strip_imp_prems rule') end;
   204 
   205 fun indrule_realizer thy induct raw_induct rsets params vs rec_names rss intrs dummies =
   206   let
   207     val concls = HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of raw_induct));
   208     val premss = map_filter (fn (s, rs) => if member (op =) rsets s then
   209       SOME (rs, map (fn (_, r) => nth (prems_of raw_induct)
   210         (find_index (fn prp => prp = prop_of r) (map prop_of intrs))) rs) else NONE) rss;
   211     val fs = maps (fn ((intrs, prems), dummy) =>
   212       let
   213         val fs = map (fn (rule, (ivs, intr)) =>
   214           fun_of_prem thy rsets vs params rule ivs intr) (prems ~~ intrs)
   215       in
   216         if dummy then Const (@{const_name default},
   217             HOLogic.unitT --> body_type (fastype_of (hd fs))) :: fs
   218         else fs
   219       end) (premss ~~ dummies);
   220     val frees = fold Term.add_frees fs [];
   221     val Ts = map fastype_of fs;
   222     fun name_of_fn intr = "r" ^ Long_Name.base_name (name_of_thm intr)
   223   in
   224     fst (fold_map (fn concl => fn names =>
   225       let val T = Extraction.etype_of thy vs [] concl
   226       in if T = Extraction.nullT then (Extraction.nullt, names) else
   227         let
   228           val Type ("fun", [U, _]) = T;
   229           val a :: names' = names
   230         in (list_abs_free (("x", U) :: map_filter (fn intr =>
   231           Option.map (pair (name_of_fn intr))
   232             (AList.lookup (op =) frees (name_of_fn intr))) intrs,
   233           list_comb (Const (a, Ts ---> T), fs) $ Free ("x", U)), names')
   234         end
   235       end) concls rec_names)
   236   end;
   237 
   238 fun add_dummy name dname (x as (_, (vs, s, mfx, cs))) =
   239   if Binding.eq_name (name, s) then (true, (vs, s, mfx, (dname, [HOLogic.unitT], NoSyn) :: cs))
   240   else x;
   241 
   242 fun add_dummies f [] _ thy =
   243       (([], NONE), thy)
   244   | add_dummies f dts used thy =
   245       thy
   246       |> f (map snd dts)
   247       |-> (fn dtinfo => pair (map fst dts, SOME dtinfo))
   248     handle Datatype_Aux.Datatype_Empty name' =>
   249       let
   250         val name = Long_Name.base_name name';
   251         val dname = Name.variant used "Dummy";
   252       in
   253         thy
   254         |> add_dummies f (map (add_dummy (Binding.name name) (Binding.name dname)) dts) (dname :: used)
   255       end;
   256 
   257 fun mk_realizer thy vs (name, rule, rrule, rlz, rt) =
   258   let
   259     val rvs = map fst (relevant_vars (prop_of rule));
   260     val xs = rev (Term.add_vars (prop_of rule) []);
   261     val vs1 = map Var (filter_out (fn ((a, _), _) => a mem rvs) xs);
   262     val rlzvs = rev (Term.add_vars (prop_of rrule) []);
   263     val vs2 = map (fn (ixn, _) => Var (ixn, (the o AList.lookup (op =) rlzvs) ixn)) xs;
   264     val rs = map Var (subtract (op = o pairself fst) xs rlzvs);
   265     val rlz' = fold_rev Logic.all (vs2 @ rs) (prop_of rrule);
   266     val rlz'' = fold_rev Logic.all vs2 rlz
   267   in (name, (vs,
   268     if rt = Extraction.nullt then rt else fold_rev lambda vs1 rt,
   269     ProofRewriteRules.un_hhf_proof rlz' rlz''
   270       (fold_rev forall_intr_prf (vs2 @ rs) (prf_of rrule))))
   271   end;
   272 
   273 fun rename tab = map (fn x => the_default x (AList.lookup op = tab x));
   274 
   275 fun add_ind_realizer rsets intrs induct raw_induct elims vs thy =
   276   let
   277     val qualifier = Long_Name.qualifier (name_of_thm induct);
   278     val inducts = PureThy.get_thms thy (Long_Name.qualify qualifier "inducts");
   279     val iTs = OldTerm.term_tvars (prop_of (hd intrs));
   280     val ar = length vs + length iTs;
   281     val params = Inductive.params_of raw_induct;
   282     val arities = Inductive.arities_of raw_induct;
   283     val nparms = length params;
   284     val params' = map dest_Var params;
   285     val rss = Inductive.partition_rules raw_induct intrs;
   286     val rss' = map (fn (((s, rs), (_, arity)), elim) =>
   287       (s, (Inductive.infer_intro_vars elim arity rs ~~ rs)))
   288         (rss ~~ arities ~~ elims);
   289     val (prfx, _) = split_last (Long_Name.explode (fst (hd rss)));
   290     val tnames = map (fn s => space_implode "_" (s ^ "T" :: vs)) rsets;
   291 
   292     val thy1 = thy |>
   293       Sign.root_path |>
   294       Sign.add_path (Long_Name.implode prfx);
   295     val (ty_eqs, rlz_eqs) = split_list
   296       (map (fn (s, rs) => mk_realizes_eqn (not (s mem rsets)) vs nparms rs) rss);
   297 
   298     val thy1' = thy1 |>
   299       Theory.copy |>
   300       Sign.add_types (map (fn s => (Binding.name (Long_Name.base_name s), ar, NoSyn)) tnames) |>
   301       fold (fn s => AxClass.axiomatize_arity
   302         (s, replicate ar HOLogic.typeS, HOLogic.typeS)) tnames |>
   303         Extraction.add_typeof_eqns_i ty_eqs;
   304     val dts = map_filter (fn (s, rs) => if s mem rsets then
   305       SOME (dt_of_intrs thy1' vs nparms rs) else NONE) rss;
   306 
   307     (** datatype representing computational content of inductive set **)
   308 
   309     val ((dummies, some_dt_names), thy2) =
   310       thy1
   311       |> add_dummies (Datatype.add_datatype
   312            { strict = false, quiet = false } (map (Binding.name_of o #2) dts))
   313            (map (pair false) dts) []
   314       ||> Extraction.add_typeof_eqns_i ty_eqs
   315       ||> Extraction.add_realizes_eqns_i rlz_eqs;
   316     val dt_names = these some_dt_names;
   317     val case_thms = map (#case_rewrites o Datatype.the_info thy2) dt_names;
   318     val rec_thms = if null dt_names then []
   319       else (#rec_rewrites o Datatype.the_info thy2) (hd dt_names);
   320     val rec_names = distinct (op =) (map (fst o dest_Const o head_of o fst o
   321       HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) rec_thms);
   322     val (constrss, _) = fold_map (fn (s, rs) => fn (recs, dummies) =>
   323       if member (op =) rsets s then
   324         let
   325           val (d :: dummies') = dummies;
   326           val (recs1, recs2) = chop (length rs) (if d then tl recs else recs)
   327         in (map (head_of o hd o rev o snd o strip_comb o fst o
   328           HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) recs1, (recs2, dummies'))
   329         end
   330       else (replicate (length rs) Extraction.nullt, (recs, dummies)))
   331         rss (rec_thms, dummies);
   332     val rintrs = map (fn (intr, c) => Envir.eta_contract
   333       (Extraction.realizes_of thy2 vs
   334         (if c = Extraction.nullt then c else list_comb (c, map Var (rev
   335           (subtract (op =) params' (Term.add_vars (prop_of intr) []))))) (prop_of intr)))
   336             (maps snd rss ~~ flat constrss);
   337     val (rlzpreds, rlzpreds') =
   338       rintrs |> map (fn rintr =>
   339         let
   340           val Const (s, T) = head_of (HOLogic.dest_Trueprop (Logic.strip_assums_concl rintr));
   341           val s' = Long_Name.base_name s;
   342           val T' = Logic.unvarifyT_global T;
   343         in (((s', T'), NoSyn), (Const (s, T'), Free (s', T'))) end)
   344       |> distinct (op = o pairself (#1 o #1))
   345       |> map (apfst (apfst (apfst Binding.name)))
   346       |> split_list;
   347 
   348     val rlzparams = map (fn Var ((s, _), T) => (s, Logic.unvarifyT_global T))
   349       (List.take (snd (strip_comb
   350         (HOLogic.dest_Trueprop (Logic.strip_assums_concl (hd rintrs)))), nparms));
   351 
   352     (** realizability predicate **)
   353 
   354     val (ind_info, thy3') = thy2 |>
   355       Inductive.add_inductive_global
   356         {quiet_mode = false, verbose = false, alt_name = Binding.empty, coind = false,
   357           no_elim = false, no_ind = false, skip_mono = false, fork_mono = false}
   358         rlzpreds rlzparams (map (fn (rintr, intr) =>
   359           ((Binding.name (Long_Name.base_name (name_of_thm intr)), []),
   360            subst_atomic rlzpreds' (Logic.unvarify_global rintr)))
   361              (rintrs ~~ maps snd rss)) [] ||>
   362       Sign.root_path;
   363     val thy3 = fold (PureThy.hide_fact false o name_of_thm) (#intrs ind_info) thy3';
   364 
   365     (** realizer for induction rule **)
   366 
   367     val Ps = map_filter (fn _ $ M $ P => if pred_of M mem rsets then
   368       SOME (fst (fst (dest_Var (head_of P)))) else NONE)
   369         (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of raw_induct)));
   370 
   371     fun add_ind_realizer Ps thy =
   372       let
   373         val vs' = rename (map (pairself (fst o fst o dest_Var))
   374           (params ~~ List.take (snd (strip_comb (HOLogic.dest_Trueprop
   375             (hd (prems_of (hd inducts))))), nparms))) vs;
   376         val rs = indrule_realizer thy induct raw_induct rsets params'
   377           (vs' @ Ps) rec_names rss' intrs dummies;
   378         val rlzs = map (fn (r, ind) => Extraction.realizes_of thy (vs' @ Ps) r
   379           (prop_of ind)) (rs ~~ inducts);
   380         val used = fold Term.add_free_names rlzs [];
   381         val rnames = Name.variant_list used (replicate (length inducts) "r");
   382         val rnames' = Name.variant_list
   383           (used @ rnames) (replicate (length intrs) "s");
   384         val rlzs' as (prems, _, _) :: _ = map (fn (rlz, name) =>
   385           let
   386             val (P, Q) = strip_one name (Logic.unvarify_global rlz);
   387             val Q' = strip_all' [] rnames' Q
   388           in
   389             (Logic.strip_imp_prems Q', P, Logic.strip_imp_concl Q')
   390           end) (rlzs ~~ rnames);
   391         val concl = HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj (map
   392           (fn (_, _ $ P, _ $ Q) => HOLogic.mk_imp (P, Q)) rlzs'));
   393         val rews = map mk_meta_eq (fst_conv :: snd_conv :: rec_thms);
   394         val thm = Goal.prove_global thy [] prems concl (fn {prems, ...} => EVERY
   395           [rtac (#raw_induct ind_info) 1,
   396            rewrite_goals_tac rews,
   397            REPEAT ((resolve_tac prems THEN_ALL_NEW EVERY'
   398              [K (rewrite_goals_tac rews), Object_Logic.atomize_prems_tac,
   399               DEPTH_SOLVE_1 o FIRST' [atac, etac allE, etac impE]]) 1)]);
   400         val (thm', thy') = PureThy.store_thm (Binding.qualified_name (space_implode "_"
   401           (Long_Name.qualify qualifier "induct" :: vs' @ Ps @ ["correctness"])), thm) thy;
   402         val thms = map (fn th => zero_var_indexes (rotate_prems ~1 (th RS mp)))
   403           (Datatype_Aux.split_conj_thm thm');
   404         val ([thms'], thy'') = PureThy.add_thmss
   405           [((Binding.qualified_name (space_implode "_"
   406              (Long_Name.qualify qualifier "inducts" :: vs' @ Ps @
   407                ["correctness"])), thms), [])] thy';
   408         val realizers = inducts ~~ thms' ~~ rlzs ~~ rs;
   409       in
   410         Extraction.add_realizers_i
   411           (map (fn (((ind, corr), rlz), r) =>
   412               mk_realizer thy' (vs' @ Ps) (Thm.get_name ind, ind, corr, rlz, r))
   413             realizers @ (case realizers of
   414              [(((ind, corr), rlz), r)] =>
   415                [mk_realizer thy' (vs' @ Ps) (Long_Name.qualify qualifier "induct",
   416                   ind, corr, rlz, r)]
   417            | _ => [])) thy''
   418       end;
   419 
   420     (** realizer for elimination rules **)
   421 
   422     val case_names = map (fst o dest_Const o head_of o fst o HOLogic.dest_eq o
   423       HOLogic.dest_Trueprop o prop_of o hd) case_thms;
   424 
   425     fun add_elim_realizer Ps
   426       (((((elim, elimR), intrs), case_thms), case_name), dummy) thy =
   427       let
   428         val (prem :: prems) = prems_of elim;
   429         fun reorder1 (p, (_, intr)) =
   430           fold (fn ((s, _), T) => Logic.all (Free (s, T)))
   431             (subtract (op =) params' (Term.add_vars (prop_of intr) []))
   432             (strip_all p);
   433         fun reorder2 ((ivs, intr), i) =
   434           let val fs = subtract (op =) params' (Term.add_vars (prop_of intr) [])
   435           in fold (lambda o Var) fs (list_comb (Bound (i + length ivs), ivs)) end;
   436         val p = Logic.list_implies
   437           (map reorder1 (prems ~~ intrs) @ [prem], concl_of elim);
   438         val T' = Extraction.etype_of thy (vs @ Ps) [] p;
   439         val T = if dummy then (HOLogic.unitT --> body_type T') --> T' else T';
   440         val Ts = map (Extraction.etype_of thy (vs @ Ps) []) (prems_of elim);
   441         val r = if null Ps then Extraction.nullt
   442           else list_abs (map (pair "x") Ts, list_comb (Const (case_name, T),
   443             (if dummy then
   444                [Abs ("x", HOLogic.unitT, Const (@{const_name default}, body_type T))]
   445              else []) @
   446             map reorder2 (intrs ~~ (length prems - 1 downto 0)) @
   447             [Bound (length prems)]));
   448         val rlz = Extraction.realizes_of thy (vs @ Ps) r (prop_of elim);
   449         val rlz' = strip_all (Logic.unvarify_global rlz);
   450         val rews = map mk_meta_eq case_thms;
   451         val thm = Goal.prove_global thy []
   452           (Logic.strip_imp_prems rlz') (Logic.strip_imp_concl rlz') (fn {prems, ...} => EVERY
   453           [cut_facts_tac [hd prems] 1,
   454            etac elimR 1,
   455            ALLGOALS (asm_simp_tac HOL_basic_ss),
   456            rewrite_goals_tac rews,
   457            REPEAT ((resolve_tac prems THEN_ALL_NEW (Object_Logic.atomize_prems_tac THEN'
   458              DEPTH_SOLVE_1 o FIRST' [atac, etac allE, etac impE])) 1)]);
   459         val (thm', thy') = PureThy.store_thm (Binding.qualified_name (space_implode "_"
   460           (name_of_thm elim :: vs @ Ps @ ["correctness"])), thm) thy
   461       in
   462         Extraction.add_realizers_i
   463           [mk_realizer thy' (vs @ Ps) (name_of_thm elim, elim, thm', rlz, r)] thy'
   464       end;
   465 
   466     (** add realizers to theory **)
   467 
   468     val thy4 = fold add_ind_realizer (subsets Ps) thy3;
   469     val thy5 = Extraction.add_realizers_i
   470       (map (mk_realizer thy4 vs) (map (fn (((rule, rrule), rlz), c) =>
   471          (name_of_thm rule, rule, rrule, rlz,
   472             list_comb (c, map Var (subtract (op =) params' (rev (Term.add_vars (prop_of rule) []))))))
   473               (maps snd rss ~~ #intrs ind_info ~~ rintrs ~~ flat constrss))) thy4;
   474     val elimps = map_filter (fn ((s, intrs), p) =>
   475       if s mem rsets then SOME (p, intrs) else NONE)
   476         (rss' ~~ (elims ~~ #elims ind_info));
   477     val thy6 =
   478       fold (fn p as (((((elim, _), _), _), _), _) =>
   479         add_elim_realizer [] p #>
   480         add_elim_realizer [fst (fst (dest_Var (HOLogic.dest_Trueprop (concl_of elim))))] p)
   481       (elimps ~~ case_thms ~~ case_names ~~ dummies) thy5;
   482 
   483   in Sign.restore_naming thy thy6 end;
   484 
   485 fun add_ind_realizers name rsets thy =
   486   let
   487     val (_, {intrs, induct, raw_induct, elims, ...}) =
   488       Inductive.the_inductive (ProofContext.init thy) name;
   489     val vss = sort (int_ord o pairself length)
   490       (subsets (map fst (relevant_vars (concl_of (hd intrs)))))
   491   in
   492     fold (add_ind_realizer rsets intrs induct raw_induct elims) vss thy
   493   end
   494 
   495 fun rlz_attrib arg = Thm.declaration_attribute (fn thm => Context.mapping
   496   let
   497     fun err () = error "ind_realizer: bad rule";
   498     val sets =
   499       (case HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of thm)) of
   500            [_] => [pred_of (HOLogic.dest_Trueprop (hd (prems_of thm)))]
   501          | xs => map (pred_of o fst o HOLogic.dest_imp) xs)
   502          handle TERM _ => err () | Empty => err ();
   503   in 
   504     add_ind_realizers (hd sets)
   505       (case arg of
   506         NONE => sets | SOME NONE => []
   507       | SOME (SOME sets') => subtract (op =) sets' sets)
   508   end I);
   509 
   510 val setup =
   511   Attrib.setup @{binding ind_realizer}
   512     ((Scan.option (Scan.lift (Args.$$$ "irrelevant") |--
   513       Scan.option (Scan.lift (Args.colon) |-- Scan.repeat1 (Args.const true)))) >> rlz_attrib)
   514     "add realizers for inductive set";
   515 
   516 end;
   517