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