src/HOL/Codatatype/Tools/bnf_fp_sugar.ML
author blanchet
Mon, 17 Sep 2012 21:13:30 +0200
changeset 50442 b017e1dbc77c
parent 50441 6d05b8452cf3
child 50444 64ac3471005a
permissions -rw-r--r--
clean unfolding of prod and sum sets
blanchet@50127
     1
(*  Title:      HOL/Codatatype/Tools/bnf_fp_sugar.ML
blanchet@50127
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@50127
     3
    Copyright   2012
blanchet@50127
     4
blanchet@50404
     5
Sugared datatype and codatatype constructions.
blanchet@50127
     6
*)
blanchet@50127
     7
blanchet@50127
     8
signature BNF_FP_SUGAR =
blanchet@50127
     9
sig
blanchet@50312
    10
  val datatyp: bool ->
blanchet@50323
    11
    (mixfix list -> (string * sort) list option -> binding list -> typ list * typ list list ->
blanchet@50323
    12
      BNF_Def.BNF list -> local_theory ->
blanchet@50352
    13
      (term list * term list * term list * term list * thm * thm list * thm list * thm list *
blanchet@50352
    14
         thm list * thm list) * local_theory) ->
blanchet@50313
    15
    bool * ((((typ * sort) list * binding) * mixfix) * ((((binding * binding) *
blanchet@50312
    16
      (binding * typ) list) * (binding * term) list) * mixfix) list) list ->
blanchet@50312
    17
    local_theory -> local_theory
blanchet@50323
    18
  val parse_datatype_cmd: bool ->
blanchet@50323
    19
    (mixfix list -> (string * sort) list option -> binding list -> typ list * typ list list ->
blanchet@50323
    20
      BNF_Def.BNF list -> local_theory ->
blanchet@50352
    21
      (term list * term list * term list * term list * thm * thm list * thm list * thm list *
blanchet@50352
    22
         thm list * thm list) * local_theory) ->
blanchet@50323
    23
    (local_theory -> local_theory) parser
blanchet@50127
    24
end;
blanchet@50127
    25
blanchet@50127
    26
structure BNF_FP_Sugar : BNF_FP_SUGAR =
blanchet@50127
    27
struct
blanchet@50127
    28
blanchet@50134
    29
open BNF_Util
blanchet@50134
    30
open BNF_Wrap
blanchet@50229
    31
open BNF_Def
blanchet@50134
    32
open BNF_FP_Util
blanchet@50138
    33
open BNF_FP_Sugar_Tactics
blanchet@50134
    34
blanchet@50315
    35
val simp_attrs = @{attributes [simp]};
blanchet@50315
    36
blanchet@50385
    37
fun split_list10 xs =
blanchet@50281
    38
  (map #1 xs, map #2 xs, map #3 xs, map #4 xs, map #5 xs, map #6 xs, map #7 xs, map #8 xs,
blanchet@50385
    39
   map #9 xs, map #10 xs);
blanchet@50229
    40
blanchet@50357
    41
fun resort_tfree S (TFree (s, _)) = TFree (s, S);
blanchet@50357
    42
blanchet@50229
    43
fun typ_subst inst (T as Type (s, Ts)) =
blanchet@50229
    44
    (case AList.lookup (op =) inst T of
blanchet@50229
    45
      NONE => Type (s, map (typ_subst inst) Ts)
blanchet@50229
    46
    | SOME T' => T')
blanchet@50229
    47
  | typ_subst inst T = the_default T (AList.lookup (op =) inst T);
blanchet@50220
    48
blanchet@50312
    49
val lists_bmoc = fold (fn xs => fn t => Term.list_comb (t, xs));
blanchet@50217
    50
blanchet@50215
    51
fun mk_tupled_fun x f xs = HOLogic.tupled_lambda x (Term.list_comb (f, xs));
blanchet@50215
    52
fun mk_uncurried_fun f xs = mk_tupled_fun (HOLogic.mk_tuple xs) f xs;
blanchet@50217
    53
fun mk_uncurried2_fun f xss =
blanchet@50215
    54
  mk_tupled_fun (HOLogic.mk_tuple (map HOLogic.mk_tuple xss)) f (flat xss);
blanchet@50215
    55
blanchet@50248
    56
fun tick v f = Term.lambda v (HOLogic.mk_prod (v, f $ v));
blanchet@50248
    57
blanchet@50248
    58
fun tack z_name (c, v) f =
blanchet@50288
    59
  let val z = Free (z_name, mk_sumT (fastype_of v, fastype_of c)) in
blanchet@50288
    60
    Term.lambda z (mk_sum_case (Term.lambda v v, Term.lambda c (f $ c)) $ z)
blanchet@50288
    61
  end;
blanchet@50229
    62
blanchet@50139
    63
fun cannot_merge_types () = error "Mutually recursive types must have the same type parameters";
blanchet@50134
    64
blanchet@50313
    65
fun merge_type_arg T T' = if T = T' then T else cannot_merge_types ();
blanchet@50134
    66
blanchet@50313
    67
fun merge_type_args (As, As') =
blanchet@50313
    68
  if length As = length As' then map2 merge_type_arg As As' else cannot_merge_types ();
blanchet@50134
    69
blanchet@50136
    70
fun type_args_constrained_of (((cAs, _), _), _) = cAs;
blanchet@50351
    71
fun type_binding_of (((_, b), _), _) = b;
blanchet@50196
    72
fun mixfix_of ((_, mx), _) = mx;
blanchet@50136
    73
fun ctr_specs_of (_, ctr_specs) = ctr_specs;
blanchet@50134
    74
blanchet@50301
    75
fun disc_of ((((disc, _), _), _), _) = disc;
blanchet@50301
    76
fun ctr_of ((((_, ctr), _), _), _) = ctr;
blanchet@50301
    77
fun args_of (((_, args), _), _) = args;
blanchet@50301
    78
fun defaults_of ((_, ds), _) = ds;
blanchet@50196
    79
fun ctr_mixfix_of (_, mx) = mx;
blanchet@50134
    80
blanchet@50323
    81
fun define_datatype prepare_constraint prepare_typ prepare_term lfp construct (no_dests, specs)
blanchet@50313
    82
    no_defs_lthy0 =
blanchet@50127
    83
  let
blanchet@50313
    84
    (* TODO: sanity checks on arguments *)
blanchet@50313
    85
blanchet@50301
    86
    val _ = if not lfp andalso no_dests then error "Cannot define destructor-less codatatypes"
blanchet@50293
    87
      else ();
blanchet@50293
    88
blanchet@50382
    89
    val nn = length specs;
blanchet@50376
    90
    val fp_bs = map type_binding_of specs;
blanchet@50376
    91
    val fp_common_name = mk_common_name fp_bs;
blanchet@50134
    92
blanchet@50313
    93
    fun prepare_type_arg (ty, c) =
blanchet@50313
    94
      let val TFree (s, _) = prepare_typ no_defs_lthy0 ty in
blanchet@50313
    95
        TFree (s, prepare_constraint no_defs_lthy0 c)
blanchet@50313
    96
      end;
blanchet@50134
    97
blanchet@50313
    98
    val Ass0 = map (map prepare_type_arg o type_args_constrained_of) specs;
blanchet@50313
    99
    val unsorted_Ass0 = map (map (resort_tfree HOLogic.typeS)) Ass0;
blanchet@50313
   100
    val unsorted_As = Library.foldr1 merge_type_args unsorted_Ass0;
blanchet@50134
   101
blanchet@50385
   102
    val ((Bs, Cs), no_defs_lthy) =
blanchet@50313
   103
      no_defs_lthy0
blanchet@50313
   104
      |> fold (Variable.declare_typ o resort_tfree dummyS) unsorted_As
blanchet@50382
   105
      |> mk_TFrees nn
blanchet@50385
   106
      ||>> mk_TFrees nn;
blanchet@50313
   107
blanchet@50313
   108
    (* TODO: cleaner handling of fake contexts, without "background_theory" *)
blanchet@50313
   109
    (*the "perhaps o try" below helps gracefully handles the case where the new type is defined in a
blanchet@50313
   110
      locale and shadows an existing global type*)
blanchet@50313
   111
    val fake_thy =
blanchet@50313
   112
      Theory.copy #> fold (fn spec => perhaps (try (Sign.add_type no_defs_lthy
blanchet@50351
   113
        (type_binding_of spec, length (type_args_constrained_of spec), mixfix_of spec)))) specs;
blanchet@50313
   114
    val fake_lthy = Proof_Context.background_theory fake_thy no_defs_lthy;
blanchet@50134
   115
blanchet@50197
   116
    fun mk_fake_T b =
blanchet@50136
   117
      Type (fst (Term.dest_Type (Proof_Context.read_type_name fake_lthy true (Binding.name_of b))),
blanchet@50313
   118
        unsorted_As);
blanchet@50136
   119
blanchet@50317
   120
    val fake_Ts = map mk_fake_T fp_bs;
blanchet@50136
   121
blanchet@50196
   122
    val mixfixes = map mixfix_of specs;
blanchet@50134
   123
blanchet@50317
   124
    val _ = (case duplicates Binding.eq_name fp_bs of [] => ()
blanchet@50134
   125
      | b :: _ => error ("Duplicate type name declaration " ^ quote (Binding.name_of b)));
blanchet@50134
   126
blanchet@50136
   127
    val ctr_specss = map ctr_specs_of specs;
blanchet@50134
   128
blanchet@50351
   129
    val disc_bindingss = map (map disc_of) ctr_specss;
blanchet@50351
   130
    val ctr_bindingss =
blanchet@50317
   131
      map2 (fn fp_b => map (Binding.qualify false (Binding.name_of fp_b) o ctr_of))
blanchet@50317
   132
        fp_bs ctr_specss;
blanchet@50136
   133
    val ctr_argsss = map (map args_of) ctr_specss;
blanchet@50196
   134
    val ctr_mixfixess = map (map ctr_mixfix_of) ctr_specss;
blanchet@50134
   135
blanchet@50351
   136
    val sel_bindingsss = map (map (map fst)) ctr_argsss;
blanchet@50313
   137
    val fake_ctr_Tsss0 = map (map (map (prepare_typ fake_lthy o snd))) ctr_argsss;
blanchet@50301
   138
    val raw_sel_defaultsss = map (map defaults_of) ctr_specss;
blanchet@50301
   139
blanchet@50323
   140
    val (As :: _) :: fake_ctr_Tsss =
blanchet@50313
   141
      burrow (burrow (Syntax.check_typs fake_lthy)) (Ass0 :: fake_ctr_Tsss0);
blanchet@50313
   142
blanchet@50313
   143
    val _ = (case duplicates (op =) unsorted_As of [] => ()
blanchet@50313
   144
      | A :: _ => error ("Duplicate type parameter " ^
blanchet@50313
   145
          quote (Syntax.string_of_typ no_defs_lthy A)));
blanchet@50313
   146
blanchet@50198
   147
    val rhs_As' = fold (fold (fold Term.add_tfreesT)) fake_ctr_Tsss [];
blanchet@50313
   148
    val _ = (case subtract (op =) (map dest_TFree As) rhs_As' of
blanchet@50180
   149
        [] => ()
blanchet@50357
   150
      | A' :: _ => error ("Extra type variable on right-hand side: " ^
blanchet@50219
   151
          quote (Syntax.string_of_typ no_defs_lthy (TFree A'))));
blanchet@50180
   152
blanchet@50219
   153
    fun eq_fpT (T as Type (s, Us)) (Type (s', Us')) =
blanchet@50161
   154
        s = s' andalso (Us = Us' orelse error ("Illegal occurrence of recursive type " ^
blanchet@50161
   155
          quote (Syntax.string_of_typ fake_lthy T)))
blanchet@50219
   156
      | eq_fpT _ _ = false;
blanchet@50161
   157
blanchet@50219
   158
    fun freeze_fp (T as Type (s, Us)) =
blanchet@50313
   159
        (case find_index (eq_fpT T) fake_Ts of ~1 => Type (s, map freeze_fp Us) | j => nth Bs j)
blanchet@50219
   160
      | freeze_fp T = T;
blanchet@50134
   161
blanchet@50312
   162
    val ctr_TsssBs = map (map (map freeze_fp)) fake_ctr_Tsss;
blanchet@50312
   163
    val ctr_sum_prod_TsBs = map (mk_sumTN_balanced o map HOLogic.mk_tupleT) ctr_TsssBs;
blanchet@50134
   164
blanchet@50313
   165
    val fp_eqs =
blanchet@50313
   166
      map dest_TFree Bs ~~ map (Term.typ_subst_atomic (As ~~ unsorted_As)) ctr_sum_prod_TsBs;
blanchet@50136
   167
blanchet@50352
   168
    val (pre_bnfs, ((unfs0, flds0, fp_iters0, fp_recs0, fp_induct, unf_flds, fld_unfs, fld_injects,
blanchet@50222
   169
        fp_iter_thms, fp_rec_thms), lthy)) =
blanchet@50323
   170
      fp_bnf construct fp_bs mixfixes (map dest_TFree unsorted_As) fp_eqs no_defs_lthy0;
blanchet@50136
   171
blanchet@50378
   172
    fun add_nesty_bnf_names Us =
blanchet@50241
   173
      let
blanchet@50241
   174
        fun add (Type (s, Ts)) ss =
blanchet@50241
   175
            let val (needs, ss') = fold_map add Ts ss in
blanchet@50241
   176
              if exists I needs then (true, insert (op =) s ss') else (false, ss')
blanchet@50241
   177
            end
blanchet@50378
   178
          | add T ss = (member (op =) Us T, ss);
blanchet@50241
   179
      in snd oo add end;
blanchet@50241
   180
blanchet@50378
   181
    fun nesty_bnfs Us =
blanchet@50378
   182
      map_filter (bnf_of lthy) (fold (fold (fold (add_nesty_bnf_names Us))) ctr_TsssBs []);
blanchet@50378
   183
blanchet@50378
   184
    val nesting_bnfs = nesty_bnfs As;
blanchet@50378
   185
    val nested_bnfs = nesty_bnfs Bs;
blanchet@50241
   186
blanchet@50182
   187
    val timer = time (Timer.startRealTimer ());
blanchet@50182
   188
blanchet@50191
   189
    fun mk_unf_or_fld get_T Ts t =
blanchet@50191
   190
      let val Type (_, Ts0) = get_T (fastype_of t) in
blanchet@50139
   191
        Term.subst_atomic_types (Ts0 ~~ Ts) t
blanchet@50136
   192
      end;
blanchet@50136
   193
blanchet@50141
   194
    val mk_unf = mk_unf_or_fld domain_type;
blanchet@50141
   195
    val mk_fld = mk_unf_or_fld range_type;
blanchet@50139
   196
blanchet@50218
   197
    val unfs = map (mk_unf As) unfs0;
blanchet@50218
   198
    val flds = map (mk_fld As) flds0;
blanchet@50136
   199
blanchet@50216
   200
    val fpTs = map (domain_type o fastype_of) unfs;
blanchet@50377
   201
blanchet@50377
   202
    val exists_fp_subtype = exists_subtype (member (op =) fpTs);
blanchet@50377
   203
blanchet@50312
   204
    val ctr_Tsss = map (map (map (Term.typ_subst_atomic (Bs ~~ fpTs)))) ctr_TsssBs;
blanchet@50218
   205
    val ns = map length ctr_Tsss;
blanchet@50227
   206
    val kss = map (fn n => 1 upto n) ns;
blanchet@50218
   207
    val mss = map (map length) ctr_Tsss;
blanchet@50218
   208
    val Css = map2 replicate ns Cs;
blanchet@50218
   209
blanchet@50229
   210
    fun mk_iter_like Ts Us t =
blanchet@50134
   211
      let
blanchet@50351
   212
        val (bindings, body) = strip_type (fastype_of t);
blanchet@50351
   213
        val (f_Us, prebody) = split_last bindings;
blanchet@50225
   214
        val Type (_, Ts0) = if lfp then prebody else body;
blanchet@50225
   215
        val Us0 = distinct (op =) (map (if lfp then body_type else domain_type) f_Us);
blanchet@50191
   216
      in
blanchet@50229
   217
        Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) t
blanchet@50191
   218
      end;
blanchet@50191
   219
blanchet@50225
   220
    val fp_iters as fp_iter1 :: _ = map (mk_iter_like As Cs) fp_iters0;
blanchet@50225
   221
    val fp_recs as fp_rec1 :: _ = map (mk_iter_like As Cs) fp_recs0;
blanchet@50225
   222
blanchet@50227
   223
    val fp_iter_fun_Ts = fst (split_last (binder_types (fastype_of fp_iter1)));
blanchet@50227
   224
    val fp_rec_fun_Ts = fst (split_last (binder_types (fastype_of fp_rec1)));
blanchet@50219
   225
blanchet@50271
   226
    val ((iter_only as (gss, _, _), rec_only as (hss, _, _)),
blanchet@50291
   227
         (zs, cs, cpss, coiter_only as ((pgss, crgsss), _), corec_only as ((phss, cshsss), _))) =
blanchet@50223
   228
      if lfp then
blanchet@50223
   229
        let
blanchet@50223
   230
          val y_Tsss =
blanchet@50270
   231
            map3 (fn n => fn ms => map2 dest_tupleT ms o dest_sumTN_balanced n o domain_type)
blanchet@50227
   232
              ns mss fp_iter_fun_Ts;
blanchet@50223
   233
          val g_Tss = map2 (map2 (curry (op --->))) y_Tsss Css;
blanchet@50219
   234
blanchet@50223
   235
          val ((gss, ysss), _) =
blanchet@50223
   236
            lthy
blanchet@50223
   237
            |> mk_Freess "f" g_Tss
blanchet@50223
   238
            ||>> mk_Freesss "x" y_Tsss;
blanchet@50289
   239
          val yssss = map (map (map single)) ysss;
blanchet@50289
   240
blanchet@50289
   241
          fun dest_rec_prodT (T as Type (@{type_name prod}, Us as [_, U])) =
blanchet@50289
   242
              if member (op =) Cs U then Us else [T]
blanchet@50289
   243
            | dest_rec_prodT T = [T];
blanchet@50219
   244
blanchet@50223
   245
          val z_Tssss =
blanchet@50289
   246
            map3 (fn n => fn ms => map2 (map dest_rec_prodT oo dest_tupleT) ms o
blanchet@50270
   247
              dest_sumTN_balanced n o domain_type) ns mss fp_rec_fun_Ts;
blanchet@50223
   248
          val h_Tss = map2 (map2 (fold_rev (curry (op --->)))) z_Tssss Css;
blanchet@50223
   249
blanchet@50313
   250
          val hss = map2 (map2 retype_free) h_Tss gss;
blanchet@50313
   251
          val zssss_hd = map2 (map2 (map2 (retype_free o hd))) z_Tssss ysss;
blanchet@50289
   252
          val (zssss_tl, _) =
blanchet@50223
   253
            lthy
blanchet@50289
   254
            |> mk_Freessss "y" (map (map (map tl)) z_Tssss);
blanchet@50289
   255
          val zssss = map2 (map2 (map2 cons)) zssss_hd zssss_tl;
blanchet@50225
   256
        in
blanchet@50289
   257
          (((gss, g_Tss, yssss), (hss, h_Tss, zssss)),
blanchet@50291
   258
           ([], [], [], (([], []), ([], [])), (([], []), ([], []))))
blanchet@50225
   259
        end
blanchet@50223
   260
      else
blanchet@50225
   261
        let
blanchet@50236
   262
          (*avoid "'a itself" arguments in coiterators and corecursors*)
blanchet@50236
   263
          val mss' =  map (fn [0] => [1] | ms => ms) mss;
blanchet@50236
   264
blanchet@50290
   265
          val p_Tss = map2 (fn n => replicate (Int.max (0, n - 1)) o mk_predT) ns Cs;
blanchet@50191
   266
blanchet@50291
   267
          fun zip_predss_getterss qss fss = maps (op @) (qss ~~ fss);
blanchet@50230
   268
blanchet@50291
   269
          fun zip_preds_predsss_gettersss [] [qss] [fss] = zip_predss_getterss qss fss
blanchet@50291
   270
            | zip_preds_predsss_gettersss (p :: ps) (qss :: qsss) (fss :: fsss) =
blanchet@50291
   271
              p :: zip_predss_getterss qss fss @ zip_preds_predsss_gettersss ps qsss fsss;
blanchet@50289
   272
blanchet@50289
   273
          fun mk_types maybe_dest_sumT fun_Ts =
blanchet@50227
   274
            let
blanchet@50227
   275
              val f_sum_prod_Ts = map range_type fun_Ts;
blanchet@50270
   276
              val f_prod_Tss = map2 dest_sumTN_balanced ns f_sum_prod_Ts;
blanchet@50290
   277
              val f_Tssss =
blanchet@50290
   278
                map3 (fn C => map2 (map (map (curry (op -->) C) o maybe_dest_sumT) oo dest_tupleT))
blanchet@50290
   279
                  Cs mss' f_prod_Tss;
blanchet@50290
   280
              val q_Tssss =
blanchet@50290
   281
                map (map (map (fn [_] => [] | [_, C] => [mk_predT (domain_type C)]))) f_Tssss;
blanchet@50291
   282
              val pf_Tss = map3 zip_preds_predsss_gettersss p_Tss q_Tssss f_Tssss;
blanchet@50290
   283
            in (q_Tssss, f_sum_prod_Ts, f_Tssss, pf_Tss) end;
blanchet@50226
   284
blanchet@50290
   285
          val (r_Tssss, g_sum_prod_Ts, g_Tssss, pg_Tss) = mk_types single fp_iter_fun_Ts;
blanchet@50226
   286
blanchet@50290
   287
          val ((((Free (z, _), cs), pss), gssss), _) =
blanchet@50225
   288
            lthy
blanchet@50248
   289
            |> yield_singleton (mk_Frees "z") dummyT
blanchet@50248
   290
            ||>> mk_Frees "a" Cs
blanchet@50226
   291
            ||>> mk_Freess "p" p_Tss
blanchet@50290
   292
            ||>> mk_Freessss "g" g_Tssss;
blanchet@50290
   293
          val rssss = map (map (map (fn [] => []))) r_Tssss;
blanchet@50289
   294
blanchet@50289
   295
          fun dest_corec_sumT (T as Type (@{type_name sum}, Us as [_, U])) =
blanchet@50289
   296
              if member (op =) Cs U then Us else [T]
blanchet@50289
   297
            | dest_corec_sumT T = [T];
blanchet@50289
   298
blanchet@50290
   299
          val (s_Tssss, h_sum_prod_Ts, h_Tssss, ph_Tss) = mk_types dest_corec_sumT fp_rec_fun_Ts;
blanchet@50225
   300
blanchet@50313
   301
          val hssss_hd = map2 (map2 (map2 (fn T :: _ => fn [g] => retype_free T g))) h_Tssss gssss;
blanchet@50290
   302
          val ((sssss, hssss_tl), _) =
blanchet@50290
   303
            lthy
blanchet@50290
   304
            |> mk_Freessss "q" s_Tssss
blanchet@50290
   305
            ||>> mk_Freessss "h" (map (map (map tl)) h_Tssss);
blanchet@50290
   306
          val hssss = map2 (map2 (map2 cons)) hssss_hd hssss_tl;
blanchet@50226
   307
blanchet@50227
   308
          val cpss = map2 (fn c => map (fn p => p $ c)) cs pss;
blanchet@50227
   309
blanchet@50291
   310
          fun mk_preds_getters_join [] [cf] = cf
blanchet@50291
   311
            | mk_preds_getters_join [cq] [cf, cf'] =
blanchet@50291
   312
              mk_If cq (mk_Inl (fastype_of cf') cf) (mk_Inr (fastype_of cf) cf');
blanchet@50291
   313
blanchet@50290
   314
          fun mk_terms qssss fssss =
blanchet@50227
   315
            let
blanchet@50291
   316
              val pfss = map3 zip_preds_predsss_gettersss pss qssss fssss;
blanchet@50290
   317
              val cqssss = map2 (fn c => map (map (map (fn f => f $ c)))) cs qssss;
blanchet@50289
   318
              val cfssss = map2 (fn c => map (map (map (fn f => f $ c)))) cs fssss;
blanchet@50291
   319
              val cqfsss = map2 (map2 (map2 mk_preds_getters_join)) cqssss cfssss;
blanchet@50291
   320
            in (pfss, cqfsss) end;
blanchet@50225
   321
        in
blanchet@50227
   322
          ((([], [], []), ([], [], [])),
blanchet@50290
   323
           ([z], cs, cpss, (mk_terms rssss gssss, (g_sum_prod_Ts, pg_Tss)),
blanchet@50290
   324
            (mk_terms sssss hssss, (h_sum_prod_Ts, ph_Tss))))
blanchet@50225
   325
        end;
blanchet@50225
   326
blanchet@50385
   327
    fun define_ctrs_case_for_type ((((((((((((((((((fp_b, fpT), C), fld), unf), fp_iter), fp_rec),
blanchet@50385
   328
          fld_unf), unf_fld), fld_inject), n), ks), ms), ctr_bindings), ctr_mixfixes), ctr_Tss),
blanchet@50385
   329
        disc_bindings), sel_bindingss), raw_sel_defaultss) no_defs_lthy =
blanchet@50191
   330
      let
blanchet@50216
   331
        val unfT = domain_type (fastype_of fld);
blanchet@50225
   332
        val ctr_prod_Ts = map HOLogic.mk_tupleT ctr_Tss;
blanchet@50270
   333
        val ctr_sum_prod_T = mk_sumTN_balanced ctr_prod_Ts;
blanchet@50149
   334
        val case_Ts = map (fn Ts => Ts ---> C) ctr_Tss;
blanchet@50139
   335
blanchet@50385
   336
        val ((((u, fs), xss), v'), _) =
blanchet@50219
   337
          no_defs_lthy
blanchet@50216
   338
          |> yield_singleton (mk_Frees "u") unfT
blanchet@50191
   339
          ||>> mk_Frees "f" case_Ts
blanchet@50385
   340
          ||>> mk_Freess "x" ctr_Tss
blanchet@50385
   341
          ||>> yield_singleton (Variable.variant_fixes) (Binding.name_of fp_b);
blanchet@50385
   342
blanchet@50385
   343
        val v = Free (v', fpT);
blanchet@50136
   344
blanchet@50144
   345
        val ctr_rhss =
blanchet@50271
   346
          map2 (fn k => fn xs => fold_rev Term.lambda xs (fld $
blanchet@50271
   347
            mk_InN_balanced ctr_sum_prod_T n (HOLogic.mk_tuple xs) k)) ks xss;
blanchet@50136
   348
blanchet@50351
   349
        val case_binding = Binding.suffix_name ("_" ^ caseN) fp_b;
blanchet@50144
   350
blanchet@50149
   351
        val case_rhs =
blanchet@50270
   352
          fold_rev Term.lambda (fs @ [v])
blanchet@50270
   353
            (mk_sum_caseN_balanced (map2 mk_uncurried_fun fs xss) $ (unf $ v));
blanchet@50144
   354
blanchet@50216
   355
        val ((raw_case :: raw_ctrs, raw_case_def :: raw_ctr_defs), (lthy', lthy)) = no_defs_lthy
blanchet@50184
   356
          |> apfst split_list o fold_map3 (fn b => fn mx => fn rhs =>
blanchet@50317
   357
              Local_Theory.define ((b, mx), ((Thm.def_binding b, []), rhs)) #>> apsnd snd)
blanchet@50351
   358
            (case_binding :: ctr_bindings) (NoSyn :: ctr_mixfixes) (case_rhs :: ctr_rhss)
blanchet@50136
   359
          ||> `Local_Theory.restore;
blanchet@50136
   360
blanchet@50136
   361
        val phi = Proof_Context.export_morphism lthy lthy';
blanchet@50136
   362
blanchet@50136
   363
        val ctr_defs = map (Morphism.thm phi) raw_ctr_defs;
blanchet@50145
   364
        val case_def = Morphism.thm phi raw_case_def;
blanchet@50145
   365
blanchet@50218
   366
        val ctrs0 = map (Morphism.term phi) raw_ctrs;
blanchet@50218
   367
        val casex0 = Morphism.term phi raw_case;
blanchet@50218
   368
blanchet@50218
   369
        val ctrs = map (mk_ctr As) ctrs0;
blanchet@50136
   370
blanchet@50150
   371
        fun exhaust_tac {context = ctxt, ...} =
blanchet@50138
   372
          let
blanchet@50150
   373
            val fld_iff_unf_thm =
blanchet@50150
   374
              let
blanchet@50150
   375
                val goal =
blanchet@50150
   376
                  fold_rev Logic.all [u, v]
blanchet@50150
   377
                    (mk_Trueprop_eq (HOLogic.mk_eq (v, fld $ u), HOLogic.mk_eq (unf $ v, u)));
blanchet@50150
   378
              in
blanchet@50150
   379
                Skip_Proof.prove lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@50216
   380
                  mk_fld_iff_unf_tac ctxt (map (SOME o certifyT lthy) [unfT, fpT])
blanchet@50191
   381
                    (certify lthy fld) (certify lthy unf) fld_unf unf_fld)
blanchet@50150
   382
                |> Thm.close_derivation
blanchet@50150
   383
                |> Morphism.thm phi
blanchet@50150
   384
              end;
blanchet@50150
   385
blanchet@50150
   386
            val sumEN_thm' =
blanchet@50150
   387
              Local_Defs.unfold lthy @{thms all_unit_eq}
blanchet@50270
   388
                (Drule.instantiate' (map (SOME o certifyT lthy) ctr_prod_Ts) []
blanchet@50270
   389
                   (mk_sumEN_balanced n))
blanchet@50150
   390
              |> Morphism.thm phi;
blanchet@50138
   391
          in
blanchet@50176
   392
            mk_exhaust_tac ctxt n ctr_defs fld_iff_unf_thm sumEN_thm'
blanchet@50138
   393
          end;
blanchet@50136
   394
blanchet@50141
   395
        val inject_tacss =
blanchet@50220
   396
          map2 (fn 0 => K [] | _ => fn ctr_def => [fn {context = ctxt, ...} =>
blanchet@50220
   397
              mk_inject_tac ctxt ctr_def fld_inject]) ms ctr_defs;
blanchet@50141
   398
blanchet@50142
   399
        val half_distinct_tacss =
blanchet@50142
   400
          map (map (fn (def, def') => fn {context = ctxt, ...} =>
blanchet@50142
   401
            mk_half_distinct_tac ctxt fld_inject [def, def'])) (mk_half_pairss ctr_defs);
blanchet@50142
   402
blanchet@50145
   403
        val case_tacs =
blanchet@50145
   404
          map3 (fn k => fn m => fn ctr_def => fn {context = ctxt, ...} =>
blanchet@50145
   405
            mk_case_tac ctxt n k m case_def ctr_def unf_fld) ks ms ctr_defs;
blanchet@50136
   406
blanchet@50136
   407
        val tacss = [exhaust_tac] :: inject_tacss @ half_distinct_tacss @ [case_tacs];
blanchet@50149
   408
blanchet@50302
   409
        fun define_iter_rec ((selss0, discIs, sel_thmss), no_defs_lthy) =
blanchet@50149
   410
          let
blanchet@50223
   411
            val fpT_to_C = fpT --> C;
blanchet@50214
   412
blanchet@50230
   413
            fun generate_iter_like (suf, fp_iter_like, (fss, f_Tss, xssss)) =
blanchet@50230
   414
              let
blanchet@50230
   415
                val res_T = fold_rev (curry (op --->)) f_Tss fpT_to_C;
blanchet@50351
   416
                val binding = Binding.suffix_name ("_" ^ suf) fp_b;
blanchet@50230
   417
                val spec =
blanchet@50351
   418
                  mk_Trueprop_eq (lists_bmoc fss (Free (Binding.name_of binding, res_T)),
blanchet@50230
   419
                    Term.list_comb (fp_iter_like,
blanchet@50270
   420
                      map2 (mk_sum_caseN_balanced oo map2 mk_uncurried2_fun) fss xssss));
blanchet@50351
   421
              in (binding, spec) end;
blanchet@50230
   422
blanchet@50315
   423
            val iter_like_infos =
blanchet@50230
   424
              [(iterN, fp_iter, iter_only),
blanchet@50230
   425
               (recN, fp_rec, rec_only)];
blanchet@50230
   426
blanchet@50351
   427
            val (bindings, specs) = map generate_iter_like iter_like_infos |> split_list;
blanchet@50230
   428
blanchet@50230
   429
            val ((csts, defs), (lthy', lthy)) = no_defs_lthy
blanchet@50216
   430
              |> apfst split_list o fold_map2 (fn b => fn spec =>
blanchet@50214
   431
                Specification.definition (SOME (b, NONE, NoSyn), ((Thm.def_binding b, []), spec))
blanchet@50351
   432
                #>> apsnd snd) bindings specs
blanchet@50214
   433
              ||> `Local_Theory.restore;
blanchet@50216
   434
blanchet@50216
   435
            val phi = Proof_Context.export_morphism lthy lthy';
blanchet@50216
   436
blanchet@50230
   437
            val [iter_def, rec_def] = map (Morphism.thm phi) defs;
blanchet@50216
   438
blanchet@50230
   439
            val [iter, recx] = map (mk_iter_like As Cs o Morphism.term phi) csts;
blanchet@50149
   440
          in
blanchet@50385
   441
            ((ctrs, selss0, iter, recx, xss, ctr_defs, discIs, sel_thmss, iter_def, rec_def), lthy)
blanchet@50149
   442
          end;
blanchet@50149
   443
blanchet@50302
   444
        fun define_coiter_corec ((selss0, discIs, sel_thmss), no_defs_lthy) =
blanchet@50225
   445
          let
blanchet@50225
   446
            val B_to_fpT = C --> fpT;
blanchet@50225
   447
blanchet@50291
   448
            fun mk_preds_getterss_join c n cps sum_prod_T cqfss =
blanchet@50291
   449
              Term.lambda c (mk_IfN sum_prod_T cps
blanchet@50291
   450
                (map2 (mk_InN_balanced sum_prod_T n) (map HOLogic.mk_tuple cqfss) (1 upto n)));
blanchet@50290
   451
blanchet@50291
   452
            fun generate_coiter_like (suf, fp_iter_like, ((pfss, cqfsss), (f_sum_prod_Ts,
blanchet@50289
   453
                pf_Tss))) =
blanchet@50226
   454
              let
blanchet@50226
   455
                val res_T = fold_rev (curry (op --->)) pf_Tss B_to_fpT;
blanchet@50351
   456
                val binding = Binding.suffix_name ("_" ^ suf) fp_b;
blanchet@50226
   457
                val spec =
blanchet@50351
   458
                  mk_Trueprop_eq (lists_bmoc pfss (Free (Binding.name_of binding, res_T)),
blanchet@50226
   459
                    Term.list_comb (fp_iter_like,
blanchet@50291
   460
                      map5 mk_preds_getterss_join cs ns cpss f_sum_prod_Ts cqfsss));
blanchet@50351
   461
              in (binding, spec) end;
blanchet@50225
   462
blanchet@50315
   463
            val coiter_like_infos =
blanchet@50230
   464
              [(coiterN, fp_iter, coiter_only),
blanchet@50230
   465
               (corecN, fp_rec, corec_only)];
blanchet@50227
   466
blanchet@50351
   467
            val (bindings, specs) = map generate_coiter_like coiter_like_infos |> split_list;
blanchet@50226
   468
blanchet@50226
   469
            val ((csts, defs), (lthy', lthy)) = no_defs_lthy
blanchet@50225
   470
              |> apfst split_list o fold_map2 (fn b => fn spec =>
blanchet@50225
   471
                Specification.definition (SOME (b, NONE, NoSyn), ((Thm.def_binding b, []), spec))
blanchet@50351
   472
                #>> apsnd snd) bindings specs
blanchet@50225
   473
              ||> `Local_Theory.restore;
blanchet@50225
   474
blanchet@50225
   475
            val phi = Proof_Context.export_morphism lthy lthy';
blanchet@50225
   476
blanchet@50226
   477
            val [coiter_def, corec_def] = map (Morphism.thm phi) defs;
blanchet@50225
   478
blanchet@50226
   479
            val [coiter, corec] = map (mk_iter_like As Cs o Morphism.term phi) csts;
blanchet@50225
   480
          in
blanchet@50385
   481
            ((ctrs, selss0, coiter, corec, xss, ctr_defs, discIs, sel_thmss, coiter_def, corec_def),
blanchet@50385
   482
             lthy)
blanchet@50225
   483
          end;
blanchet@50301
   484
blanchet@50302
   485
        fun wrap lthy =
blanchet@50302
   486
          let val sel_defaultss = map (map (apsnd (prepare_term lthy))) raw_sel_defaultss in
blanchet@50351
   487
            wrap_datatype tacss (((no_dests, ctrs0), casex0), (disc_bindings, (sel_bindingss,
blanchet@50302
   488
              sel_defaultss))) lthy
blanchet@50302
   489
          end;
blanchet@50302
   490
blanchet@50302
   491
        val define_iter_likes = if lfp then define_iter_rec else define_coiter_corec;
blanchet@50134
   492
      in
blanchet@50302
   493
        ((wrap, define_iter_likes), lthy')
blanchet@50134
   494
      end;
blanchet@50182
   495
blanchet@50241
   496
    val pre_map_defs = map map_def_of_bnf pre_bnfs;
blanchet@50357
   497
    val pre_set_defss = map set_defs_of_bnf pre_bnfs;
blanchet@50383
   498
    val nested_set_natural's = maps set_natural'_of_bnf nested_bnfs;
blanchet@50378
   499
    val nesting_map_ids = map map_id_of_bnf nesting_bnfs;
blanchet@50241
   500
blanchet@50408
   501
    fun mk_map live Ts Us t =
blanchet@50441
   502
      let
blanchet@50441
   503
        val (Type (_, Ts0), Type (_, Us0)) = strip_typeN (live + 1) (fastype_of t) |>> List.last
blanchet@50441
   504
      in
blanchet@50229
   505
        Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) t
blanchet@50229
   506
      end;
blanchet@50229
   507
blanchet@50396
   508
    fun build_map build_arg (T as Type (s, Ts)) (U as Type (_, Us)) =
blanchet@50249
   509
      let
blanchet@50407
   510
        val bnf = the (bnf_of lthy s);
blanchet@50408
   511
        val live = live_of_bnf bnf;
blanchet@50408
   512
        val mapx = mk_map live Ts Us (map_of_bnf bnf);
blanchet@50408
   513
        val TUs = map dest_funT (fst (strip_typeN live (fastype_of mapx)));
blanchet@50249
   514
        val args = map build_arg TUs;
blanchet@50249
   515
      in Term.list_comb (mapx, args) end;
blanchet@50249
   516
blanchet@50385
   517
    fun derive_induct_iter_rec_thms_for_types ((ctrss, _, iters, recs, xsss, ctr_defss, _, _,
blanchet@50352
   518
        iter_defs, rec_defs), lthy) =
blanchet@50217
   519
      let
blanchet@50385
   520
        val (((phis, phis'), vs'), names_lthy) =
blanchet@50385
   521
          lthy
blanchet@50385
   522
          |> mk_Frees' "P" (map mk_predT fpTs)
blanchet@50385
   523
          ||>> Variable.variant_fixes (map Binding.name_of fp_bs);
blanchet@50385
   524
blanchet@50385
   525
        val vs = map2 (curry Free) vs' fpTs;
blanchet@50385
   526
blanchet@50377
   527
        fun mk_sets_nested bnf =
blanchet@50377
   528
          let
blanchet@50377
   529
            val Type (T_name, Us) = T_of_bnf bnf;
blanchet@50377
   530
            val lives = lives_of_bnf bnf;
blanchet@50377
   531
            val sets = sets_of_bnf bnf;
blanchet@50377
   532
            fun mk_set U =
blanchet@50377
   533
              (case find_index (curry (op =) U) lives of
blanchet@50377
   534
                ~1 => Term.dummy
blanchet@50377
   535
              | i => nth sets i);
blanchet@50377
   536
          in
blanchet@50377
   537
            (T_name, map mk_set Us)
blanchet@50377
   538
          end;
blanchet@50377
   539
blanchet@50377
   540
        val setss_nested = map mk_sets_nested nested_bnfs;
blanchet@50377
   541
blanchet@50352
   542
        val (induct_thms, induct_thm) =
blanchet@50352
   543
          let
blanchet@50377
   544
            fun mk_set Ts t =
blanchet@50377
   545
              let val Type (_, Ts0) = domain_type (fastype_of t) in
blanchet@50377
   546
                Term.subst_atomic_types (Ts0 ~~ Ts) t
blanchet@50377
   547
              end;
blanchet@50377
   548
blanchet@50390
   549
            fun mk_raw_prem_prems names_lthy (x as Free (s, T as Type (T_name, Ts0))) =
blanchet@50376
   550
                (case find_index (curry (op =) T) fpTs of
blanchet@50377
   551
                  ~1 =>
blanchet@50377
   552
                  (case AList.lookup (op =) setss_nested T_name of
blanchet@50377
   553
                    NONE => []
blanchet@50377
   554
                  | SOME raw_sets0 =>
blanchet@50377
   555
                    let
blanchet@50377
   556
                      val (Ts, raw_sets) =
blanchet@50377
   557
                        split_list (filter (exists_fp_subtype o fst) (Ts0 ~~ raw_sets0));
blanchet@50377
   558
                      val sets = map (mk_set Ts0) raw_sets;
blanchet@50377
   559
                      val (ys, names_lthy') = names_lthy |> mk_Frees s Ts;
blanchet@50390
   560
                      val xysets = map (pair x) (ys ~~ sets);
blanchet@50390
   561
                      val ppremss = map (mk_raw_prem_prems names_lthy') ys;
blanchet@50377
   562
                    in
blanchet@50390
   563
                      flat (map2 (map o apfst o cons) xysets ppremss)
blanchet@50377
   564
                    end)
blanchet@50391
   565
                | i => [([], (i + 1, x))])
blanchet@50390
   566
              | mk_raw_prem_prems _ _ = [];
blanchet@50357
   567
blanchet@50393
   568
            fun close_prem_prem xs t =
blanchet@50393
   569
              fold_rev Logic.all (map Free (drop (nn + length xs)
blanchet@50393
   570
                (rev (Term.add_frees t (map dest_Free xs @ phis'))))) t;
blanchet@50377
   571
blanchet@50393
   572
            fun mk_prem_prem xs (xysets, (j, x)) =
blanchet@50393
   573
              close_prem_prem xs (Logic.list_implies (map (fn (x', (y, set)) =>
blanchet@50391
   574
                  HOLogic.mk_Trueprop (HOLogic.mk_mem (y, set $ x'))) xysets,
blanchet@50391
   575
                HOLogic.mk_Trueprop (nth phis (j - 1) $ x)));
blanchet@50390
   576
blanchet@50387
   577
            fun mk_raw_prem phi ctr ctr_Ts =
blanchet@50377
   578
              let
blanchet@50377
   579
                val (xs, names_lthy') = names_lthy |> mk_Frees "x" ctr_Ts;
blanchet@50391
   580
                val pprems = maps (mk_raw_prem_prems names_lthy') xs;
blanchet@50393
   581
              in (xs, pprems, HOLogic.mk_Trueprop (phi $ Term.list_comb (ctr, xs))) end;
blanchet@50357
   582
blanchet@50391
   583
            fun mk_prem (xs, raw_pprems, concl) =
blanchet@50393
   584
              fold_rev Logic.all xs (Logic.list_implies (map (mk_prem_prem xs) raw_pprems, concl));
blanchet@50383
   585
blanchet@50404
   586
            val raw_premss = map3 (map2 o mk_raw_prem) phis ctrss ctr_Tsss;
blanchet@50404
   587
blanchet@50376
   588
            val goal =
blanchet@50387
   589
              Library.foldr (Logic.list_implies o apfst (map mk_prem)) (raw_premss,
blanchet@50383
   590
                HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj
blanchet@50383
   591
                  (map2 (curry (op $)) phis vs)));
blanchet@50383
   592
blanchet@50392
   593
            fun mk_raw_prem_prems_indices pprems =
blanchet@50391
   594
              let
blanchet@50392
   595
                fun has_index kk (_, (kk', _)) = kk' = kk;
blanchet@50392
   596
                val buckets = Library.partition_list has_index 1 nn pprems;
blanchet@50392
   597
                val pps = map length buckets;
blanchet@50391
   598
              in
blanchet@50393
   599
                map (fn pprem as (xysets, (kk, _)) =>
blanchet@50392
   600
                  ((nth pps (kk - 1), find_index (curry (op =) pprem) (nth buckets (kk - 1)) + 1),
blanchet@50393
   601
                   (length xysets, kk))) pprems
blanchet@50391
   602
              end;
blanchet@50391
   603
blanchet@50404
   604
            val ppjjqqkksss = map (map (mk_raw_prem_prems_indices o #2)) raw_premss;
blanchet@50442
   605
val _ = tracing ("val ppjjqqkksss = " ^ PolyML.makestring ppjjqqkksss) (*###*)
blanchet@50383
   606
blanchet@50383
   607
            val fld_induct' = fp_induct OF (map mk_sumEN_tupled_balanced mss);
blanchet@50357
   608
blanchet@50357
   609
            val induct_thm =
blanchet@50376
   610
              Skip_Proof.prove lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@50404
   611
                mk_induct_tac ctxt ns mss ppjjqqkksss (flat ctr_defss) fld_induct'
blanchet@50404
   612
                  nested_set_natural's pre_set_defss)
blanchet@50383
   613
              |> singleton (Proof_Context.export names_lthy lthy)
blanchet@50352
   614
          in
blanchet@50382
   615
            `(conj_dests nn) induct_thm
blanchet@50352
   616
          end;
blanchet@50216
   617
blanchet@50217
   618
        val (iter_thmss, rec_thmss) =
blanchet@50222
   619
          let
blanchet@50352
   620
            val xctrss = map2 (map2 (curry Term.list_comb)) ctrss xsss;
blanchet@50352
   621
            val giters = map (lists_bmoc gss) iters;
blanchet@50352
   622
            val hrecs = map (lists_bmoc hss) recs;
blanchet@50352
   623
blanchet@50227
   624
            fun mk_goal_iter_like fss fiter_like xctr f xs fxs =
blanchet@50222
   625
              fold_rev (fold_rev Logic.all) (xs :: fss)
blanchet@50227
   626
                (mk_Trueprop_eq (fiter_like $ xctr, Term.list_comb (f, fxs)));
blanchet@50216
   627
blanchet@50249
   628
            fun build_call fiter_likes maybe_tick (T, U) =
blanchet@50249
   629
              if T = U then
blanchet@50383
   630
                id_const T
blanchet@50249
   631
              else
blanchet@50249
   632
                (case find_index (curry (op =) T) fpTs of
blanchet@50249
   633
                  ~1 => build_map (build_call fiter_likes maybe_tick) T U
blanchet@50249
   634
                | j => maybe_tick (nth vs j) (nth fiter_likes j));
blanchet@50248
   635
blanchet@50289
   636
            fun mk_U maybe_mk_prodT =
blanchet@50289
   637
              typ_subst (map2 (fn fpT => fn C => (fpT, maybe_mk_prodT fpT C)) fpTs Cs);
blanchet@50229
   638
blanchet@50357
   639
            fun intr_calls fiter_likes maybe_cons maybe_tick maybe_mk_prodT (x as Free (_, T)) =
blanchet@50229
   640
              if member (op =) fpTs T then
blanchet@50248
   641
                maybe_cons x [build_call fiter_likes (K I) (T, mk_U (K I) T) $ x]
blanchet@50377
   642
              else if exists_fp_subtype T then
blanchet@50289
   643
                [build_call fiter_likes maybe_tick (T, mk_U maybe_mk_prodT T) $ x]
blanchet@50229
   644
              else
blanchet@50229
   645
                [x];
blanchet@50229
   646
blanchet@50357
   647
            val gxsss = map (map (maps (intr_calls giters (K I) (K I) (K I)))) xsss;
blanchet@50357
   648
            val hxsss = map (map (maps (intr_calls hrecs cons tick (curry HOLogic.mk_prodT)))) xsss;
blanchet@50219
   649
blanchet@50227
   650
            val goal_iterss = map5 (map4 o mk_goal_iter_like gss) giters xctrss gss xsss gxsss;
blanchet@50227
   651
            val goal_recss = map5 (map4 o mk_goal_iter_like hss) hrecs xctrss hss xsss hxsss;
blanchet@50219
   652
blanchet@50218
   653
            val iter_tacss =
blanchet@50378
   654
              map2 (map o mk_iter_like_tac pre_map_defs nesting_map_ids iter_defs) fp_iter_thms
blanchet@50378
   655
                ctr_defss;
blanchet@50218
   656
            val rec_tacss =
blanchet@50378
   657
              map2 (map o mk_iter_like_tac pre_map_defs nesting_map_ids rec_defs) fp_rec_thms
blanchet@50378
   658
                ctr_defss;
blanchet@50217
   659
          in
blanchet@50291
   660
            (map2 (map2 (fn goal => fn tac => Skip_Proof.prove lthy [] [] goal (tac o #context)))
blanchet@50220
   661
               goal_iterss iter_tacss,
blanchet@50291
   662
             map2 (map2 (fn goal => fn tac => Skip_Proof.prove lthy [] [] goal (tac o #context)))
blanchet@50220
   663
               goal_recss rec_tacss)
blanchet@50217
   664
          end;
blanchet@50216
   665
blanchet@50352
   666
        val common_notes =
blanchet@50382
   667
          (if nn > 1 then [(inductN, [induct_thm], [])] (* FIXME: attribs *) else [])
blanchet@50352
   668
          |> map (fn (thmN, thms, attrs) =>
blanchet@50352
   669
              ((Binding.qualify true fp_common_name (Binding.name thmN), attrs), [(thms, [])]));
blanchet@50352
   670
blanchet@50241
   671
        val notes =
blanchet@50357
   672
          [(inductN, map single induct_thms, []), (* FIXME: attribs *)
blanchet@50357
   673
           (itersN, iter_thmss, simp_attrs),
blanchet@50315
   674
           (recsN, rec_thmss, Code.add_default_eqn_attrib :: simp_attrs)]
blanchet@50315
   675
          |> maps (fn (thmN, thmss, attrs) =>
blanchet@50217
   676
            map2 (fn b => fn thms =>
blanchet@50315
   677
              ((Binding.qualify true (Binding.name_of b) (Binding.name thmN), attrs),
blanchet@50317
   678
                [(thms, [])])) fp_bs thmss);
blanchet@50217
   679
      in
blanchet@50352
   680
        lthy |> Local_Theory.notes (common_notes @ notes) |> snd
blanchet@50217
   681
      end;
blanchet@50217
   682
blanchet@50385
   683
    fun derive_coinduct_coiter_corec_thms_for_types ((ctrss, selsss, coiters, corecs, _, ctr_defss,
blanchet@50385
   684
        discIss, sel_thmsss, coiter_defs, corec_defs), lthy) =
blanchet@50227
   685
      let
blanchet@50387
   686
        val (vs', _) =
blanchet@50385
   687
          lthy
blanchet@50385
   688
          |> Variable.variant_fixes (map Binding.name_of fp_bs);
blanchet@50385
   689
blanchet@50385
   690
        val vs = map2 (curry Free) vs' fpTs;
blanchet@50385
   691
blanchet@50352
   692
        val (coinduct_thms, coinduct_thm) =
blanchet@50352
   693
          let
blanchet@50352
   694
            val coinduct_thm = fp_induct;
blanchet@50352
   695
          in
blanchet@50382
   696
            `(conj_dests nn) coinduct_thm
blanchet@50352
   697
          end;
blanchet@50227
   698
blanchet@50227
   699
        val (coiter_thmss, corec_thmss) =
blanchet@50227
   700
          let
blanchet@50352
   701
            val z = the_single zs;
blanchet@50352
   702
            val gcoiters = map (lists_bmoc pgss) coiters;
blanchet@50352
   703
            val hcorecs = map (lists_bmoc phss) corecs;
blanchet@50352
   704
blanchet@50247
   705
            fun mk_goal_cond pos = HOLogic.mk_Trueprop o (not pos ? HOLogic.mk_not);
blanchet@50227
   706
blanchet@50291
   707
            fun mk_goal_coiter_like pfss c cps fcoiter_like n k ctr m cfs' =
blanchet@50227
   708
              fold_rev (fold_rev Logic.all) ([c] :: pfss)
blanchet@50247
   709
                (Logic.list_implies (seq_conds mk_goal_cond n k cps,
blanchet@50291
   710
                   mk_Trueprop_eq (fcoiter_like $ c, Term.list_comb (ctr, take m cfs'))));
blanchet@50227
   711
blanchet@50249
   712
            fun build_call fiter_likes maybe_tack (T, U) =
blanchet@50249
   713
              if T = U then
blanchet@50383
   714
                id_const T
blanchet@50249
   715
              else
blanchet@50249
   716
                (case find_index (curry (op =) U) fpTs of
blanchet@50249
   717
                  ~1 => build_map (build_call fiter_likes maybe_tack) T U
blanchet@50249
   718
                | j => maybe_tack (nth cs j, nth vs j) (nth fiter_likes j));
blanchet@50248
   719
blanchet@50289
   720
            fun mk_U maybe_mk_sumT =
blanchet@50289
   721
              typ_subst (map2 (fn C => fn fpT => (maybe_mk_sumT fpT C, fpT)) Cs fpTs);
blanchet@50227
   722
blanchet@50357
   723
            fun intr_calls fiter_likes maybe_mk_sumT maybe_tack cqf =
blanchet@50291
   724
              let val T = fastype_of cqf in
blanchet@50291
   725
                if exists_subtype (member (op =) Cs) T then
blanchet@50291
   726
                  build_call fiter_likes maybe_tack (T, mk_U maybe_mk_sumT T) $ cqf
blanchet@50291
   727
                else
blanchet@50291
   728
                  cqf
blanchet@50291
   729
              end;
blanchet@50247
   730
blanchet@50357
   731
            val crgsss' = map (map (map (intr_calls gcoiters (K I) (K I)))) crgsss;
blanchet@50357
   732
            val cshsss' = map (map (map (intr_calls hcorecs (curry mk_sumT) (tack z)))) cshsss;
blanchet@50227
   733
blanchet@50227
   734
            val goal_coiterss =
blanchet@50291
   735
              map8 (map4 oooo mk_goal_coiter_like pgss) cs cpss gcoiters ns kss ctrss mss crgsss';
blanchet@50248
   736
            val goal_corecss =
blanchet@50291
   737
              map8 (map4 oooo mk_goal_coiter_like phss) cs cpss hcorecs ns kss ctrss mss cshsss';
blanchet@50228
   738
blanchet@50228
   739
            val coiter_tacss =
blanchet@50378
   740
              map3 (map oo mk_coiter_like_tac coiter_defs nesting_map_ids) fp_iter_thms pre_map_defs
blanchet@50241
   741
                ctr_defss;
blanchet@50248
   742
            val corec_tacss =
blanchet@50378
   743
              map3 (map oo mk_coiter_like_tac corec_defs nesting_map_ids) fp_rec_thms pre_map_defs
blanchet@50248
   744
                ctr_defss;
blanchet@50227
   745
          in
blanchet@50291
   746
            (map2 (map2 (fn goal => fn tac =>
blanchet@50291
   747
                 Skip_Proof.prove lthy [] [] goal (tac o #context) |> Thm.close_derivation))
blanchet@50228
   748
               goal_coiterss coiter_tacss,
blanchet@50291
   749
             map2 (map2 (fn goal => fn tac =>
blanchet@50291
   750
                 Skip_Proof.prove lthy [] [] goal (tac o #context)
blanchet@50291
   751
                 |> Local_Defs.unfold lthy @{thms sum_case_if} |> Thm.close_derivation))
blanchet@50248
   752
               goal_corecss corec_tacss)
blanchet@50227
   753
          end;
blanchet@50227
   754
blanchet@50281
   755
        fun mk_disc_coiter_like_thms [_] = K []
blanchet@50281
   756
          | mk_disc_coiter_like_thms thms = map2 (curry (op RS)) thms;
blanchet@50281
   757
blanchet@50281
   758
        val disc_coiter_thmss = map2 mk_disc_coiter_like_thms coiter_thmss discIss;
blanchet@50281
   759
        val disc_corec_thmss = map2 mk_disc_coiter_like_thms corec_thmss discIss;
blanchet@50281
   760
blanchet@50282
   761
        fun mk_sel_coiter_like_thm coiter_like_thm sel0 sel_thm =
blanchet@50281
   762
          let
blanchet@50282
   763
            val (domT, ranT) = dest_funT (fastype_of sel0);
blanchet@50281
   764
            val arg_cong' =
blanchet@50281
   765
              Drule.instantiate' (map (SOME o certifyT lthy) [domT, ranT])
blanchet@50282
   766
                [NONE, NONE, SOME (certify lthy sel0)] arg_cong
blanchet@50282
   767
              |> Thm.varifyT_global;
blanchet@50281
   768
            val sel_thm' = sel_thm RSN (2, trans);
blanchet@50281
   769
          in
blanchet@50282
   770
            coiter_like_thm RS arg_cong' RS sel_thm'
blanchet@50281
   771
          end;
blanchet@50281
   772
blanchet@50281
   773
        val sel_coiter_thmsss =
blanchet@50281
   774
          map3 (map3 (map2 o mk_sel_coiter_like_thm)) coiter_thmss selsss sel_thmsss;
blanchet@50281
   775
        val sel_corec_thmsss =
blanchet@50282
   776
          map3 (map3 (map2 o mk_sel_coiter_like_thm)) corec_thmss selsss sel_thmsss;
blanchet@50281
   777
blanchet@50357
   778
        val common_notes =
blanchet@50382
   779
          (if nn > 1 then [(coinductN, [coinduct_thm], [])] (* FIXME: attribs *) else [])
blanchet@50357
   780
          |> map (fn (thmN, thms, attrs) =>
blanchet@50357
   781
              ((Binding.qualify true fp_common_name (Binding.name thmN), attrs), [(thms, [])]));
blanchet@50357
   782
blanchet@50227
   783
        val notes =
blanchet@50357
   784
          [(coinductN, map single coinduct_thms, []), (* FIXME: attribs *)
blanchet@50357
   785
           (coitersN, coiter_thmss, []),
blanchet@50315
   786
           (disc_coitersN, disc_coiter_thmss, []),
blanchet@50315
   787
           (sel_coitersN, map flat sel_coiter_thmsss, []),
blanchet@50315
   788
           (corecsN, corec_thmss, []),
blanchet@50315
   789
           (disc_corecsN, disc_corec_thmss, []),
blanchet@50315
   790
           (sel_corecsN, map flat sel_corec_thmsss, [])]
blanchet@50315
   791
          |> maps (fn (thmN, thmss, attrs) =>
blanchet@50281
   792
            map_filter (fn (_, []) => NONE | (b, thms) =>
blanchet@50315
   793
              SOME ((Binding.qualify true (Binding.name_of b) (Binding.name thmN), attrs),
blanchet@50317
   794
                [(thms, [])])) (fp_bs ~~ thmss));
blanchet@50227
   795
      in
blanchet@50376
   796
        lthy |> Local_Theory.notes (common_notes @ notes) |> snd
blanchet@50227
   797
      end;
blanchet@50227
   798
blanchet@50302
   799
    fun wrap_types_and_define_iter_likes ((wraps, define_iter_likess), lthy) =
blanchet@50385
   800
      fold_map2 (curry (op o)) define_iter_likess wraps lthy |>> split_list10
blanchet@50302
   801
blanchet@50219
   802
    val lthy' = lthy
blanchet@50385
   803
      |> fold_map define_ctrs_case_for_type (fp_bs ~~ fpTs ~~ Cs ~~ flds ~~ unfs ~~ fp_iters ~~
blanchet@50385
   804
        fp_recs ~~ fld_unfs ~~ unf_flds ~~ fld_injects ~~ ns ~~ kss ~~ mss ~~ ctr_bindingss ~~
blanchet@50385
   805
        ctr_mixfixess ~~ ctr_Tsss ~~ disc_bindingss ~~ sel_bindingsss ~~ raw_sel_defaultsss)
blanchet@50302
   806
      |>> split_list |> wrap_types_and_define_iter_likes
blanchet@50352
   807
      |> (if lfp then derive_induct_iter_rec_thms_for_types
blanchet@50352
   808
          else derive_coinduct_coiter_corec_thms_for_types);
blanchet@50182
   809
blanchet@50182
   810
    val timer = time (timer ("Constructors, discriminators, selectors, etc., for the new " ^
blanchet@50223
   811
      (if lfp then "" else "co") ^ "datatype"));
blanchet@50127
   812
  in
blanchet@50323
   813
    timer; lthy'
blanchet@50127
   814
  end;
blanchet@50127
   815
blanchet@50313
   816
val datatyp = define_datatype (K I) (K I) (K I);
blanchet@50312
   817
blanchet@50313
   818
val datatype_cmd = define_datatype Typedecl.read_constraint Syntax.parse_typ Syntax.read_term;
blanchet@50134
   819
blanchet@50344
   820
val parse_binding_colon = Parse.binding --| @{keyword ":"};
blanchet@50351
   821
val parse_opt_binding_colon = Scan.optional parse_binding_colon no_binding;
blanchet@50134
   822
blanchet@50127
   823
val parse_ctr_arg =
blanchet@50344
   824
  @{keyword "("} |-- parse_binding_colon -- Parse.typ --| @{keyword ")"} ||
blanchet@50351
   825
  (Parse.typ >> pair no_binding);
blanchet@50127
   826
blanchet@50301
   827
val parse_defaults =
blanchet@50301
   828
  @{keyword "("} |-- @{keyword "defaults"} |-- Scan.repeat parse_bound_term --| @{keyword ")"};
blanchet@50301
   829
blanchet@50127
   830
val parse_single_spec =
blanchet@50127
   831
  Parse.type_args_constrained -- Parse.binding -- Parse.opt_mixfix --
blanchet@50134
   832
  (@{keyword "="} |-- Parse.enum1 "|" (parse_opt_binding_colon -- Parse.binding --
blanchet@50301
   833
    Scan.repeat parse_ctr_arg -- Scan.optional parse_defaults [] -- Parse.opt_mixfix));
blanchet@50127
   834
blanchet@50293
   835
val parse_datatype = parse_wrap_options -- Parse.and_list1 parse_single_spec;
blanchet@50293
   836
blanchet@50323
   837
fun parse_datatype_cmd lfp construct = parse_datatype >> datatype_cmd lfp construct;
blanchet@50127
   838
blanchet@50127
   839
end;