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