src/HOL/Tools/BNF/bnf_fp_n2m.ML
author blanchet
Mon Mar 03 12:48:20 2014 +0100 (2014-03-03)
changeset 55854 ee270328a781
parent 55819 e21d83c8e1c7
child 55868 37b99986d435
permissions -rw-r--r--
make 'typedef' optional, depending on size of original type
blanchet@55061
     1
(*  Title:      HOL/Tools/BNF/bnf_fp_n2m.ML
blanchet@53303
     2
    Author:     Dmitriy Traytel, TU Muenchen
blanchet@53303
     3
    Copyright   2013
blanchet@53303
     4
blanchet@53303
     5
Flattening of nested to mutual (co)recursion.
blanchet@53303
     6
*)
blanchet@53303
     7
blanchet@53303
     8
signature BNF_FP_N2M =
blanchet@53303
     9
sig
blanchet@55575
    10
  val construct_mutualized_fp: BNF_Util.fp_kind -> typ list -> BNF_FP_Def_Sugar.fp_sugar list ->
blanchet@53303
    11
    binding list -> (string * sort) list -> typ list * typ list list -> BNF_Def.bnf list ->
traytel@55803
    12
    BNF_Comp.absT_info list -> local_theory -> BNF_FP_Util.fp_result * local_theory
blanchet@53303
    13
end;
blanchet@53303
    14
blanchet@53303
    15
structure BNF_FP_N2M : BNF_FP_N2M =
blanchet@53303
    16
struct
blanchet@53303
    17
blanchet@53303
    18
open BNF_Def
blanchet@53303
    19
open BNF_Util
traytel@55803
    20
open BNF_Comp
blanchet@53303
    21
open BNF_FP_Util
blanchet@53303
    22
open BNF_FP_Def_Sugar
blanchet@53303
    23
open BNF_Tactics
blanchet@53303
    24
open BNF_FP_N2M_Tactics
blanchet@53303
    25
blanchet@53303
    26
fun force_typ ctxt T =
blanchet@54233
    27
  map_types Type_Infer.paramify_vars
blanchet@53303
    28
  #> Type.constraint T
blanchet@53303
    29
  #> Syntax.check_term ctxt
blanchet@53303
    30
  #> singleton (Variable.polymorphic ctxt);
blanchet@53303
    31
blanchet@53303
    32
fun mk_prod_map f g =
blanchet@53303
    33
  let
blanchet@53303
    34
    val ((fAT, fBT), fT) = `dest_funT (fastype_of f);
blanchet@53303
    35
    val ((gAT, gBT), gT) = `dest_funT (fastype_of g);
blanchet@53303
    36
  in
blanchet@53303
    37
    Const (@{const_name map_pair},
blanchet@53303
    38
      fT --> gT --> HOLogic.mk_prodT (fAT, gAT) --> HOLogic.mk_prodT (fBT, gBT)) $ f $ g
blanchet@53303
    39
  end;
blanchet@53303
    40
blanchet@53303
    41
fun mk_sum_map f g =
blanchet@53303
    42
  let
blanchet@53303
    43
    val ((fAT, fBT), fT) = `dest_funT (fastype_of f);
blanchet@53303
    44
    val ((gAT, gBT), gT) = `dest_funT (fastype_of g);
blanchet@53303
    45
  in
blanchet@53303
    46
    Const (@{const_name sum_map}, fT --> gT --> mk_sumT (fAT, gAT) --> mk_sumT (fBT, gBT)) $ f $ g
blanchet@53303
    47
  end;
blanchet@53303
    48
traytel@55803
    49
fun construct_mutualized_fp fp fpTs (fp_sugars : fp_sugar list) bs resBs (resDs, Dss) bnfs
traytel@55819
    50
    (absT_infos : absT_info list) lthy =
blanchet@53303
    51
  let
traytel@55803
    52
    fun of_fp_res get =
blanchet@55539
    53
      map (fn {fp_res, fp_res_index, ...} => nth (get fp_res) fp_res_index) fp_sugars;
blanchet@53303
    54
blanchet@53303
    55
    fun mk_co_algT T U = fp_case fp (T --> U) (U --> T);
blanchet@53303
    56
    fun co_swap pair = fp_case fp I swap pair;
traytel@55803
    57
    val mk_co_comp = HOLogic.mk_comp o co_swap;
traytel@55803
    58
blanchet@53303
    59
    val dest_co_algT = co_swap o dest_funT;
blanchet@53303
    60
    val co_alg_argT = fp_case fp range_type domain_type;
blanchet@53303
    61
    val co_alg_funT = fp_case fp domain_type range_type;
blanchet@55414
    62
    val mk_co_product = curry (fp_case fp mk_convol mk_case_sum);
blanchet@53303
    63
    val mk_map_co_product = fp_case fp mk_prod_map mk_sum_map;
blanchet@53303
    64
    val co_proj1_const = fp_case fp (fst_const o fst) (uncurry Inl_const o dest_sumT o snd);
blanchet@53303
    65
    val mk_co_productT = curry (fp_case fp HOLogic.mk_prodT mk_sumT);
blanchet@53303
    66
    val dest_co_productT = fp_case fp HOLogic.dest_prodT dest_sumT;
traytel@55803
    67
    val rewrite_comp_comp = fp_case fp @{thm rewriteL_comp_comp} @{thm rewriteR_comp_comp};
traytel@55803
    68
traytel@55803
    69
    val fp_absT_infos = map #absT_info fp_sugars;
traytel@55803
    70
    val fp_bnfs = of_fp_res #bnfs;
traytel@55803
    71
    val pre_bnfs = map #pre_bnf fp_sugars;
traytel@55803
    72
    val nesty_bnfss = map (fn sugar => #nested_bnfs sugar @ #nesting_bnfs sugar) fp_sugars;
traytel@55803
    73
    val fp_nesty_bnfss = fp_bnfs :: nesty_bnfss;
traytel@55803
    74
    val fp_nesty_bnfs = distinct (op = o pairself T_of_bnf) (flat fp_nesty_bnfss);
traytel@55803
    75
traytel@55803
    76
    val fp_absTs = map #absT fp_absT_infos;
traytel@55803
    77
    val fp_repTs = map #repT fp_absT_infos;
traytel@55803
    78
    val fp_abss = map #abs fp_absT_infos;
traytel@55803
    79
    val fp_reps = map #rep fp_absT_infos;
traytel@55803
    80
    val fp_type_definitions = map #type_definition fp_absT_infos;
traytel@55803
    81
traytel@55803
    82
    val absTs = map #absT absT_infos;
traytel@55803
    83
    val repTs = map #repT absT_infos;
traytel@55803
    84
    val absTs' = map (Logic.type_map (singleton (Variable.polymorphic lthy))) absTs;
traytel@55803
    85
    val repTs' = map (Logic.type_map (singleton (Variable.polymorphic lthy))) repTs;
traytel@55803
    86
    val abss = map #abs absT_infos;
traytel@55803
    87
    val reps = map #rep absT_infos;
traytel@55803
    88
    val abs_inverses = map #abs_inverse absT_infos;
traytel@55803
    89
    val type_definitions = map #type_definition absT_infos;
traytel@55803
    90
traytel@55803
    91
    val n = length bnfs;
traytel@55803
    92
    val deads = fold (union (op =)) Dss resDs;
traytel@55803
    93
    val As = subtract (op =) deads (map TFree resBs);
traytel@55803
    94
    val names_lthy = fold Variable.declare_typ (As @ deads) lthy;
traytel@55803
    95
    val m = length As;
traytel@55803
    96
    val live = m + n;
traytel@55803
    97
traytel@55803
    98
    val ((Xs, Bs), names_lthy) = names_lthy
traytel@55803
    99
      |> mk_TFrees n
traytel@55803
   100
      ||>> mk_TFrees m;
traytel@55803
   101
traytel@55803
   102
    val allAs = As @ Xs;
traytel@55803
   103
    val allBs = Bs @ Xs;
traytel@55803
   104
    val phiTs = map2 mk_pred2T As Bs;
traytel@55803
   105
    val thetaBs = As ~~ Bs;
traytel@55803
   106
    val fpTs' = map (Term.typ_subst_atomic thetaBs) fpTs;
traytel@55803
   107
    val fold_thetaAs = Xs ~~ fpTs;
traytel@55803
   108
    val fold_thetaBs = Xs ~~ fpTs';
traytel@55803
   109
    val rec_theta = Xs ~~ map2 mk_co_productT fpTs Xs;
traytel@55803
   110
    val pre_phiTs = map2 mk_pred2T fpTs fpTs';
blanchet@53303
   111
blanchet@53303
   112
    val ((ctors, dtors), (xtor's, xtors)) =
blanchet@53303
   113
      let
traytel@55803
   114
        val ctors = map2 (force_typ names_lthy o (fn T => dummyT --> T)) fpTs (of_fp_res #ctors);
traytel@55803
   115
        val dtors = map2 (force_typ names_lthy o (fn T => T --> dummyT)) fpTs (of_fp_res #dtors);
blanchet@53303
   116
      in
traytel@55803
   117
        ((ctors, dtors), `(map (Term.subst_atomic_types thetaBs)) (fp_case fp ctors dtors))
blanchet@53303
   118
      end;
blanchet@53303
   119
traytel@55803
   120
    val absATs = map (domain_type o fastype_of) ctors;
traytel@55803
   121
    val absBTs = map (Term.typ_subst_atomic thetaBs) absATs;
blanchet@53303
   122
    val xTs = map (domain_type o fastype_of) xtors;
blanchet@53303
   123
    val yTs = map (domain_type o fastype_of) xtor's;
blanchet@53303
   124
traytel@55819
   125
    val absAs = map3 (fn Ds => mk_abs o mk_T_of_bnf Ds allAs) Dss bnfs abss;
traytel@55819
   126
    val absBs = map3 (fn Ds => mk_abs o mk_T_of_bnf Ds allBs) Dss bnfs abss;
traytel@55819
   127
    val fp_repAs = map2 mk_rep absATs fp_reps;
traytel@55819
   128
    val fp_repBs = map2 mk_rep absBTs fp_reps;
traytel@55803
   129
blanchet@53303
   130
    val (((((phis, phis'), pre_phis), xs), ys), names_lthy) = names_lthy
blanchet@53303
   131
      |> mk_Frees' "R" phiTs
blanchet@53303
   132
      ||>> mk_Frees "S" pre_phiTs
blanchet@53303
   133
      ||>> mk_Frees "x" xTs
blanchet@53303
   134
      ||>> mk_Frees "y" yTs;
blanchet@53303
   135
blanchet@53303
   136
    val rels =
blanchet@53303
   137
      let
blanchet@53303
   138
        fun find_rel T As Bs = fp_nesty_bnfss
blanchet@55394
   139
          |> map (filter_out (curry (op = o pairself name_of_bnf) BNF_Comp.DEADID_bnf))
blanchet@53303
   140
          |> get_first (find_first (fn bnf => Type.could_unify (T_of_bnf bnf, T)))
blanchet@53303
   141
          |> Option.map (fn bnf =>
blanchet@53303
   142
            let val live = live_of_bnf bnf;
blanchet@53303
   143
            in (mk_rel live As Bs (rel_of_bnf bnf), live) end)
blanchet@53303
   144
          |> the_default (HOLogic.eq_const T, 0);
blanchet@53303
   145
blanchet@53303
   146
        fun mk_rel (T as Type (_, Ts)) (Type (_, Us)) =
blanchet@53303
   147
              let
blanchet@53303
   148
                val (rel, live) = find_rel T Ts Us;
blanchet@53303
   149
                val (Ts', Us') = fastype_of rel |> strip_typeN live |> fst |> map_split dest_pred2T;
blanchet@53303
   150
                val rels = map2 mk_rel Ts' Us';
blanchet@53303
   151
              in
blanchet@53303
   152
                Term.list_comb (rel, rels)
blanchet@53303
   153
              end
traytel@54244
   154
          | mk_rel (T as TFree _) _ = (nth phis (find_index (curry op = T) As)
traytel@54244
   155
              handle General.Subscript => HOLogic.eq_const T)
blanchet@53303
   156
          | mk_rel _ _ = raise Fail "fpTs contains schematic type variables";
blanchet@53303
   157
      in
traytel@54298
   158
        map2 (fold_rev Term.absfree phis' oo mk_rel) fpTs fpTs'
blanchet@53303
   159
      end;
blanchet@53303
   160
blanchet@53303
   161
    val pre_rels = map2 (fn Ds => mk_rel_of_bnf Ds (As @ fpTs) (Bs @ fpTs')) Dss bnfs;
blanchet@53303
   162
blanchet@55539
   163
    val rel_unfolds = maps (no_refl o single o rel_def_of_bnf) pre_bnfs;
traytel@55803
   164
    val rel_xtor_co_inducts = of_fp_res (split_conj_thm o #rel_xtor_co_induct_thm)
blanchet@55539
   165
      |> map (unfold_thms lthy (id_apply :: rel_unfolds));
blanchet@53303
   166
blanchet@53303
   167
    val rel_defs = map rel_def_of_bnf bnfs;
blanchet@53303
   168
    val rel_monos = map rel_mono_of_bnf bnfs;
blanchet@53303
   169
traytel@55803
   170
    fun cast castA castB pre_rel =
traytel@55803
   171
      let
traytel@55803
   172
        val castAB = mk_vimage2p (Term.subst_atomic_types fold_thetaAs castA)
traytel@55803
   173
          (Term.subst_atomic_types fold_thetaBs castB);
traytel@55803
   174
      in
traytel@55803
   175
        fold_rev (fold_rev Term.absdummy) [phiTs, pre_phiTs]
traytel@55803
   176
          (castAB $ Term.list_comb (pre_rel, map Bound (live - 1 downto 0)))
traytel@55803
   177
      end;
traytel@55803
   178
traytel@55803
   179
    val castAs = map2 (curry HOLogic.mk_comp) absAs fp_repAs;
traytel@55803
   180
    val castBs = map2 (curry HOLogic.mk_comp) absBs fp_repBs;
traytel@55803
   181
blanchet@53303
   182
    val rel_xtor_co_induct_thm =
traytel@55803
   183
      mk_rel_xtor_co_induct_thm fp (map3 cast castAs castBs pre_rels) pre_phis rels phis xs ys xtors
traytel@55803
   184
        xtor's (mk_rel_xtor_co_induct_tactic fp abs_inverses rel_xtor_co_inducts rel_defs rel_monos)
traytel@55803
   185
        lthy;
blanchet@53303
   186
blanchet@53303
   187
    val rel_eqs = no_refl (map rel_eq_of_bnf fp_nesty_bnfs);
blanchet@53303
   188
    val map_id0s = no_refl (map map_id0_of_bnf bnfs);
blanchet@53303
   189
blanchet@53303
   190
    val xtor_co_induct_thm =
blanchet@53303
   191
      (case fp of
blanchet@53303
   192
        Least_FP =>
blanchet@53303
   193
          let
blanchet@53303
   194
            val (Ps, names_lthy) = names_lthy
blanchet@53303
   195
              |> mk_Frees "P" (map (fn T => T --> HOLogic.boolT) fpTs);
blanchet@53303
   196
            fun mk_Grp_id P =
blanchet@53303
   197
              let val T = domain_type (fastype_of P);
blanchet@53303
   198
              in mk_Grp (HOLogic.Collect_const T $ P) (HOLogic.id_const T) end;
blanchet@53303
   199
            val cts = map (SOME o certify lthy) (map HOLogic.eq_const As @ map mk_Grp_id Ps);
traytel@55803
   200
            fun mk_fp_type_copy_thms thm = map (curry op RS thm)
traytel@55803
   201
              @{thms type_copy_Abs_o_Rep type_copy_vimage2p_Grp_Rep};
traytel@55803
   202
            fun mk_type_copy_thms thm = map (curry op RS thm)
traytel@55803
   203
              @{thms type_copy_Rep_o_Abs type_copy_vimage2p_Grp_Abs};
blanchet@53303
   204
          in
blanchet@53303
   205
            cterm_instantiate_pos cts rel_xtor_co_induct_thm
blanchet@53303
   206
            |> singleton (Proof_Context.export names_lthy lthy)
blanchet@53303
   207
            |> unfold_thms lthy (@{thms eq_le_Grp_id_iff all_simps(1,2)[symmetric]} @ rel_eqs)
blanchet@53303
   208
            |> funpow n (fn thm => thm RS spec)
blanchet@53303
   209
            |> unfold_thms lthy (@{thm eq_alt} :: map rel_Grp_of_bnf bnfs @ map_id0s)
blanchet@55854
   210
            |> unfold_thms lthy (@{thms vimage2p_id vimage2p_comp comp_apply comp_id
traytel@55803
   211
               Grp_id_mono_subst eqTrueI[OF subset_UNIV] simp_thms(22)} @
traytel@55803
   212
               maps mk_fp_type_copy_thms fp_type_definitions @
traytel@55803
   213
               maps mk_type_copy_thms type_definitions)
blanchet@53303
   214
            |> unfold_thms lthy @{thms subset_iff mem_Collect_eq
blanchet@53303
   215
               atomize_conjL[symmetric] atomize_all[symmetric] atomize_imp[symmetric]}
blanchet@53303
   216
          end
blanchet@53303
   217
      | Greatest_FP =>
blanchet@53303
   218
          let
blanchet@53303
   219
            val cts = NONE :: map (SOME o certify lthy) (map HOLogic.eq_const As);
blanchet@53303
   220
          in
blanchet@53303
   221
            cterm_instantiate_pos cts rel_xtor_co_induct_thm
blanchet@53303
   222
            |> unfold_thms lthy (@{thms le_fun_def le_bool_def all_simps(1,2)[symmetric]} @ rel_eqs)
blanchet@53303
   223
            |> funpow (2 * n) (fn thm => thm RS spec)
wenzelm@54742
   224
            |> Conv.fconv_rule (Object_Logic.atomize lthy)
blanchet@53303
   225
            |> funpow n (fn thm => thm RS mp)
blanchet@53303
   226
          end);
blanchet@53303
   227
blanchet@53303
   228
    val fold_preTs = map2 (fn Ds => mk_T_of_bnf Ds allAs) Dss bnfs;
blanchet@53303
   229
    val rec_preTs = map (Term.typ_subst_atomic rec_theta) fold_preTs;
blanchet@53303
   230
blanchet@53303
   231
    val fold_strTs = map2 mk_co_algT fold_preTs Xs;
blanchet@53303
   232
    val rec_strTs = map2 mk_co_algT rec_preTs Xs;
blanchet@53303
   233
    val resTs = map2 mk_co_algT fpTs Xs;
blanchet@53303
   234
blanchet@53303
   235
    val (((fold_strs, fold_strs'), (rec_strs, rec_strs')), names_lthy) = names_lthy
blanchet@53303
   236
      |> mk_Frees' "s" fold_strTs
blanchet@53303
   237
      ||>> mk_Frees' "s" rec_strTs;
blanchet@53303
   238
traytel@55803
   239
    val co_iters = of_fp_res #xtor_co_iterss;
blanchet@55539
   240
    val ns = map (length o #Ts o #fp_res) fp_sugars;
blanchet@55539
   241
blanchet@53303
   242
    fun substT rho (Type (@{type_name "fun"}, [T, U])) = substT rho T --> substT rho U
blanchet@53303
   243
      | substT rho (Type (s, Ts)) = Type (s, map (typ_subst_nonatomic rho) Ts)
blanchet@53303
   244
      | substT _ T = T;
blanchet@55539
   245
traytel@55803
   246
    val typ_subst_nonatomic_sorted = fold_rev (typ_subst_nonatomic o single);
traytel@55803
   247
blanchet@53303
   248
    fun force_iter is_rec i TU TU_rec raw_iters =
blanchet@53303
   249
      let
traytel@55803
   250
        val thy = Proof_Context.theory_of lthy;
traytel@55803
   251
blanchet@53303
   252
        val approx_fold = un_fold_of raw_iters
blanchet@53303
   253
          |> force_typ names_lthy
blanchet@53303
   254
            (replicate (nth ns i) dummyT ---> (if is_rec then TU_rec else TU));
traytel@55803
   255
        val subst = Term.typ_subst_atomic fold_thetaAs;
traytel@55803
   256
traytel@55803
   257
        fun mk_fp_absT_repT fp_repT fp_absT = mk_absT thy fp_repT fp_absT ooo mk_repT;
traytel@55803
   258
        val mk_fp_absT_repTs = map5 mk_fp_absT_repT fp_repTs fp_absTs absTs repTs;
traytel@55803
   259
traytel@55803
   260
        val fold_preTs' = mk_fp_absT_repTs (map subst fold_preTs);
traytel@55803
   261
traytel@55803
   262
        val fold_pre_deads_only_Ts =
traytel@55803
   263
          map (typ_subst_nonatomic_sorted (map (rpair dummyT) (As @ fpTs))) fold_preTs';
traytel@55803
   264
traytel@55478
   265
        val TUs = map_split dest_co_algT (binder_fun_types (fastype_of approx_fold))
traytel@55478
   266
          |>> map subst
traytel@55478
   267
          |> uncurry (map2 mk_co_algT);
traytel@55803
   268
        val cands = map2 mk_co_algT fold_preTs' Xs;
traytel@55803
   269
traytel@55803
   270
        val js = find_indices Type.could_unify TUs cands;
blanchet@53303
   271
        val Tpats = map (fn j => mk_co_algT (nth fold_pre_deads_only_Ts j) (nth Xs j)) js;
blanchet@53303
   272
        val iter = raw_iters |> (if is_rec then co_rec_of else un_fold_of);
blanchet@53303
   273
      in
blanchet@53303
   274
        force_typ names_lthy (Tpats ---> TU) iter
blanchet@53303
   275
      end;
blanchet@53303
   276
traytel@55803
   277
    fun mk_co_comp_abs_rep fp_absT absT fp_abs fp_rep abs rep t =
traytel@55803
   278
      fp_case fp (HOLogic.mk_comp (HOLogic.mk_comp (t, mk_abs absT abs), mk_rep fp_absT fp_rep))
traytel@55803
   279
        (HOLogic.mk_comp (mk_abs fp_absT fp_abs, HOLogic.mk_comp (mk_rep absT rep, t)));
traytel@55803
   280
blanchet@53303
   281
    fun mk_iter b_opt is_rec iters lthy TU =
blanchet@53303
   282
      let
traytel@55803
   283
        val thy = Proof_Context.theory_of lthy;
traytel@55803
   284
blanchet@53303
   285
        val x = co_alg_argT TU;
blanchet@53303
   286
        val i = find_index (fn T => x = T) Xs;
blanchet@53303
   287
        val TUiter =
blanchet@53303
   288
          (case find_first (fn f => body_fun_type (fastype_of f) = TU) iters of
blanchet@53303
   289
            NONE => nth co_iters i
blanchet@53303
   290
              |> force_iter is_rec i
blanchet@53303
   291
                (TU |> (is_none b_opt andalso not is_rec) ? substT (fpTs ~~ Xs))
blanchet@53303
   292
                (TU |> (is_none b_opt) ? substT (map2 mk_co_productT fpTs Xs ~~ Xs))
blanchet@53303
   293
          | SOME f => f);
traytel@55803
   294
blanchet@53303
   295
        val TUs = binder_fun_types (fastype_of TUiter);
blanchet@53303
   296
        val iter_preTs = if is_rec then rec_preTs else fold_preTs;
blanchet@53303
   297
        val iter_strs = if is_rec then rec_strs else fold_strs;
traytel@55803
   298
blanchet@53303
   299
        fun mk_s TU' =
blanchet@53303
   300
          let
traytel@55803
   301
            fun mk_absT_fp_repT repT absT = mk_absT thy repT absT ooo mk_repT;
traytel@55803
   302
blanchet@53303
   303
            val i = find_index (fn T => co_alg_argT TU' = T) Xs;
traytel@55803
   304
            val fp_abs = nth fp_abss i;
traytel@55803
   305
            val fp_rep = nth fp_reps i;
traytel@55803
   306
            val abs = nth abss i;
traytel@55803
   307
            val rep = nth reps i;
blanchet@54233
   308
            val sF = co_alg_funT TU';
traytel@55803
   309
            val sF' =
traytel@55803
   310
              mk_absT_fp_repT (nth repTs' i) (nth absTs' i) (nth fp_absTs i) (nth fp_repTs i) sF
traytel@55803
   311
                handle Term.TYPE _ => sF;
blanchet@53303
   312
            val F = nth iter_preTs i;
blanchet@53303
   313
            val s = nth iter_strs i;
blanchet@53303
   314
          in
traytel@55803
   315
            if sF = F then s
traytel@55803
   316
            else if sF' = F then mk_co_comp_abs_rep sF sF' fp_abs fp_rep abs rep s
blanchet@53303
   317
            else
blanchet@53303
   318
              let
traytel@55803
   319
                val smapT = replicate live dummyT ---> mk_co_algT sF' F;
blanchet@53303
   320
                fun hidden_to_unit t =
blanchet@53303
   321
                  Term.subst_TVars (map (rpair HOLogic.unitT) (Term.add_tvar_names t [])) t;
blanchet@53303
   322
                val smap = map_of_bnf (nth bnfs i)
blanchet@53303
   323
                  |> force_typ names_lthy smapT
blanchet@53303
   324
                  |> hidden_to_unit;
blanchet@53303
   325
                val smap_argTs = strip_typeN live (fastype_of smap) |> fst;
blanchet@54233
   326
                fun mk_smap_arg TU =
blanchet@53303
   327
                  (if domain_type TU = range_type TU then
blanchet@53303
   328
                    HOLogic.id_const (domain_type TU)
blanchet@53303
   329
                  else if is_rec then
blanchet@53303
   330
                    let
blanchet@53303
   331
                      val (TY, (U, X)) = TU |> dest_co_algT ||> dest_co_productT;
blanchet@53303
   332
                      val T = mk_co_algT TY U;
blanchet@53303
   333
                    in
blanchet@53303
   334
                      (case try (force_typ lthy T o build_map lthy co_proj1_const o dest_funT) T of
blanchet@53303
   335
                        SOME f => mk_co_product f
blanchet@53303
   336
                          (fst (fst (mk_iter NONE is_rec iters lthy (mk_co_algT TY X))))
blanchet@53303
   337
                      | NONE => mk_map_co_product
blanchet@53303
   338
                          (build_map lthy co_proj1_const
blanchet@53303
   339
                            (dest_funT (mk_co_algT (dest_co_productT TY |> fst) U)))
blanchet@53303
   340
                          (HOLogic.id_const X))
blanchet@53303
   341
                    end
blanchet@53303
   342
                  else
blanchet@53303
   343
                    fst (fst (mk_iter NONE is_rec iters lthy TU)))
blanchet@53303
   344
                val smap_args = map mk_smap_arg smap_argTs;
blanchet@53303
   345
              in
traytel@55803
   346
                mk_co_comp_abs_rep sF sF' fp_abs fp_rep abs rep
traytel@55803
   347
                  (mk_co_comp (s, Term.list_comb (smap, smap_args)))
traytel@55803
   348
              end
blanchet@53303
   349
          end;
blanchet@53303
   350
        val t = Term.list_comb (TUiter, map mk_s TUs);
blanchet@53303
   351
      in
blanchet@53303
   352
        (case b_opt of
blanchet@53303
   353
          NONE => ((t, Drule.dummy_thm), lthy)
blanchet@54233
   354
        | SOME b => Local_Theory.define ((b, NoSyn), ((Binding.conceal (Thm.def_binding b), []),
blanchet@53303
   355
            fold_rev Term.absfree (if is_rec then rec_strs' else fold_strs') t)) lthy |>> apsnd snd)
blanchet@53303
   356
      end;
blanchet@53303
   357
blanchet@53303
   358
    fun mk_iters is_rec name lthy =
blanchet@53303
   359
      fold2 (fn TU => fn b => fn ((iters, defs), lthy) =>
blanchet@53303
   360
        mk_iter (SOME b) is_rec iters lthy TU |>> (fn (f, d) => (f :: iters, d :: defs)))
blanchet@53303
   361
      resTs (map (Binding.suffix_name ("_" ^ name)) bs) (([], []), lthy)
blanchet@53303
   362
      |>> apfst rev o apsnd rev;
blanchet@53303
   363
    val foldN = fp_case fp ctor_foldN dtor_unfoldN;
blanchet@53303
   364
    val recN = fp_case fp ctor_recN dtor_corecN;
traytel@53331
   365
    val (((raw_un_folds, raw_un_fold_defs), (raw_co_recs, raw_co_rec_defs)), (lthy, raw_lthy)) =
blanchet@53303
   366
      lthy
blanchet@53303
   367
      |> mk_iters false foldN
blanchet@53303
   368
      ||>> mk_iters true recN
traytel@53331
   369
      ||> `Local_Theory.restore;
blanchet@53303
   370
traytel@53331
   371
    val phi = Proof_Context.export_morphism raw_lthy lthy;
blanchet@53303
   372
blanchet@53303
   373
    val un_folds = map (Morphism.term phi) raw_un_folds;
blanchet@53303
   374
    val co_recs = map (Morphism.term phi) raw_co_recs;
blanchet@53303
   375
blanchet@53303
   376
    val (xtor_un_fold_thms, xtor_co_rec_thms) =
blanchet@53303
   377
      let
blanchet@53303
   378
        val folds = map (fn f => Term.list_comb (f, fold_strs)) raw_un_folds;
blanchet@53303
   379
        val recs = map (fn r => Term.list_comb (r, rec_strs)) raw_co_recs;
blanchet@53303
   380
        val fold_mapTs = co_swap (As @ fpTs, As @ Xs);
blanchet@53303
   381
        val rec_mapTs = co_swap (As @ fpTs, As @ map2 mk_co_productT fpTs Xs);
blanchet@53303
   382
        val pre_fold_maps =
blanchet@53303
   383
          map2 (fn Ds => fn bnf =>
blanchet@53303
   384
            Term.list_comb (uncurry (mk_map_of_bnf Ds) fold_mapTs bnf,
blanchet@53303
   385
              map HOLogic.id_const As @ folds))
blanchet@53303
   386
          Dss bnfs;
blanchet@53303
   387
        val pre_rec_maps =
blanchet@53303
   388
          map2 (fn Ds => fn bnf =>
blanchet@53303
   389
            Term.list_comb (uncurry (mk_map_of_bnf Ds) rec_mapTs bnf,
blanchet@53303
   390
              map HOLogic.id_const As @ map2 (mk_co_product o HOLogic.id_const) fpTs recs))
blanchet@53303
   391
          Dss bnfs;
blanchet@53303
   392
traytel@55803
   393
        fun mk_goals f xtor s smap fp_abs fp_rep abs rep =
traytel@55803
   394
          let
traytel@55803
   395
            val lhs = mk_co_comp (f, xtor);
traytel@55803
   396
            val rhs = mk_co_comp (s, smap);
traytel@55803
   397
          in
traytel@55803
   398
            HOLogic.mk_eq (lhs,
traytel@55803
   399
              mk_co_comp_abs_rep (co_alg_funT (fastype_of lhs)) (co_alg_funT (fastype_of rhs))
traytel@55803
   400
                fp_abs fp_rep abs rep rhs)
traytel@55803
   401
          end;
blanchet@53303
   402
traytel@55803
   403
        val fold_goals =
traytel@55803
   404
          map8 mk_goals folds xtors fold_strs pre_fold_maps fp_abss fp_reps abss reps;
traytel@55803
   405
        val rec_goals = map8 mk_goals recs xtors rec_strs pre_rec_maps fp_abss fp_reps abss reps;
blanchet@53303
   406
blanchet@53303
   407
        fun mk_thms ss goals tac =
blanchet@53303
   408
          Library.foldr1 HOLogic.mk_conj goals
blanchet@53303
   409
          |> HOLogic.mk_Trueprop
blanchet@53303
   410
          |> fold_rev Logic.all ss
traytel@53331
   411
          |> (fn goal => Goal.prove_sorry raw_lthy [] [] goal tac)
blanchet@53303
   412
          |> Thm.close_derivation
blanchet@53303
   413
          |> Morphism.thm phi
blanchet@53303
   414
          |> split_conj_thm
blanchet@53303
   415
          |> map (fn thm => thm RS @{thm comp_eq_dest});
blanchet@53303
   416
blanchet@53303
   417
        val pre_map_defs = no_refl (map map_def_of_bnf bnfs);
blanchet@53303
   418
        val fp_pre_map_defs = no_refl (map map_def_of_bnf pre_bnfs);
blanchet@53303
   419
traytel@55803
   420
        val unfold_map = map (unfold_thms lthy (id_apply :: pre_map_defs));
traytel@55803
   421
traytel@55803
   422
        val fp_xtor_co_iterss = of_fp_res #xtor_co_iter_thmss;
traytel@55803
   423
        val fp_xtor_un_folds = map (mk_pointfree lthy o un_fold_of) fp_xtor_co_iterss;
traytel@55803
   424
        val fp_xtor_co_recs = map (mk_pointfree lthy o co_rec_of) fp_xtor_co_iterss;
blanchet@53303
   425
traytel@55803
   426
        val fp_co_iter_o_mapss = of_fp_res #xtor_co_iter_o_map_thmss;
traytel@55803
   427
        val fp_fold_o_maps = map un_fold_of fp_co_iter_o_mapss;
traytel@55803
   428
        val fp_rec_o_maps = map co_rec_of fp_co_iter_o_mapss;
traytel@55803
   429
        val fold_thms = fp_case fp @{thm comp_assoc} @{thm comp_assoc[symmetric]} ::
traytel@55803
   430
          map (fn thm => thm RS rewrite_comp_comp) @{thms map_pair.comp sum_map.comp} @
traytel@55803
   431
          @{thms id_apply comp_id id_comp map_pair.comp map_pair.id sum_map.comp sum_map.id};
blanchet@53303
   432
        val rec_thms = fold_thms @ fp_case fp
blanchet@53303
   433
          @{thms fst_convol map_pair_o_convol convol_o}
blanchet@55414
   434
          @{thms case_sum_o_inj(1) case_sum_o_sum_map o_case_sum};
traytel@55803
   435
traytel@55810
   436
        val eq_thm_prop_untyped = Term.aconv_untyped o pairself Thm.full_prop_of;
traytel@55803
   437
blanchet@53303
   438
        val map_thms = no_refl (maps (fn bnf =>
traytel@55803
   439
           let val map_comp0 = map_comp0_of_bnf bnf RS sym
traytel@55803
   440
           in [map_comp0, map_comp0 RS rewrite_comp_comp, map_id0_of_bnf bnf] end) fp_nesty_bnfs) @
traytel@55803
   441
          remove eq_thm_prop_untyped (fp_case fp @{thm comp_assoc[symmetric]} @{thm comp_assoc})
traytel@55803
   442
          (map2 (fn thm => fn bnf =>
traytel@55803
   443
            @{thm type_copy_map_comp0_undo} OF
traytel@55803
   444
              (replicate 3 thm @ unfold_map [map_comp0_of_bnf bnf]) RS
traytel@55803
   445
              rewrite_comp_comp)
traytel@55803
   446
          type_definitions bnfs);
traytel@55803
   447
traytel@55803
   448
        fun mk_Rep_o_Abs thm = thm RS @{thm type_copy_Rep_o_Abs} RS rewrite_comp_comp;
traytel@55803
   449
traytel@55803
   450
        val fp_Rep_o_Abss = map mk_Rep_o_Abs fp_type_definitions;
traytel@55803
   451
        val Rep_o_Abss = map mk_Rep_o_Abs type_definitions;
blanchet@53303
   452
blanchet@53303
   453
        fun mk_tac defs o_map_thms xtor_thms thms {context = ctxt, prems = _} =
traytel@55803
   454
          unfold_thms_tac ctxt (flat [thms, defs, pre_map_defs, fp_pre_map_defs,
traytel@55803
   455
            xtor_thms, o_map_thms, map_thms, fp_Rep_o_Abss, Rep_o_Abss]) THEN
blanchet@53303
   456
          CONJ_WRAP (K (HEADGOAL (rtac refl))) bnfs;
blanchet@53303
   457
blanchet@53303
   458
        val fold_tac = mk_tac raw_un_fold_defs fp_fold_o_maps fp_xtor_un_folds fold_thms;
blanchet@53303
   459
        val rec_tac = mk_tac raw_co_rec_defs fp_rec_o_maps fp_xtor_co_recs rec_thms;
blanchet@53303
   460
      in
blanchet@53303
   461
        (mk_thms fold_strs fold_goals fold_tac, mk_thms rec_strs rec_goals rec_tac)
blanchet@53303
   462
      end;
blanchet@53303
   463
blanchet@53303
   464
    (* These results are half broken. This is deliberate. We care only about those fields that are
blanchet@55531
   465
       used by "primrec", "primcorecursive", and "datatype_compat". *)
blanchet@53303
   466
    val fp_res =
blanchet@53303
   467
      ({Ts = fpTs,
traytel@55803
   468
        bnfs = of_fp_res #bnfs,
blanchet@53303
   469
        dtors = dtors,
blanchet@53303
   470
        ctors = ctors,
blanchet@53303
   471
        xtor_co_iterss = transpose [un_folds, co_recs],
blanchet@53303
   472
        xtor_co_induct = xtor_co_induct_thm,
traytel@55803
   473
        dtor_ctors = of_fp_res #dtor_ctors (*too general types*),
traytel@55803
   474
        ctor_dtors = of_fp_res #ctor_dtors (*too general types*),
traytel@55803
   475
        ctor_injects = of_fp_res #ctor_injects (*too general types*),
traytel@55803
   476
        dtor_injects = of_fp_res #dtor_injects (*too general types*),
traytel@55803
   477
        xtor_map_thms = of_fp_res #xtor_map_thms (*too general types and terms*),
traytel@55803
   478
        xtor_set_thmss = of_fp_res #xtor_set_thmss (*too general types and terms*),
traytel@55803
   479
        xtor_rel_thms = of_fp_res #xtor_rel_thms (*too general types and terms*),
blanchet@53303
   480
        xtor_co_iter_thmss = transpose [xtor_un_fold_thms, xtor_co_rec_thms],
traytel@55803
   481
        xtor_co_iter_o_map_thmss = of_fp_res #xtor_co_iter_o_map_thmss
blanchet@55539
   482
          (*theorem about old constant*),
blanchet@53303
   483
        rel_xtor_co_induct_thm = rel_xtor_co_induct_thm}
wenzelm@54740
   484
       |> morph_fp_result (Morphism.term_morphism "BNF" (singleton (Variable.polymorphic lthy))));
blanchet@53303
   485
  in
blanchet@53303
   486
    (fp_res, lthy)
blanchet@54242
   487
  end;
blanchet@53303
   488
blanchet@53303
   489
end;