src/HOL/Tools/inductive_realizer.ML
author wenzelm
Tue Dec 13 23:23:51 2011 +0100 (2011-12-13)
changeset 45839 43a5b86bc102
parent 45701 615da8b8d758
child 46219 426ed18eba43
permissions -rw-r--r--
'datatype' specifications allow explicit sort constraints;
tuned signatures;
     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
    73     ((tname, map (rpair dummyS) (map (fn a => "'" ^ a) vs @ map (fst o fst) iTs), NoSyn),
    74       map constr_of_intr intrs)
    75   end;
    76 
    77 fun mk_rlz T = Const ("realizes", [T, HOLogic.boolT] ---> HOLogic.boolT);
    78 
    79 (** turn "P" into "%r x. realizes r (P x)" **)
    80 
    81 fun gen_rvar vs (t as Var ((a, 0), T)) =
    82       if body_type T <> HOLogic.boolT then t else
    83         let
    84           val U = TVar (("'" ^ a, 0), [])
    85           val Ts = binder_types T;
    86           val i = length Ts;
    87           val xs = map (pair "x") Ts;
    88           val u = list_comb (t, map Bound (i - 1 downto 0))
    89         in 
    90           if member (op =) vs a then
    91             list_abs (("r", U) :: xs, mk_rlz U $ Bound i $ u)
    92           else list_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 ("all", _) $ Abs (s, _, P)) = is_meta P
   149       | is_meta (Const ("==>", _) $ _ $ 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 if U = Extraction.nullT
   168                   then fun_of (Free (x, T) :: ts)
   169                     (Free (r, binder_types T ---> HOLogic.unitT) :: rts)
   170                     (Free (x, T) :: args) (x :: r :: used) prems'
   171                   else fun_of (Free (x, T) :: ts) (Free (r, U) :: rts)
   172                     (Free (r, U) :: Free (x, T) :: args) (x :: r :: used) prems'
   173                 end
   174               else (case strip_type T of
   175                   (Ts, Type (@{type_name Product_Type.prod}, [T1, T2])) =>
   176                     let
   177                       val fx = Free (x, Ts ---> T1);
   178                       val fr = Free (r, Ts ---> T2);
   179                       val bs = map Bound (length Ts - 1 downto 0);
   180                       val t = list_abs (map (pair "z") Ts,
   181                         HOLogic.mk_prod (list_comb (fx, bs), list_comb (fr, bs)))
   182                     in fun_of (fx :: ts) (fr :: rts) (t::args)
   183                       (x :: r :: used) prems
   184                     end
   185                 | (Ts, U) => fun_of (Free (x, T) :: ts)
   186                     (Free (r, binder_types T ---> HOLogic.unitT) :: rts)
   187                     (Free (x, T) :: args) (x :: r :: used) prems)
   188             else fun_of (Free (x, T) :: ts) rts (Free (x, T) :: args)
   189               (x :: used) prems
   190           end
   191       | fun_of ts rts args used [] =
   192           let val xs = rev (rts @ ts)
   193           in if conclT = Extraction.nullT
   194             then fold_rev (absfree o dest_Free) xs HOLogic.unit
   195             else fold_rev (absfree o dest_Free) xs
   196               (list_comb
   197                 (Free ("r" ^ Long_Name.base_name (name_of_thm intr),
   198                   map fastype_of (rev args) ---> conclT), rev args))
   199           end
   200 
   201   in fun_of args' [] (rev args) used (Logic.strip_imp_prems rule') end;
   202 
   203 fun indrule_realizer thy induct raw_induct rsets params vs rec_names rss intrs dummies =
   204   let
   205     val concls = HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of raw_induct));
   206     val premss = map_filter (fn (s, rs) => if member (op =) rsets s then
   207       SOME (rs, map (fn (_, r) => nth (prems_of raw_induct)
   208         (find_index (fn prp => prp = prop_of r) (map prop_of intrs))) rs) else NONE) rss;
   209     val fs = maps (fn ((intrs, prems), dummy) =>
   210       let
   211         val fs = map (fn (rule, (ivs, intr)) =>
   212           fun_of_prem thy rsets vs params rule ivs intr) (prems ~~ intrs)
   213       in
   214         if dummy then Const (@{const_name 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" ^ Long_Name.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
   229           (fold_rev absfree (("x", U) :: map_filter (fn intr =>
   230             Option.map (pair (name_of_fn intr))
   231               (AList.lookup (op =) frees (name_of_fn intr))) intrs)
   232             (list_comb (Const (a, Ts ---> T), fs) $ Free ("x", U)), names')
   233         end
   234       end) concls rec_names)
   235   end;
   236 
   237 fun add_dummy name dname (x as (_, ((s, vs, mx), cs))) =
   238   if Binding.eq_name (name, s)
   239   then (true, ((s, vs, mx), (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 = singleton (Name.variant_list 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, _), _) => member (op =) rvs a) 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 rs (prop_of rrule)
   266   in (name, (vs,
   267     if rt = Extraction.nullt then rt else fold_rev lambda vs1 rt,
   268     Extraction.abs_corr_shyps thy rule vs vs2
   269       (ProofRewriteRules.un_hhf_proof rlz' (attach_typeS rlz)
   270          (fold_rev Proofterm.forall_intr_proof' 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 = Global_Theory.get_thms thy (Long_Name.qualify qualifier "inducts");
   279     val iTs = rev (Term.add_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 (member (op =) rsets s)) vs nparms rs) rss);
   297 
   298     val thy1' = thy1 |>
   299       Theory.copy |>
   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 (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 Datatype.the_info thy2) dt_names;
   316     val rec_thms =
   317       if null dt_names then []
   318       else #rec_rewrites (Datatype.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, fork_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 {prems, ...} => EVERY
   396           [rtac (#raw_induct ind_info) 1,
   397            rewrite_goals_tac rews,
   398            REPEAT ((resolve_tac prems THEN_ALL_NEW EVERY'
   399              [K (rewrite_goals_tac rews), Object_Logic.atomize_prems_tac,
   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           (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 = if null Ps then Extraction.nullt
   443           else list_abs (map (pair "x") Ts, list_comb (Const (case_name, T),
   444             (if dummy then
   445                [Abs ("x", HOLogic.unitT, Const (@{const_name default}, body_type T))]
   446              else []) @
   447             map reorder2 (intrs ~~ (length prems - 1 downto 0)) @
   448             [Bound (length prems)]));
   449         val rlz = Extraction.realizes_of thy (vs @ Ps) r (prop_of elim);
   450         val rlz' = attach_typeS (strip_all (Logic.unvarify_global rlz));
   451         val rews = map mk_meta_eq case_thms;
   452         val thm = Goal.prove_global thy []
   453           (Logic.strip_imp_prems rlz') (Logic.strip_imp_concl rlz') (fn {prems, ...} => EVERY
   454           [cut_facts_tac [hd prems] 1,
   455            etac elimR 1,
   456            ALLGOALS (asm_simp_tac HOL_basic_ss),
   457            rewrite_goals_tac rews,
   458            REPEAT ((resolve_tac prems THEN_ALL_NEW (Object_Logic.atomize_prems_tac THEN'
   459              DEPTH_SOLVE_1 o FIRST' [atac, etac allE, etac impE])) 1)]);
   460         val (thm', thy') = Global_Theory.store_thm (Binding.qualified_name (space_implode "_"
   461           (name_of_thm elim :: vs @ Ps @ ["correctness"])), thm) thy
   462       in
   463         Extraction.add_realizers_i
   464           [mk_realizer thy' (vs @ Ps) (name_of_thm elim, elim, thm', rlz, r)] thy'
   465       end;
   466 
   467     (** add realizers to theory **)
   468 
   469     val thy4 = fold add_ind_realizer (subsets Ps) thy3;
   470     val thy5 = Extraction.add_realizers_i
   471       (map (mk_realizer thy4 vs) (map (fn (((rule, rrule), rlz), c) =>
   472          (name_of_thm rule, rule, rrule, rlz,
   473             list_comb (c, map Var (subtract (op =) params' (rev (Term.add_vars (prop_of rule) []))))))
   474               (maps snd rss ~~ #intrs ind_info ~~ rintrs ~~ flat constrss))) thy4;
   475     val elimps = map_filter (fn ((s, intrs), p) =>
   476       if member (op =) rsets s then SOME (p, intrs) else NONE)
   477         (rss' ~~ (elims ~~ #elims ind_info));
   478     val thy6 =
   479       fold (fn p as (((((elim, _), _), _), _), _) =>
   480         add_elim_realizer [] p #>
   481         add_elim_realizer [fst (fst (dest_Var (HOLogic.dest_Trueprop (concl_of elim))))] p)
   482       (elimps ~~ case_thms ~~ case_names ~~ dummies) thy5;
   483 
   484   in Sign.restore_naming thy thy6 end;
   485 
   486 fun add_ind_realizers name rsets thy =
   487   let
   488     val (_, {intrs, induct, raw_induct, elims, ...}) =
   489       Inductive.the_inductive (Proof_Context.init_global thy) name;
   490     val vss = sort (int_ord o pairself length)
   491       (subsets (map fst (relevant_vars (concl_of (hd intrs)))))
   492   in
   493     fold_rev (add_ind_realizer rsets intrs induct raw_induct elims) vss thy
   494   end
   495 
   496 fun rlz_attrib arg = Thm.declaration_attribute (fn thm => Context.mapping
   497   let
   498     fun err () = error "ind_realizer: bad rule";
   499     val sets =
   500       (case HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of thm)) of
   501            [_] => [pred_of (HOLogic.dest_Trueprop (hd (prems_of thm)))]
   502          | xs => map (pred_of o fst o HOLogic.dest_imp) xs)
   503          handle TERM _ => err () | Empty => err ();
   504   in 
   505     add_ind_realizers (hd sets)
   506       (case arg of
   507         NONE => sets | SOME NONE => []
   508       | SOME (SOME sets') => subtract (op =) sets' sets)
   509   end I);
   510 
   511 val setup =
   512   Attrib.setup @{binding ind_realizer}
   513     ((Scan.option (Scan.lift (Args.$$$ "irrelevant") |--
   514       Scan.option (Scan.lift (Args.colon) |-- Scan.repeat1 (Args.const true)))) >> rlz_attrib)
   515     "add realizers for inductive set";
   516 
   517 end;
   518