src/HOL/Tools/inductive_realizer.ML
author haftmann
Fri Oct 10 19:55:32 2014 +0200 (2014-10-10)
changeset 58646 cd63a4b12a33
parent 58372 bfd497f2f4c2
child 58963 26bf09b95dda
permissions -rw-r--r--
specialized specification: avoid trivial instances
     1 (*  Title:      HOL/Tools/inductive_realizer.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Program 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 end;
    12 
    13 structure InductiveRealizer : INDUCTIVE_REALIZER =
    14 struct
    15 
    16 fun name_of_thm thm =
    17   (case Proofterm.fold_proof_atoms false (fn PThm (_, ((name, _, _), _)) => cons name | _ => I)
    18       [Thm.proof_of thm] [] of
    19     [name] => name
    20   | _ => raise THM ("name_of_thm: bad proof of theorem", 0, [thm]));
    21 
    22 fun prf_of thm =
    23   Reconstruct.proof_of thm
    24   |> Reconstruct.expand_proof (Thm.theory_of_thm thm) [("", NONE)];  (* FIXME *)
    25 
    26 fun subsets [] = [[]]
    27   | subsets (x::xs) =
    28       let val ys = subsets xs
    29       in ys @ map (cons x) ys end;
    30 
    31 val pred_of = fst o dest_Const o head_of;
    32 
    33 fun strip_all' used names (Const (@{const_name Pure.all}, _) $ Abs (s, T, t)) =
    34       let val (s', names') = (case names of
    35           [] => (singleton (Name.variant_list used) s, [])
    36         | name :: names' => (name, names'))
    37       in strip_all' (s'::used) names' (subst_bound (Free (s', T), t)) end
    38   | strip_all' used names ((t as Const (@{const_name Pure.imp}, _) $ P) $ Q) =
    39       t $ strip_all' used names Q
    40   | strip_all' _ _ t = t;
    41 
    42 fun strip_all t = strip_all' (Term.add_free_names t []) [] t;
    43 
    44 fun strip_one name
    45     (Const (@{const_name Pure.all}, _) $ Abs (s, T, Const (@{const_name Pure.imp}, _) $ P $ Q)) =
    46       (subst_bound (Free (name, T), P), subst_bound (Free (name, T), Q))
    47   | strip_one _ (Const (@{const_name Pure.imp}, _) $ P $ Q) = (P, Q);
    48 
    49 fun relevant_vars prop = fold (fn ((a, i), T) => fn vs =>
    50      (case strip_type T of
    51         (_, Type (s, _)) => if s = @{type_name bool} then (a, T) :: vs else vs
    52       | _ => vs)) (Term.add_vars prop []) [];
    53 
    54 val attach_typeS = map_types (map_atyps
    55   (fn TFree (s, []) => TFree (s, @{sort type})
    56     | TVar (ixn, []) => TVar (ixn, @{sort type})
    57     | T => T));
    58 
    59 fun dt_of_intrs thy vs nparms intrs =
    60   let
    61     val iTs = rev (Term.add_tvars (prop_of (hd intrs)) []);
    62     val (Const (s, _), ts) = strip_comb (HOLogic.dest_Trueprop
    63       (Logic.strip_imp_concl (prop_of (hd intrs))));
    64     val params = map dest_Var (take nparms ts);
    65     val tname = Binding.name (space_implode "_" (Long_Name.base_name s ^ "T" :: vs));
    66     fun constr_of_intr intr = (Binding.name (Long_Name.base_name (name_of_thm intr)),
    67       map (Logic.unvarifyT_global o snd) (subtract (op =) params (rev (Term.add_vars (prop_of intr) []))) @
    68         filter_out (equal Extraction.nullT) (map
    69           (Logic.unvarifyT_global o Extraction.etype_of thy vs []) (prems_of intr)),
    70             NoSyn);
    71   in
    72     ((tname, map (rpair dummyS) (map (fn a => "'" ^ a) vs @ map (fst o fst) iTs), NoSyn),
    73       map constr_of_intr intrs)
    74   end;
    75 
    76 fun mk_rlz T = Const ("realizes", [T, HOLogic.boolT] ---> HOLogic.boolT);
    77 
    78 (** turn "P" into "%r x. realizes r (P x)" **)
    79 
    80 fun gen_rvar vs (t as Var ((a, 0), T)) =
    81       if body_type T <> HOLogic.boolT then t else
    82         let
    83           val U = TVar (("'" ^ a, 0), [])
    84           val Ts = binder_types T;
    85           val i = length Ts;
    86           val xs = map (pair "x") Ts;
    87           val u = list_comb (t, map Bound (i - 1 downto 0))
    88         in 
    89           if member (op =) vs a then
    90             fold_rev Term.abs (("r", U) :: xs) (mk_rlz U $ Bound i $ u)
    91           else
    92             fold_rev Term.abs xs (mk_rlz Extraction.nullT $ Extraction.nullt $ u)
    93         end
    94   | gen_rvar _ t = t;
    95 
    96 fun mk_realizes_eqn n vs nparms intrs =
    97   let
    98     val intr = map_types Type.strip_sorts (prop_of (hd intrs));
    99     val concl = HOLogic.dest_Trueprop (Logic.strip_imp_concl intr);
   100     val iTs = rev (Term.add_tvars intr []);
   101     val Tvs = map TVar iTs;
   102     val (h as Const (s, T), us) = strip_comb concl;
   103     val params = List.take (us, nparms);
   104     val elTs = List.drop (binder_types T, nparms);
   105     val predT = elTs ---> HOLogic.boolT;
   106     val used = map (fst o fst o dest_Var) params;
   107     val xs = map (Var o apfst (rpair 0))
   108       (Name.variant_list used (replicate (length elTs) "x") ~~ elTs);
   109     val rT = if n then Extraction.nullT
   110       else Type (space_implode "_" (s ^ "T" :: vs),
   111         map (fn a => TVar (("'" ^ a, 0), [])) vs @ Tvs);
   112     val r = if n then Extraction.nullt else Var ((Long_Name.base_name s, 0), rT);
   113     val S = list_comb (h, params @ xs);
   114     val rvs = relevant_vars S;
   115     val vs' = subtract (op =) vs (map fst rvs);
   116     val rname = space_implode "_" (s ^ "R" :: vs);
   117 
   118     fun mk_Tprem n v =
   119       let val T = (the o AList.lookup (op =) rvs) v
   120       in (Const ("typeof", T --> Type ("Type", [])) $ Var ((v, 0), T),
   121         Extraction.mk_typ (if n then Extraction.nullT
   122           else TVar (("'" ^ v, 0), [])))
   123       end;
   124 
   125     val prems = map (mk_Tprem true) vs' @ map (mk_Tprem false) vs;
   126     val ts = map (gen_rvar vs) params;
   127     val argTs = map fastype_of ts;
   128 
   129   in ((prems, (Const ("typeof", HOLogic.boolT --> Type ("Type", [])) $ S,
   130        Extraction.mk_typ rT)),
   131     (prems, (mk_rlz rT $ r $ S,
   132        if n then list_comb (Const (rname, argTs ---> predT), ts @ xs)
   133        else list_comb (Const (rname, argTs @ [rT] ---> predT), ts @ [r] @ xs))))
   134   end;
   135 
   136 fun fun_of_prem thy rsets vs params rule ivs intr =
   137   let
   138     val ctxt = Proof_Context.init_global thy
   139     val args = map (Free o apfst fst o dest_Var) ivs;
   140     val args' = map (Free o apfst fst)
   141       (subtract (op =) params (Term.add_vars (prop_of intr) []));
   142     val rule' = strip_all rule;
   143     val conclT = Extraction.etype_of thy vs [] (Logic.strip_imp_concl rule');
   144     val used = map (fst o dest_Free) args;
   145 
   146     val is_rec = exists_Const (fn (c, _) => member (op =) rsets c);
   147 
   148     fun is_meta (Const (@{const_name Pure.all}, _) $ Abs (s, _, P)) = is_meta P
   149       | is_meta (Const (@{const_name Pure.imp}, _) $ _ $ Q) = is_meta Q
   150       | is_meta (Const (@{const_name Trueprop}, _) $ t) =
   151           (case head_of t of
   152             Const (s, _) => can (Inductive.the_inductive ctxt) s
   153           | _ => true)
   154       | is_meta _ = false;
   155 
   156     fun fun_of ts rts args used (prem :: prems) =
   157           let
   158             val T = Extraction.etype_of thy vs [] prem;
   159             val [x, r] = Name.variant_list used ["x", "r"]
   160           in if T = Extraction.nullT
   161             then fun_of ts rts args used prems
   162             else if is_rec prem then
   163               if is_meta prem then
   164                 let
   165                   val prem' :: prems' = prems;
   166                   val U = Extraction.etype_of thy vs [] prem';
   167                 in
   168                   if U = Extraction.nullT
   169                   then fun_of (Free (x, T) :: ts)
   170                     (Free (r, binder_types T ---> HOLogic.unitT) :: rts)
   171                     (Free (x, T) :: args) (x :: r :: used) prems'
   172                   else fun_of (Free (x, T) :: ts) (Free (r, U) :: rts)
   173                     (Free (r, U) :: Free (x, T) :: args) (x :: r :: used) prems'
   174                 end
   175               else
   176                 (case strip_type T of
   177                   (Ts, Type (@{type_name Product_Type.prod}, [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 =
   183                         fold_rev (Term.abs o 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) (x :: r :: used) prems end
   186                 | (Ts, U) => fun_of (Free (x, T) :: ts)
   187                     (Free (r, binder_types T ---> HOLogic.unitT) :: rts)
   188                     (Free (x, T) :: args) (x :: r :: used) prems)
   189             else fun_of (Free (x, T) :: ts) rts (Free (x, T) :: args)
   190               (x :: used) prems
   191           end
   192       | fun_of ts rts args used [] =
   193           let val xs = rev (rts @ ts)
   194           in if conclT = Extraction.nullT
   195             then fold_rev (absfree o dest_Free) xs HOLogic.unit
   196             else fold_rev (absfree o dest_Free) xs
   197               (list_comb
   198                 (Free ("r" ^ Long_Name.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 = map_filter (fn (s, rs) => if member (op =) rsets s then
   208       SOME (rs, map (fn (_, r) => nth (prems_of raw_induct)
   209         (find_index (fn prp => prp = 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
   215         if dummy then Const (@{const_name default},
   216             HOLogic.unitT --> body_type (fastype_of (hd fs))) :: fs
   217         else fs
   218       end) (premss ~~ dummies);
   219     val frees = fold Term.add_frees fs [];
   220     val Ts = map fastype_of fs;
   221     fun name_of_fn intr = "r" ^ Long_Name.base_name (name_of_thm intr)
   222   in
   223     fst (fold_map (fn concl => fn names =>
   224       let val T = Extraction.etype_of thy vs [] concl
   225       in if T = Extraction.nullT then (Extraction.nullt, names) else
   226         let
   227           val Type ("fun", [U, _]) = T;
   228           val a :: names' = names
   229         in
   230           (fold_rev absfree (("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 (_, ((s, vs, mx), cs))) =
   239   if Binding.eq_name (name, s)
   240   then (true, ((s, vs, mx), (dname, [HOLogic.unitT], NoSyn) :: cs))
   241   else x;
   242 
   243 fun add_dummies f [] _ thy =
   244       (([], NONE), thy)
   245   | add_dummies f dts used thy =
   246       thy
   247       |> f (map snd dts)
   248       |-> (fn dtinfo => pair (map fst dts, SOME dtinfo))
   249     handle Old_Datatype_Aux.Datatype_Empty name' =>
   250       let
   251         val name = Long_Name.base_name name';
   252         val dname = singleton (Name.variant_list used) "Dummy";
   253       in
   254         thy
   255         |> add_dummies f (map (add_dummy (Binding.name name) (Binding.name dname)) dts) (dname :: used)
   256       end;
   257 
   258 fun mk_realizer thy vs (name, rule, rrule, rlz, rt) =
   259   let
   260     val rvs = map fst (relevant_vars (prop_of rule));
   261     val xs = rev (Term.add_vars (prop_of rule) []);
   262     val vs1 = map Var (filter_out (fn ((a, _), _) => member (op =) rvs a) xs);
   263     val rlzvs = rev (Term.add_vars (prop_of rrule) []);
   264     val vs2 = map (fn (ixn, _) => Var (ixn, (the o AList.lookup (op =) rlzvs) ixn)) xs;
   265     val rs = map Var (subtract (op = o pairself fst) xs rlzvs);
   266     val rlz' = fold_rev Logic.all rs (prop_of rrule)
   267   in (name, (vs,
   268     if rt = Extraction.nullt then rt else fold_rev lambda vs1 rt,
   269     Extraction.abs_corr_shyps thy rule vs vs2
   270       (ProofRewriteRules.un_hhf_proof rlz' (attach_typeS rlz)
   271          (fold_rev Proofterm.forall_intr_proof' rs (prf_of rrule)))))
   272   end;
   273 
   274 fun rename tab = map (fn x => the_default x (AList.lookup op = tab x));
   275 
   276 fun add_ind_realizer rsets intrs induct raw_induct elims vs thy =
   277   let
   278     val qualifier = Long_Name.qualifier (name_of_thm induct);
   279     val inducts = Global_Theory.get_thms thy (Long_Name.qualify qualifier "inducts");
   280     val iTs = rev (Term.add_tvars (prop_of (hd intrs)) []);
   281     val ar = length vs + length iTs;
   282     val params = Inductive.params_of raw_induct;
   283     val arities = Inductive.arities_of raw_induct;
   284     val nparms = length params;
   285     val params' = map dest_Var params;
   286     val rss = Inductive.partition_rules raw_induct intrs;
   287     val rss' = map (fn (((s, rs), (_, arity)), elim) =>
   288       (s, (Inductive.infer_intro_vars elim arity rs ~~ rs)))
   289         (rss ~~ arities ~~ elims);
   290     val (prfx, _) = split_last (Long_Name.explode (fst (hd rss)));
   291     val tnames = map (fn s => space_implode "_" (s ^ "T" :: vs)) rsets;
   292 
   293     val thy1 = thy |>
   294       Sign.root_path |>
   295       Sign.add_path (Long_Name.implode prfx);
   296     val (ty_eqs, rlz_eqs) = split_list
   297       (map (fn (s, rs) => mk_realizes_eqn (not (member (op =) rsets s)) vs nparms rs) rss);
   298 
   299     val thy1' = thy1 |>
   300       Sign.add_types_global
   301         (map (fn s => (Binding.name (Long_Name.base_name s), ar, NoSyn)) tnames) |>
   302       Extraction.add_typeof_eqns_i ty_eqs;
   303     val dts = map_filter (fn (s, rs) => if member (op =) rsets s 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, some_dt_names), thy2) =
   309       thy1
   310       |> add_dummies (Old_Datatype.add_datatype {strict = false, quiet = false})
   311         (map (pair false) dts) []
   312       ||> Extraction.add_typeof_eqns_i ty_eqs
   313       ||> Extraction.add_realizes_eqns_i rlz_eqs;
   314     val dt_names = these some_dt_names;
   315     val case_thms = map (#case_rewrites o Old_Datatype_Data.the_info thy2) dt_names;
   316     val rec_thms =
   317       if null dt_names then []
   318       else #rec_rewrites (Old_Datatype_Data.the_info thy2 (hd dt_names));
   319     val rec_names = distinct (op =) (map (fst o dest_Const o head_of o fst o
   320       HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) rec_thms);
   321     val (constrss, _) = fold_map (fn (s, rs) => fn (recs, dummies) =>
   322       if member (op =) rsets s then
   323         let
   324           val (d :: dummies') = dummies;
   325           val (recs1, recs2) = chop (length rs) (if d then tl recs else recs)
   326         in (map (head_of o hd o rev o snd o strip_comb o fst o
   327           HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) recs1, (recs2, dummies'))
   328         end
   329       else (replicate (length rs) Extraction.nullt, (recs, dummies)))
   330         rss (rec_thms, dummies);
   331     val rintrs = map (fn (intr, c) => attach_typeS (Envir.eta_contract
   332       (Extraction.realizes_of thy2 vs
   333         (if c = Extraction.nullt then c else list_comb (c, map Var (rev
   334           (subtract (op =) params' (Term.add_vars (prop_of intr) []))))) (prop_of intr))))
   335             (maps snd rss ~~ flat constrss);
   336     val (rlzpreds, rlzpreds') =
   337       rintrs |> map (fn rintr =>
   338         let
   339           val Const (s, T) = head_of (HOLogic.dest_Trueprop (Logic.strip_assums_concl rintr));
   340           val s' = Long_Name.base_name s;
   341           val T' = Logic.unvarifyT_global T;
   342         in (((s', T'), NoSyn), (Const (s, T'), Free (s', T'))) end)
   343       |> distinct (op = o pairself (#1 o #1))
   344       |> map (apfst (apfst (apfst Binding.name)))
   345       |> split_list;
   346 
   347     val rlzparams = map (fn Var ((s, _), T) => (s, Logic.unvarifyT_global T))
   348       (List.take (snd (strip_comb
   349         (HOLogic.dest_Trueprop (Logic.strip_assums_concl (hd rintrs)))), nparms));
   350 
   351     (** realizability predicate **)
   352 
   353     val (ind_info, thy3') = thy2 |>
   354       Inductive.add_inductive_global
   355         {quiet_mode = false, verbose = false, alt_name = Binding.empty, coind = false,
   356           no_elim = false, no_ind = false, skip_mono = false}
   357         rlzpreds rlzparams (map (fn (rintr, intr) =>
   358           ((Binding.name (Long_Name.base_name (name_of_thm intr)), []),
   359            subst_atomic rlzpreds' (Logic.unvarify_global rintr)))
   360              (rintrs ~~ maps snd rss)) [] ||>
   361       Sign.root_path;
   362     val thy3 = fold (Global_Theory.hide_fact false o name_of_thm) (#intrs ind_info) thy3';
   363 
   364     (** realizer for induction rule **)
   365 
   366     val Ps = map_filter (fn _ $ M $ P => if member (op =) rsets (pred_of M) then
   367       SOME (fst (fst (dest_Var (head_of P)))) else NONE)
   368         (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of raw_induct)));
   369 
   370     fun add_ind_realizer Ps thy =
   371       let
   372         val vs' = rename (map (pairself (fst o fst o dest_Var))
   373           (params ~~ List.take (snd (strip_comb (HOLogic.dest_Trueprop
   374             (hd (prems_of (hd inducts))))), nparms))) vs;
   375         val rs = indrule_realizer thy induct raw_induct rsets params'
   376           (vs' @ Ps) rec_names rss' intrs dummies;
   377         val rlzs = map (fn (r, ind) => Extraction.realizes_of thy (vs' @ Ps) r
   378           (prop_of ind)) (rs ~~ inducts);
   379         val used = fold Term.add_free_names rlzs [];
   380         val rnames = Name.variant_list used (replicate (length inducts) "r");
   381         val rnames' = Name.variant_list
   382           (used @ rnames) (replicate (length intrs) "s");
   383         val rlzs' as (prems, _, _) :: _ = map (fn (rlz, name) =>
   384           let
   385             val (P, Q) = strip_one name (Logic.unvarify_global rlz);
   386             val Q' = strip_all' [] rnames' Q
   387           in
   388             (Logic.strip_imp_prems Q', P, Logic.strip_imp_concl Q')
   389           end) (rlzs ~~ rnames);
   390         val concl = HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj (map
   391           (fn (_, _ $ P, _ $ Q) => HOLogic.mk_imp (P, Q)) rlzs'));
   392         val rews = map mk_meta_eq (@{thm fst_conv} :: @{thm snd_conv} :: rec_thms);
   393         val thm = Goal.prove_global thy []
   394           (map attach_typeS prems) (attach_typeS concl)
   395           (fn {context = ctxt, prems} => EVERY
   396           [rtac (#raw_induct ind_info) 1,
   397            rewrite_goals_tac ctxt rews,
   398            REPEAT ((resolve_tac prems THEN_ALL_NEW EVERY'
   399              [K (rewrite_goals_tac ctxt rews), Object_Logic.atomize_prems_tac ctxt,
   400               DEPTH_SOLVE_1 o FIRST' [atac, etac allE, etac impE]]) 1)]);
   401         val (thm', thy') = Global_Theory.store_thm (Binding.qualified_name (space_implode "_"
   402           (Long_Name.qualify qualifier "induct" :: vs' @ Ps @ ["correctness"])), thm) thy;
   403         val thms = map (fn th => zero_var_indexes (rotate_prems ~1 (th RS mp)))
   404           (Old_Datatype_Aux.split_conj_thm thm');
   405         val ([thms'], thy'') = Global_Theory.add_thmss
   406           [((Binding.qualified_name (space_implode "_"
   407              (Long_Name.qualify qualifier "inducts" :: vs' @ Ps @
   408                ["correctness"])), thms), [])] thy';
   409         val realizers = inducts ~~ thms' ~~ rlzs ~~ rs;
   410       in
   411         Extraction.add_realizers_i
   412           (map (fn (((ind, corr), rlz), r) =>
   413               mk_realizer thy'' (vs' @ Ps) (Thm.derivation_name ind, ind, corr, rlz, r))
   414             realizers @ (case realizers of
   415              [(((ind, corr), rlz), r)] =>
   416                [mk_realizer thy'' (vs' @ Ps) (Long_Name.qualify qualifier "induct",
   417                   ind, corr, rlz, r)]
   418            | _ => [])) thy''
   419       end;
   420 
   421     (** realizer for elimination rules **)
   422 
   423     val case_names = map (fst o dest_Const o head_of o fst o HOLogic.dest_eq o
   424       HOLogic.dest_Trueprop o prop_of o hd) case_thms;
   425 
   426     fun add_elim_realizer Ps
   427       (((((elim, elimR), intrs), case_thms), case_name), dummy) thy =
   428       let
   429         val (prem :: prems) = prems_of elim;
   430         fun reorder1 (p, (_, intr)) =
   431           fold (fn ((s, _), T) => Logic.all (Free (s, T)))
   432             (subtract (op =) params' (Term.add_vars (prop_of intr) []))
   433             (strip_all p);
   434         fun reorder2 ((ivs, intr), i) =
   435           let val fs = subtract (op =) params' (Term.add_vars (prop_of intr) [])
   436           in fold (lambda o Var) fs (list_comb (Bound (i + length ivs), ivs)) end;
   437         val p = Logic.list_implies
   438           (map reorder1 (prems ~~ intrs) @ [prem], concl_of elim);
   439         val T' = Extraction.etype_of thy (vs @ Ps) [] p;
   440         val T = if dummy then (HOLogic.unitT --> body_type T') --> T' else T';
   441         val Ts = map (Extraction.etype_of thy (vs @ Ps) []) (prems_of elim);
   442         val r =
   443           if null Ps then Extraction.nullt
   444           else
   445             fold_rev (Term.abs o pair "x") Ts
   446               (list_comb (Const (case_name, T),
   447                 (if dummy then
   448                    [Abs ("x", HOLogic.unitT, Const (@{const_name default}, body_type T))]
   449                  else []) @
   450                 map reorder2 (intrs ~~ (length prems - 1 downto 0)) @
   451                 [Bound (length prems)]));
   452         val rlz = Extraction.realizes_of thy (vs @ Ps) r (prop_of elim);
   453         val rlz' = attach_typeS (strip_all (Logic.unvarify_global rlz));
   454         val rews = map mk_meta_eq case_thms;
   455         val thm = Goal.prove_global thy []
   456           (Logic.strip_imp_prems rlz') (Logic.strip_imp_concl rlz')
   457           (fn {context = ctxt, prems, ...} => EVERY
   458             [cut_tac (hd prems) 1,
   459              etac elimR 1,
   460              ALLGOALS (asm_simp_tac (put_simpset HOL_basic_ss ctxt)),
   461              rewrite_goals_tac ctxt rews,
   462              REPEAT ((resolve_tac prems THEN_ALL_NEW (Object_Logic.atomize_prems_tac ctxt THEN'
   463                DEPTH_SOLVE_1 o FIRST' [atac, etac allE, etac impE])) 1)]);
   464         val (thm', thy') = Global_Theory.store_thm (Binding.qualified_name (space_implode "_"
   465           (name_of_thm elim :: vs @ Ps @ ["correctness"])), thm) thy
   466       in
   467         Extraction.add_realizers_i
   468           [mk_realizer thy' (vs @ Ps) (name_of_thm elim, elim, thm', rlz, r)] thy'
   469       end;
   470 
   471     (** add realizers to theory **)
   472 
   473     val thy4 = fold add_ind_realizer (subsets Ps) thy3;
   474     val thy5 = Extraction.add_realizers_i
   475       (map (mk_realizer thy4 vs) (map (fn (((rule, rrule), rlz), c) =>
   476          (name_of_thm rule, rule, rrule, rlz,
   477             list_comb (c, map Var (subtract (op =) params' (rev (Term.add_vars (prop_of rule) []))))))
   478               (maps snd rss ~~ #intrs ind_info ~~ rintrs ~~ flat constrss))) thy4;
   479     val elimps = map_filter (fn ((s, intrs), p) =>
   480       if member (op =) rsets s then SOME (p, intrs) else NONE)
   481         (rss' ~~ (elims ~~ #elims ind_info));
   482     val thy6 =
   483       fold (fn p as (((((elim, _), _), _), _), _) =>
   484         add_elim_realizer [] p #>
   485         add_elim_realizer [fst (fst (dest_Var (HOLogic.dest_Trueprop (concl_of elim))))] p)
   486       (elimps ~~ case_thms ~~ case_names ~~ dummies) thy5;
   487 
   488   in Sign.restore_naming thy thy6 end;
   489 
   490 fun add_ind_realizers name rsets thy =
   491   let
   492     val (_, {intrs, induct, raw_induct, elims, ...}) =
   493       Inductive.the_inductive (Proof_Context.init_global thy) name;
   494     val vss = sort (int_ord o pairself length)
   495       (subsets (map fst (relevant_vars (concl_of (hd intrs)))))
   496   in
   497     fold_rev (add_ind_realizer rsets intrs induct raw_induct elims) vss thy
   498   end
   499 
   500 fun rlz_attrib arg = Thm.declaration_attribute (fn thm => Context.mapping
   501   let
   502     fun err () = error "ind_realizer: bad rule";
   503     val sets =
   504       (case HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of thm)) of
   505            [_] => [pred_of (HOLogic.dest_Trueprop (hd (prems_of thm)))]
   506          | xs => map (pred_of o fst o HOLogic.dest_imp) xs)
   507          handle TERM _ => err () | List.Empty => err ();
   508   in 
   509     add_ind_realizers (hd sets)
   510       (case arg of
   511         NONE => sets | SOME NONE => []
   512       | SOME (SOME sets') => subtract (op =) sets' sets)
   513   end I);
   514 
   515 val _ = Theory.setup (Attrib.setup @{binding ind_realizer}
   516   ((Scan.option (Scan.lift (Args.$$$ "irrelevant") |--
   517     Scan.option (Scan.lift (Args.colon) |--
   518       Scan.repeat1 (Args.const {proper = true, strict = true})))) >> rlz_attrib)
   519   "add realizers for inductive set");
   520 
   521 end;