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