src/HOL/BNF/Tools/bnf_fp_sugar.ML
author blanchet
Sun Sep 23 14:52:53 2012 +0200 (2012-09-23)
changeset 49536 898aea2e7a94
parent 49518 b377da40244b
child 49540 b1bdbb099f99
permissions -rw-r--r--
started work on generation of "rel" theorems
blanchet@49509
     1
(*  Title:      HOL/BNF/Tools/bnf_fp_sugar.ML
blanchet@49112
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@49112
     3
    Copyright   2012
blanchet@49112
     4
blanchet@49389
     5
Sugared datatype and codatatype constructions.
blanchet@49112
     6
*)
blanchet@49112
     7
blanchet@49112
     8
signature BNF_FP_SUGAR =
blanchet@49112
     9
sig
blanchet@49536
    10
  val datatypes: bool ->
blanchet@49308
    11
    (mixfix list -> (string * sort) list option -> binding list -> typ list * typ list list ->
blanchet@49308
    12
      BNF_Def.BNF list -> local_theory ->
blanchet@49536
    13
      (term list * term list * term list *term list * term list * thm * thm list * thm list *
blanchet@49536
    14
         thm list * thm list * thm list) * local_theory) ->
blanchet@49298
    15
    bool * ((((typ * sort) list * binding) * mixfix) * ((((binding * binding) *
blanchet@49297
    16
      (binding * typ) list) * (binding * term) list) * mixfix) list) list ->
blanchet@49297
    17
    local_theory -> local_theory
blanchet@49308
    18
  val parse_datatype_cmd: bool ->
blanchet@49308
    19
    (mixfix list -> (string * sort) list option -> binding list -> typ list * typ list list ->
blanchet@49308
    20
      BNF_Def.BNF list -> local_theory ->
blanchet@49536
    21
      (term list * term list * term list * term list * term list * thm * thm list * thm list *
blanchet@49536
    22
         thm list * thm list * thm list) * local_theory) ->
blanchet@49308
    23
    (local_theory -> local_theory) parser
blanchet@49112
    24
end;
blanchet@49112
    25
blanchet@49112
    26
structure BNF_FP_Sugar : BNF_FP_SUGAR =
blanchet@49112
    27
struct
blanchet@49112
    28
blanchet@49119
    29
open BNF_Util
blanchet@49119
    30
open BNF_Wrap
blanchet@49214
    31
open BNF_Def
blanchet@49457
    32
open BNF_FP
blanchet@49123
    33
open BNF_FP_Sugar_Tactics
blanchet@49119
    34
blanchet@49300
    35
val simp_attrs = @{attributes [simp]};
blanchet@49300
    36
blanchet@49536
    37
fun split_list9 xs =
blanchet@49536
    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@49536
    39
   map #9 xs);
blanchet@49214
    40
blanchet@49342
    41
fun resort_tfree S (TFree (s, _)) = TFree (s, S);
blanchet@49342
    42
blanchet@49214
    43
fun typ_subst inst (T as Type (s, Ts)) =
blanchet@49214
    44
    (case AList.lookup (op =) inst T of
blanchet@49214
    45
      NONE => Type (s, map (typ_subst inst) Ts)
blanchet@49214
    46
    | SOME T' => T')
blanchet@49214
    47
  | typ_subst inst T = the_default T (AList.lookup (op =) inst T);
blanchet@49205
    48
blanchet@49297
    49
val lists_bmoc = fold (fn xs => fn t => Term.list_comb (t, xs));
blanchet@49202
    50
blanchet@49200
    51
fun mk_tupled_fun x f xs = HOLogic.tupled_lambda x (Term.list_comb (f, xs));
blanchet@49200
    52
fun mk_uncurried_fun f xs = mk_tupled_fun (HOLogic.mk_tuple xs) f xs;
blanchet@49202
    53
fun mk_uncurried2_fun f xss =
blanchet@49200
    54
  mk_tupled_fun (HOLogic.mk_tuple (map HOLogic.mk_tuple xss)) f (flat xss);
blanchet@49200
    55
blanchet@49536
    56
fun mk_ctor_or_dtor get_T Ts t =
blanchet@49536
    57
  let val Type (_, Ts0) = get_T (fastype_of t) in
blanchet@49536
    58
    Term.subst_atomic_types (Ts0 ~~ Ts) t
blanchet@49536
    59
  end;
blanchet@49536
    60
blanchet@49536
    61
val mk_ctor = mk_ctor_or_dtor range_type;
blanchet@49536
    62
val mk_dtor = mk_ctor_or_dtor domain_type;
blanchet@49536
    63
blanchet@49536
    64
fun mk_rec_like lfp Ts Us t =
blanchet@49536
    65
  let
blanchet@49536
    66
    val (bindings, body) = strip_type (fastype_of t);
blanchet@49536
    67
    val (f_Us, prebody) = split_last bindings;
blanchet@49536
    68
    val Type (_, Ts0) = if lfp then prebody else body;
blanchet@49536
    69
    val Us0 = distinct (op =) (map (if lfp then body_type else domain_type) f_Us);
blanchet@49536
    70
  in
blanchet@49536
    71
    Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) t
blanchet@49536
    72
  end;
blanchet@49536
    73
blanchet@49536
    74
fun mk_map live Ts Us t =
blanchet@49536
    75
  let val (Type (_, Ts0), Type (_, Us0)) = strip_typeN (live + 1) (fastype_of t) |>> List.last in
blanchet@49536
    76
    Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) t
blanchet@49536
    77
  end;
blanchet@49536
    78
blanchet@49536
    79
fun mk_rel Ts Us t =
blanchet@49536
    80
  let
blanchet@49536
    81
    val ((Type (_, Ts0), Type (_, Us0)), body) =
blanchet@49536
    82
      strip_type (fastype_of t) |>> split_last |>> apfst List.last;
blanchet@49536
    83
val _ = tracing ("*** " ^ PolyML.makestring (Ts, "***", Us, "***", t, Ts0, Us0)) (*###*)
blanchet@49536
    84
  in
blanchet@49536
    85
    Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) t
blanchet@49536
    86
  end;
blanchet@49536
    87
blanchet@49498
    88
fun tick u f = Term.lambda u (HOLogic.mk_prod (u, f $ u));
blanchet@49233
    89
blanchet@49498
    90
fun tack z_name (c, u) f =
blanchet@49498
    91
  let val z = Free (z_name, mk_sumT (fastype_of u, fastype_of c)) in
blanchet@49498
    92
    Term.lambda z (mk_sum_case (Term.lambda u u, Term.lambda c (f $ c)) $ z)
blanchet@49273
    93
  end;
blanchet@49214
    94
blanchet@49124
    95
fun cannot_merge_types () = error "Mutually recursive types must have the same type parameters";
blanchet@49119
    96
blanchet@49298
    97
fun merge_type_arg T T' = if T = T' then T else cannot_merge_types ();
blanchet@49119
    98
blanchet@49298
    99
fun merge_type_args (As, As') =
blanchet@49298
   100
  if length As = length As' then map2 merge_type_arg As As' else cannot_merge_types ();
blanchet@49119
   101
blanchet@49479
   102
fun is_triv_implies thm =
blanchet@49479
   103
  op aconv (Logic.dest_implies (Thm.prop_of thm))
blanchet@49479
   104
  handle TERM _ => false;
blanchet@49479
   105
blanchet@49121
   106
fun type_args_constrained_of (((cAs, _), _), _) = cAs;
blanchet@49336
   107
fun type_binding_of (((_, b), _), _) = b;
blanchet@49181
   108
fun mixfix_of ((_, mx), _) = mx;
blanchet@49121
   109
fun ctr_specs_of (_, ctr_specs) = ctr_specs;
blanchet@49119
   110
blanchet@49286
   111
fun disc_of ((((disc, _), _), _), _) = disc;
blanchet@49286
   112
fun ctr_of ((((_, ctr), _), _), _) = ctr;
blanchet@49286
   113
fun args_of (((_, args), _), _) = args;
blanchet@49286
   114
fun defaults_of ((_, ds), _) = ds;
blanchet@49181
   115
fun ctr_mixfix_of (_, mx) = mx;
blanchet@49119
   116
blanchet@49536
   117
fun define_datatypes prepare_constraint prepare_typ prepare_term lfp construct (no_dests, specs)
blanchet@49298
   118
    no_defs_lthy0 =
blanchet@49112
   119
  let
blanchet@49298
   120
    (* TODO: sanity checks on arguments *)
blanchet@49478
   121
    (* TODO: integration with function package ("size") *)
blanchet@49298
   122
blanchet@49286
   123
    val _ = if not lfp andalso no_dests then error "Cannot define destructor-less codatatypes"
blanchet@49278
   124
      else ();
blanchet@49278
   125
blanchet@49367
   126
    val nn = length specs;
blanchet@49361
   127
    val fp_bs = map type_binding_of specs;
blanchet@49498
   128
    val fp_b_names = map Binding.name_of fp_bs;
blanchet@49498
   129
    val fp_common_name = mk_common_name fp_b_names;
blanchet@49298
   130
blanchet@49298
   131
    fun prepare_type_arg (ty, c) =
blanchet@49298
   132
      let val TFree (s, _) = prepare_typ no_defs_lthy0 ty in
blanchet@49298
   133
        TFree (s, prepare_constraint no_defs_lthy0 c)
blanchet@49298
   134
      end;
blanchet@49298
   135
blanchet@49298
   136
    val Ass0 = map (map prepare_type_arg o type_args_constrained_of) specs;
blanchet@49298
   137
    val unsorted_Ass0 = map (map (resort_tfree HOLogic.typeS)) Ass0;
blanchet@49298
   138
    val unsorted_As = Library.foldr1 merge_type_args unsorted_Ass0;
blanchet@49119
   139
blanchet@49536
   140
    val ((Xs, Cs), no_defs_lthy) =
blanchet@49298
   141
      no_defs_lthy0
blanchet@49298
   142
      |> fold (Variable.declare_typ o resort_tfree dummyS) unsorted_As
blanchet@49367
   143
      |> mk_TFrees nn
blanchet@49370
   144
      ||>> mk_TFrees nn;
blanchet@49119
   145
blanchet@49298
   146
    (* TODO: cleaner handling of fake contexts, without "background_theory" *)
blanchet@49298
   147
    (*the "perhaps o try" below helps gracefully handles the case where the new type is defined in a
blanchet@49298
   148
      locale and shadows an existing global type*)
blanchet@49298
   149
    val fake_thy =
blanchet@49298
   150
      Theory.copy #> fold (fn spec => perhaps (try (Sign.add_type no_defs_lthy
blanchet@49336
   151
        (type_binding_of spec, length (type_args_constrained_of spec), mixfix_of spec)))) specs;
blanchet@49298
   152
    val fake_lthy = Proof_Context.background_theory fake_thy no_defs_lthy;
blanchet@49119
   153
blanchet@49182
   154
    fun mk_fake_T b =
blanchet@49121
   155
      Type (fst (Term.dest_Type (Proof_Context.read_type_name fake_lthy true (Binding.name_of b))),
blanchet@49298
   156
        unsorted_As);
blanchet@49121
   157
blanchet@49302
   158
    val fake_Ts = map mk_fake_T fp_bs;
blanchet@49121
   159
blanchet@49181
   160
    val mixfixes = map mixfix_of specs;
blanchet@49119
   161
blanchet@49302
   162
    val _ = (case duplicates Binding.eq_name fp_bs of [] => ()
blanchet@49119
   163
      | b :: _ => error ("Duplicate type name declaration " ^ quote (Binding.name_of b)));
blanchet@49119
   164
blanchet@49121
   165
    val ctr_specss = map ctr_specs_of specs;
blanchet@49119
   166
blanchet@49336
   167
    val disc_bindingss = map (map disc_of) ctr_specss;
blanchet@49336
   168
    val ctr_bindingss =
blanchet@49498
   169
      map2 (fn fp_b_name => map (Binding.qualify false fp_b_name o ctr_of)) fp_b_names ctr_specss;
blanchet@49121
   170
    val ctr_argsss = map (map args_of) ctr_specss;
blanchet@49181
   171
    val ctr_mixfixess = map (map ctr_mixfix_of) ctr_specss;
blanchet@49119
   172
blanchet@49336
   173
    val sel_bindingsss = map (map (map fst)) ctr_argsss;
blanchet@49298
   174
    val fake_ctr_Tsss0 = map (map (map (prepare_typ fake_lthy o snd))) ctr_argsss;
blanchet@49286
   175
    val raw_sel_defaultsss = map (map defaults_of) ctr_specss;
blanchet@49286
   176
blanchet@49308
   177
    val (As :: _) :: fake_ctr_Tsss =
blanchet@49298
   178
      burrow (burrow (Syntax.check_typs fake_lthy)) (Ass0 :: fake_ctr_Tsss0);
blanchet@49298
   179
blanchet@49298
   180
    val _ = (case duplicates (op =) unsorted_As of [] => ()
blanchet@49298
   181
      | A :: _ => error ("Duplicate type parameter " ^
blanchet@49298
   182
          quote (Syntax.string_of_typ no_defs_lthy A)));
blanchet@49298
   183
blanchet@49183
   184
    val rhs_As' = fold (fold (fold Term.add_tfreesT)) fake_ctr_Tsss [];
blanchet@49298
   185
    val _ = (case subtract (op =) (map dest_TFree As) rhs_As' of
blanchet@49165
   186
        [] => ()
blanchet@49342
   187
      | A' :: _ => error ("Extra type variable on right-hand side: " ^
blanchet@49204
   188
          quote (Syntax.string_of_typ no_defs_lthy (TFree A'))));
blanchet@49165
   189
blanchet@49204
   190
    fun eq_fpT (T as Type (s, Us)) (Type (s', Us')) =
blanchet@49146
   191
        s = s' andalso (Us = Us' orelse error ("Illegal occurrence of recursive type " ^
blanchet@49146
   192
          quote (Syntax.string_of_typ fake_lthy T)))
blanchet@49204
   193
      | eq_fpT _ _ = false;
blanchet@49146
   194
blanchet@49204
   195
    fun freeze_fp (T as Type (s, Us)) =
blanchet@49536
   196
        (case find_index (eq_fpT T) fake_Ts of ~1 => Type (s, map freeze_fp Us) | j => nth Xs j)
blanchet@49204
   197
      | freeze_fp T = T;
blanchet@49121
   198
blanchet@49536
   199
    val ctr_TsssXs = map (map (map freeze_fp)) fake_ctr_Tsss;
blanchet@49536
   200
    val ctr_sum_prod_TsXs = map (mk_sumTN_balanced o map HOLogic.mk_tupleT) ctr_TsssXs;
blanchet@49119
   201
blanchet@49298
   202
    val fp_eqs =
blanchet@49536
   203
      map dest_TFree Xs ~~ map (Term.typ_subst_atomic (As ~~ unsorted_As)) ctr_sum_prod_TsXs;
blanchet@49121
   204
blanchet@49536
   205
    val (pre_bnfs, ((dtors0, ctors0, rels0, fp_folds0, fp_recs0, fp_induct, dtor_ctors, ctor_dtors,
blanchet@49504
   206
           ctor_injects, fp_fold_thms, fp_rec_thms), lthy)) =
blanchet@49308
   207
      fp_bnf construct fp_bs mixfixes (map dest_TFree unsorted_As) fp_eqs no_defs_lthy0;
blanchet@49121
   208
blanchet@49363
   209
    fun add_nesty_bnf_names Us =
blanchet@49226
   210
      let
blanchet@49226
   211
        fun add (Type (s, Ts)) ss =
blanchet@49226
   212
            let val (needs, ss') = fold_map add Ts ss in
blanchet@49226
   213
              if exists I needs then (true, insert (op =) s ss') else (false, ss')
blanchet@49226
   214
            end
blanchet@49363
   215
          | add T ss = (member (op =) Us T, ss);
blanchet@49226
   216
      in snd oo add end;
blanchet@49226
   217
blanchet@49363
   218
    fun nesty_bnfs Us =
blanchet@49536
   219
      map_filter (bnf_of lthy) (fold (fold (fold (add_nesty_bnf_names Us))) ctr_TsssXs []);
blanchet@49363
   220
blanchet@49363
   221
    val nesting_bnfs = nesty_bnfs As;
blanchet@49536
   222
    val nested_bnfs = nesty_bnfs Xs;
blanchet@49226
   223
blanchet@49167
   224
    val timer = time (Timer.startRealTimer ());
blanchet@49167
   225
blanchet@49501
   226
    val ctors = map (mk_ctor As) ctors0;
blanchet@49501
   227
    val dtors = map (mk_dtor As) dtors0;
blanchet@49536
   228
    val rels = map (mk_rel As As) rels0; (*FIXME*)
blanchet@49124
   229
blanchet@49501
   230
    val fpTs = map (domain_type o fastype_of) dtors;
blanchet@49362
   231
blanchet@49362
   232
    val exists_fp_subtype = exists_subtype (member (op =) fpTs);
blanchet@49362
   233
blanchet@49536
   234
    val ctr_Tsss = map (map (map (Term.typ_subst_atomic (Xs ~~ fpTs)))) ctr_TsssXs;
blanchet@49203
   235
    val ns = map length ctr_Tsss;
blanchet@49212
   236
    val kss = map (fn n => 1 upto n) ns;
blanchet@49203
   237
    val mss = map (map length) ctr_Tsss;
blanchet@49203
   238
    val Css = map2 replicate ns Cs;
blanchet@49203
   239
blanchet@49536
   240
    val fp_folds as fp_fold1 :: _ = map (mk_rec_like lfp As Cs) fp_folds0;
blanchet@49536
   241
    val fp_recs as fp_rec1 :: _ = map (mk_rec_like lfp As Cs) fp_recs0;
blanchet@49210
   242
blanchet@49504
   243
    val fp_fold_fun_Ts = fst (split_last (binder_types (fastype_of fp_fold1)));
blanchet@49212
   244
    val fp_rec_fun_Ts = fst (split_last (binder_types (fastype_of fp_rec1)));
blanchet@49204
   245
blanchet@49504
   246
    val (((fold_only as (gss, _, _), rec_only as (hss, _, _)),
blanchet@49504
   247
          (zs, cs, cpss, unfold_only as ((pgss, crgsss), _), corec_only as ((phss, cshsss), _))),
blanchet@49484
   248
         names_lthy) =
blanchet@49208
   249
      if lfp then
blanchet@49208
   250
        let
blanchet@49208
   251
          val y_Tsss =
blanchet@49255
   252
            map3 (fn n => fn ms => map2 dest_tupleT ms o dest_sumTN_balanced n o domain_type)
blanchet@49504
   253
              ns mss fp_fold_fun_Ts;
blanchet@49208
   254
          val g_Tss = map2 (map2 (curry (op --->))) y_Tsss Css;
blanchet@49208
   255
blanchet@49484
   256
          val ((gss, ysss), lthy) =
blanchet@49208
   257
            lthy
blanchet@49208
   258
            |> mk_Freess "f" g_Tss
blanchet@49208
   259
            ||>> mk_Freesss "x" y_Tsss;
blanchet@49274
   260
          val yssss = map (map (map single)) ysss;
blanchet@49274
   261
blanchet@49274
   262
          fun dest_rec_prodT (T as Type (@{type_name prod}, Us as [_, U])) =
blanchet@49274
   263
              if member (op =) Cs U then Us else [T]
blanchet@49274
   264
            | dest_rec_prodT T = [T];
blanchet@49204
   265
blanchet@49208
   266
          val z_Tssss =
blanchet@49274
   267
            map3 (fn n => fn ms => map2 (map dest_rec_prodT oo dest_tupleT) ms o
blanchet@49255
   268
              dest_sumTN_balanced n o domain_type) ns mss fp_rec_fun_Ts;
blanchet@49208
   269
          val h_Tss = map2 (map2 (fold_rev (curry (op --->)))) z_Tssss Css;
blanchet@49204
   270
blanchet@49298
   271
          val hss = map2 (map2 retype_free) h_Tss gss;
blanchet@49298
   272
          val zssss_hd = map2 (map2 (map2 (retype_free o hd))) z_Tssss ysss;
blanchet@49484
   273
          val (zssss_tl, lthy) =
blanchet@49208
   274
            lthy
blanchet@49274
   275
            |> mk_Freessss "y" (map (map (map tl)) z_Tssss);
blanchet@49274
   276
          val zssss = map2 (map2 (map2 cons)) zssss_hd zssss_tl;
blanchet@49210
   277
        in
blanchet@49484
   278
          ((((gss, g_Tss, yssss), (hss, h_Tss, zssss)),
blanchet@49484
   279
            ([], [], [], (([], []), ([], [])), (([], []), ([], [])))), lthy)
blanchet@49210
   280
        end
blanchet@49208
   281
      else
blanchet@49210
   282
        let
blanchet@49221
   283
          (*avoid "'a itself" arguments in coiterators and corecursors*)
blanchet@49221
   284
          val mss' =  map (fn [0] => [1] | ms => ms) mss;
blanchet@49221
   285
blanchet@49463
   286
          val p_Tss = map2 (fn n => replicate (Int.max (0, n - 1)) o mk_pred1T) ns Cs;
blanchet@49275
   287
blanchet@49276
   288
          fun zip_predss_getterss qss fss = maps (op @) (qss ~~ fss);
blanchet@49211
   289
blanchet@49276
   290
          fun zip_preds_predsss_gettersss [] [qss] [fss] = zip_predss_getterss qss fss
blanchet@49276
   291
            | zip_preds_predsss_gettersss (p :: ps) (qss :: qsss) (fss :: fsss) =
blanchet@49276
   292
              p :: zip_predss_getterss qss fss @ zip_preds_predsss_gettersss ps qsss fsss;
blanchet@49274
   293
blanchet@49274
   294
          fun mk_types maybe_dest_sumT fun_Ts =
blanchet@49212
   295
            let
blanchet@49212
   296
              val f_sum_prod_Ts = map range_type fun_Ts;
blanchet@49255
   297
              val f_prod_Tss = map2 dest_sumTN_balanced ns f_sum_prod_Ts;
blanchet@49275
   298
              val f_Tssss =
blanchet@49275
   299
                map3 (fn C => map2 (map (map (curry (op -->) C) o maybe_dest_sumT) oo dest_tupleT))
blanchet@49275
   300
                  Cs mss' f_prod_Tss;
blanchet@49275
   301
              val q_Tssss =
blanchet@49463
   302
                map (map (map (fn [_] => [] | [_, C] => [mk_pred1T (domain_type C)]))) f_Tssss;
blanchet@49276
   303
              val pf_Tss = map3 zip_preds_predsss_gettersss p_Tss q_Tssss f_Tssss;
blanchet@49275
   304
            in (q_Tssss, f_sum_prod_Ts, f_Tssss, pf_Tss) end;
blanchet@49176
   305
blanchet@49504
   306
          val (r_Tssss, g_sum_prod_Ts, g_Tssss, pg_Tss) = mk_types single fp_fold_fun_Ts;
blanchet@49211
   307
blanchet@49484
   308
          val ((((Free (z, _), cs), pss), gssss), lthy) =
blanchet@49210
   309
            lthy
blanchet@49233
   310
            |> yield_singleton (mk_Frees "z") dummyT
blanchet@49233
   311
            ||>> mk_Frees "a" Cs
blanchet@49211
   312
            ||>> mk_Freess "p" p_Tss
blanchet@49275
   313
            ||>> mk_Freessss "g" g_Tssss;
blanchet@49275
   314
          val rssss = map (map (map (fn [] => []))) r_Tssss;
blanchet@49274
   315
blanchet@49274
   316
          fun dest_corec_sumT (T as Type (@{type_name sum}, Us as [_, U])) =
blanchet@49274
   317
              if member (op =) Cs U then Us else [T]
blanchet@49274
   318
            | dest_corec_sumT T = [T];
blanchet@49274
   319
blanchet@49275
   320
          val (s_Tssss, h_sum_prod_Ts, h_Tssss, ph_Tss) = mk_types dest_corec_sumT fp_rec_fun_Ts;
blanchet@49210
   321
blanchet@49298
   322
          val hssss_hd = map2 (map2 (map2 (fn T :: _ => fn [g] => retype_free T g))) h_Tssss gssss;
blanchet@49484
   323
          val ((sssss, hssss_tl), lthy) =
blanchet@49275
   324
            lthy
blanchet@49275
   325
            |> mk_Freessss "q" s_Tssss
blanchet@49275
   326
            ||>> mk_Freessss "h" (map (map (map tl)) h_Tssss);
blanchet@49275
   327
          val hssss = map2 (map2 (map2 cons)) hssss_hd hssss_tl;
blanchet@49211
   328
blanchet@49212
   329
          val cpss = map2 (fn c => map (fn p => p $ c)) cs pss;
blanchet@49212
   330
blanchet@49276
   331
          fun mk_preds_getters_join [] [cf] = cf
blanchet@49276
   332
            | mk_preds_getters_join [cq] [cf, cf'] =
blanchet@49276
   333
              mk_If cq (mk_Inl (fastype_of cf') cf) (mk_Inr (fastype_of cf) cf');
blanchet@49276
   334
blanchet@49275
   335
          fun mk_terms qssss fssss =
blanchet@49212
   336
            let
blanchet@49276
   337
              val pfss = map3 zip_preds_predsss_gettersss pss qssss fssss;
blanchet@49275
   338
              val cqssss = map2 (fn c => map (map (map (fn f => f $ c)))) cs qssss;
blanchet@49274
   339
              val cfssss = map2 (fn c => map (map (map (fn f => f $ c)))) cs fssss;
blanchet@49276
   340
              val cqfsss = map2 (map2 (map2 mk_preds_getters_join)) cqssss cfssss;
blanchet@49276
   341
            in (pfss, cqfsss) end;
blanchet@49210
   342
        in
blanchet@49484
   343
          (((([], [], []), ([], [], [])),
blanchet@49484
   344
            ([z], cs, cpss, (mk_terms rssss gssss, (g_sum_prod_Ts, pg_Tss)),
blanchet@49484
   345
             (mk_terms sssss hssss, (h_sum_prod_Ts, ph_Tss)))), lthy)
blanchet@49210
   346
        end;
blanchet@49210
   347
blanchet@49504
   348
    fun define_ctrs_case_for_type ((((((((((((((((((fp_b, fpT), C), ctor), dtor), fp_fold), fp_rec),
blanchet@49501
   349
          ctor_dtor), dtor_ctor), ctor_inject), n), ks), ms), ctr_bindings), ctr_mixfixes), ctr_Tss),
blanchet@49370
   350
        disc_bindings), sel_bindingss), raw_sel_defaultss) no_defs_lthy =
blanchet@49176
   351
      let
blanchet@49498
   352
        val fp_b_name = Binding.name_of fp_b;
blanchet@49498
   353
blanchet@49501
   354
        val dtorT = domain_type (fastype_of ctor);
blanchet@49210
   355
        val ctr_prod_Ts = map HOLogic.mk_tupleT ctr_Tss;
blanchet@49255
   356
        val ctr_sum_prod_T = mk_sumTN_balanced ctr_prod_Ts;
blanchet@49134
   357
        val case_Ts = map (fn Ts => Ts ---> C) ctr_Tss;
blanchet@49119
   358
blanchet@49536
   359
        val (((((w, fs), xss), yss), u'), _) =
blanchet@49204
   360
          no_defs_lthy
blanchet@49501
   361
          |> yield_singleton (mk_Frees "w") dtorT
blanchet@49176
   362
          ||>> mk_Frees "f" case_Ts
blanchet@49370
   363
          ||>> mk_Freess "x" ctr_Tss
blanchet@49536
   364
          ||>> mk_Freess "y" ctr_Tss
blanchet@49498
   365
          ||>> yield_singleton Variable.variant_fixes fp_b_name;
blanchet@49370
   366
blanchet@49498
   367
        val u = Free (u', fpT);
blanchet@49121
   368
blanchet@49129
   369
        val ctr_rhss =
blanchet@49501
   370
          map2 (fn k => fn xs => fold_rev Term.lambda xs (ctor $
blanchet@49256
   371
            mk_InN_balanced ctr_sum_prod_T n (HOLogic.mk_tuple xs) k)) ks xss;
blanchet@49121
   372
blanchet@49336
   373
        val case_binding = Binding.suffix_name ("_" ^ caseN) fp_b;
blanchet@49129
   374
blanchet@49134
   375
        val case_rhs =
blanchet@49498
   376
          fold_rev Term.lambda (fs @ [u])
blanchet@49501
   377
            (mk_sum_caseN_balanced (map2 mk_uncurried_fun fs xss) $ (dtor $ u));
blanchet@49129
   378
blanchet@49201
   379
        val ((raw_case :: raw_ctrs, raw_case_def :: raw_ctr_defs), (lthy', lthy)) = no_defs_lthy
blanchet@49169
   380
          |> apfst split_list o fold_map3 (fn b => fn mx => fn rhs =>
blanchet@49302
   381
              Local_Theory.define ((b, mx), ((Thm.def_binding b, []), rhs)) #>> apsnd snd)
blanchet@49336
   382
            (case_binding :: ctr_bindings) (NoSyn :: ctr_mixfixes) (case_rhs :: ctr_rhss)
blanchet@49121
   383
          ||> `Local_Theory.restore;
blanchet@49121
   384
blanchet@49121
   385
        val phi = Proof_Context.export_morphism lthy lthy';
blanchet@49121
   386
blanchet@49121
   387
        val ctr_defs = map (Morphism.thm phi) raw_ctr_defs;
blanchet@49130
   388
        val case_def = Morphism.thm phi raw_case_def;
blanchet@49130
   389
blanchet@49203
   390
        val ctrs0 = map (Morphism.term phi) raw_ctrs;
blanchet@49203
   391
        val casex0 = Morphism.term phi raw_case;
blanchet@49203
   392
blanchet@49203
   393
        val ctrs = map (mk_ctr As) ctrs0;
blanchet@49121
   394
blanchet@49135
   395
        fun exhaust_tac {context = ctxt, ...} =
blanchet@49123
   396
          let
blanchet@49501
   397
            val ctor_iff_dtor_thm =
blanchet@49135
   398
              let
blanchet@49135
   399
                val goal =
blanchet@49498
   400
                  fold_rev Logic.all [w, u]
blanchet@49501
   401
                    (mk_Trueprop_eq (HOLogic.mk_eq (u, ctor $ w), HOLogic.mk_eq (dtor $ u, w)));
blanchet@49135
   402
              in
blanchet@49135
   403
                Skip_Proof.prove lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@49501
   404
                  mk_ctor_iff_dtor_tac ctxt (map (SOME o certifyT lthy) [dtorT, fpT])
blanchet@49501
   405
                    (certify lthy ctor) (certify lthy dtor) ctor_dtor dtor_ctor)
blanchet@49135
   406
                |> Thm.close_derivation
blanchet@49135
   407
                |> Morphism.thm phi
blanchet@49135
   408
              end;
blanchet@49135
   409
blanchet@49135
   410
            val sumEN_thm' =
blanchet@49504
   411
              unfold_thms lthy @{thms all_unit_eq}
blanchet@49255
   412
                (Drule.instantiate' (map (SOME o certifyT lthy) ctr_prod_Ts) []
blanchet@49255
   413
                   (mk_sumEN_balanced n))
blanchet@49135
   414
              |> Morphism.thm phi;
blanchet@49123
   415
          in
blanchet@49501
   416
            mk_exhaust_tac ctxt n ctr_defs ctor_iff_dtor_thm sumEN_thm'
blanchet@49123
   417
          end;
blanchet@49121
   418
blanchet@49126
   419
        val inject_tacss =
blanchet@49205
   420
          map2 (fn 0 => K [] | _ => fn ctr_def => [fn {context = ctxt, ...} =>
blanchet@49501
   421
              mk_inject_tac ctxt ctr_def ctor_inject]) ms ctr_defs;
blanchet@49126
   422
blanchet@49127
   423
        val half_distinct_tacss =
blanchet@49127
   424
          map (map (fn (def, def') => fn {context = ctxt, ...} =>
blanchet@49501
   425
            mk_half_distinct_tac ctxt ctor_inject [def, def'])) (mk_half_pairss ctr_defs);
blanchet@49127
   426
blanchet@49130
   427
        val case_tacs =
blanchet@49130
   428
          map3 (fn k => fn m => fn ctr_def => fn {context = ctxt, ...} =>
blanchet@49501
   429
            mk_case_tac ctxt n k m case_def ctr_def dtor_ctor) ks ms ctr_defs;
blanchet@49121
   430
blanchet@49121
   431
        val tacss = [exhaust_tac] :: inject_tacss @ half_distinct_tacss @ [case_tacs];
blanchet@49134
   432
blanchet@49504
   433
        fun define_fold_rec (wrap_res, no_defs_lthy) =
blanchet@49134
   434
          let
blanchet@49208
   435
            val fpT_to_C = fpT --> C;
blanchet@49199
   436
blanchet@49504
   437
            fun generate_rec_like (suf, fp_rec_like, (fss, f_Tss, xssss)) =
blanchet@49215
   438
              let
blanchet@49215
   439
                val res_T = fold_rev (curry (op --->)) f_Tss fpT_to_C;
blanchet@49336
   440
                val binding = Binding.suffix_name ("_" ^ suf) fp_b;
blanchet@49215
   441
                val spec =
blanchet@49336
   442
                  mk_Trueprop_eq (lists_bmoc fss (Free (Binding.name_of binding, res_T)),
blanchet@49504
   443
                    Term.list_comb (fp_rec_like,
blanchet@49255
   444
                      map2 (mk_sum_caseN_balanced oo map2 mk_uncurried2_fun) fss xssss));
blanchet@49336
   445
              in (binding, spec) end;
blanchet@49199
   446
blanchet@49504
   447
            val rec_like_infos =
blanchet@49504
   448
              [(foldN, fp_fold, fold_only),
blanchet@49215
   449
               (recN, fp_rec, rec_only)];
blanchet@49215
   450
blanchet@49504
   451
            val (bindings, specs) = map generate_rec_like rec_like_infos |> split_list;
blanchet@49215
   452
blanchet@49215
   453
            val ((csts, defs), (lthy', lthy)) = no_defs_lthy
blanchet@49201
   454
              |> apfst split_list o fold_map2 (fn b => fn spec =>
blanchet@49199
   455
                Specification.definition (SOME (b, NONE, NoSyn), ((Thm.def_binding b, []), spec))
blanchet@49336
   456
                #>> apsnd snd) bindings specs
blanchet@49199
   457
              ||> `Local_Theory.restore;
blanchet@49201
   458
blanchet@49201
   459
            val phi = Proof_Context.export_morphism lthy lthy';
blanchet@49201
   460
blanchet@49504
   461
            val [fold_def, rec_def] = map (Morphism.thm phi) defs;
blanchet@49201
   462
blanchet@49536
   463
            val [foldx, recx] = map (mk_rec_like lfp As Cs o Morphism.term phi) csts;
blanchet@49134
   464
          in
blanchet@49536
   465
            ((wrap_res, ctrs, foldx, recx, xss, yss, ctr_defs, fold_def, rec_def), lthy)
blanchet@49134
   466
          end;
blanchet@49134
   467
blanchet@49504
   468
        fun define_unfold_corec (wrap_res, no_defs_lthy) =
blanchet@49210
   469
          let
blanchet@49210
   470
            val B_to_fpT = C --> fpT;
blanchet@49211
   471
blanchet@49276
   472
            fun mk_preds_getterss_join c n cps sum_prod_T cqfss =
blanchet@49276
   473
              Term.lambda c (mk_IfN sum_prod_T cps
blanchet@49276
   474
                (map2 (mk_InN_balanced sum_prod_T n) (map HOLogic.mk_tuple cqfss) (1 upto n)));
blanchet@49275
   475
blanchet@49504
   476
            fun generate_corec_like (suf, fp_rec_like, ((pfss, cqfsss), (f_sum_prod_Ts,
blanchet@49274
   477
                pf_Tss))) =
blanchet@49211
   478
              let
blanchet@49211
   479
                val res_T = fold_rev (curry (op --->)) pf_Tss B_to_fpT;
blanchet@49336
   480
                val binding = Binding.suffix_name ("_" ^ suf) fp_b;
blanchet@49211
   481
                val spec =
blanchet@49336
   482
                  mk_Trueprop_eq (lists_bmoc pfss (Free (Binding.name_of binding, res_T)),
blanchet@49504
   483
                    Term.list_comb (fp_rec_like,
blanchet@49276
   484
                      map5 mk_preds_getterss_join cs ns cpss f_sum_prod_Ts cqfsss));
blanchet@49336
   485
              in (binding, spec) end;
blanchet@49210
   486
blanchet@49504
   487
            val corec_like_infos =
blanchet@49504
   488
              [(unfoldN, fp_fold, unfold_only),
blanchet@49215
   489
               (corecN, fp_rec, corec_only)];
blanchet@49212
   490
blanchet@49504
   491
            val (bindings, specs) = map generate_corec_like corec_like_infos |> split_list;
blanchet@49211
   492
blanchet@49211
   493
            val ((csts, defs), (lthy', lthy)) = no_defs_lthy
blanchet@49210
   494
              |> apfst split_list o fold_map2 (fn b => fn spec =>
blanchet@49210
   495
                Specification.definition (SOME (b, NONE, NoSyn), ((Thm.def_binding b, []), spec))
blanchet@49336
   496
                #>> apsnd snd) bindings specs
blanchet@49210
   497
              ||> `Local_Theory.restore;
blanchet@49210
   498
blanchet@49210
   499
            val phi = Proof_Context.export_morphism lthy lthy';
blanchet@49210
   500
blanchet@49504
   501
            val [unfold_def, corec_def] = map (Morphism.thm phi) defs;
blanchet@49210
   502
blanchet@49536
   503
            val [unfold, corec] = map (mk_rec_like lfp As Cs o Morphism.term phi) csts;
blanchet@49210
   504
          in
blanchet@49536
   505
            ((wrap_res, ctrs, unfold, corec, xss, yss, ctr_defs, unfold_def, corec_def), lthy)
blanchet@49210
   506
          end;
blanchet@49286
   507
blanchet@49287
   508
        fun wrap lthy =
blanchet@49287
   509
          let val sel_defaultss = map (map (apsnd (prepare_term lthy))) raw_sel_defaultss in
blanchet@49336
   510
            wrap_datatype tacss (((no_dests, ctrs0), casex0), (disc_bindings, (sel_bindingss,
blanchet@49287
   511
              sel_defaultss))) lthy
blanchet@49287
   512
          end;
blanchet@49287
   513
blanchet@49504
   514
        val define_rec_likes = if lfp then define_fold_rec else define_unfold_corec;
blanchet@49119
   515
      in
blanchet@49504
   516
        ((wrap, define_rec_likes), lthy')
blanchet@49119
   517
      end;
blanchet@49167
   518
blanchet@49518
   519
    fun wrap_types_and_define_rec_likes ((wraps, define_rec_likess), lthy) =
blanchet@49536
   520
      fold_map2 (curry (op o)) define_rec_likess wraps lthy |>> split_list9
blanchet@49518
   521
blanchet@49226
   522
    val pre_map_defs = map map_def_of_bnf pre_bnfs;
blanchet@49342
   523
    val pre_set_defss = map set_defs_of_bnf pre_bnfs;
blanchet@49368
   524
    val nested_set_natural's = maps set_natural'_of_bnf nested_bnfs;
blanchet@49363
   525
    val nesting_map_ids = map map_id_of_bnf nesting_bnfs;
blanchet@49226
   526
blanchet@49437
   527
    fun build_map build_arg (Type (s, Ts)) (Type (_, Us)) =
blanchet@49234
   528
      let
blanchet@49392
   529
        val bnf = the (bnf_of lthy s);
blanchet@49393
   530
        val live = live_of_bnf bnf;
blanchet@49393
   531
        val mapx = mk_map live Ts Us (map_of_bnf bnf);
blanchet@49393
   532
        val TUs = map dest_funT (fst (strip_typeN live (fastype_of mapx)));
blanchet@49234
   533
        val args = map build_arg TUs;
blanchet@49234
   534
      in Term.list_comb (mapx, args) end;
blanchet@49234
   535
blanchet@49479
   536
    val mk_simp_thmss =
blanchet@49505
   537
      map3 (fn (_, _, injects, distincts, cases, _, _, _) => fn rec_likes => fn fold_likes =>
blanchet@49505
   538
        injects @ distincts @ cases @ rec_likes @ fold_likes);
blanchet@49479
   539
blanchet@49536
   540
    fun derive_induct_fold_rec_thms_for_types ((wrap_ress, ctrss, folds, recs, xsss, _, ctr_defss,
blanchet@49504
   541
        fold_defs, rec_defs), lthy) =
blanchet@49202
   542
      let
blanchet@49498
   543
        val (((phis, phis'), us'), names_lthy) =
blanchet@49370
   544
          lthy
blanchet@49463
   545
          |> mk_Frees' "P" (map mk_pred1T fpTs)
blanchet@49498
   546
          ||>> Variable.variant_fixes fp_b_names;
blanchet@49370
   547
blanchet@49498
   548
        val us = map2 (curry Free) us' fpTs;
blanchet@49370
   549
blanchet@49362
   550
        fun mk_sets_nested bnf =
blanchet@49362
   551
          let
blanchet@49362
   552
            val Type (T_name, Us) = T_of_bnf bnf;
blanchet@49362
   553
            val lives = lives_of_bnf bnf;
blanchet@49362
   554
            val sets = sets_of_bnf bnf;
blanchet@49362
   555
            fun mk_set U =
blanchet@49362
   556
              (case find_index (curry (op =) U) lives of
blanchet@49362
   557
                ~1 => Term.dummy
blanchet@49362
   558
              | i => nth sets i);
blanchet@49362
   559
          in
blanchet@49362
   560
            (T_name, map mk_set Us)
blanchet@49362
   561
          end;
blanchet@49362
   562
blanchet@49362
   563
        val setss_nested = map mk_sets_nested nested_bnfs;
blanchet@49362
   564
blanchet@49337
   565
        val (induct_thms, induct_thm) =
blanchet@49337
   566
          let
blanchet@49362
   567
            fun mk_set Ts t =
blanchet@49362
   568
              let val Type (_, Ts0) = domain_type (fastype_of t) in
blanchet@49362
   569
                Term.subst_atomic_types (Ts0 ~~ Ts) t
blanchet@49362
   570
              end;
blanchet@49362
   571
blanchet@49375
   572
            fun mk_raw_prem_prems names_lthy (x as Free (s, T as Type (T_name, Ts0))) =
blanchet@49361
   573
                (case find_index (curry (op =) T) fpTs of
blanchet@49362
   574
                  ~1 =>
blanchet@49362
   575
                  (case AList.lookup (op =) setss_nested T_name of
blanchet@49362
   576
                    NONE => []
blanchet@49362
   577
                  | SOME raw_sets0 =>
blanchet@49362
   578
                    let
blanchet@49362
   579
                      val (Ts, raw_sets) =
blanchet@49362
   580
                        split_list (filter (exists_fp_subtype o fst) (Ts0 ~~ raw_sets0));
blanchet@49362
   581
                      val sets = map (mk_set Ts0) raw_sets;
blanchet@49362
   582
                      val (ys, names_lthy') = names_lthy |> mk_Frees s Ts;
blanchet@49375
   583
                      val xysets = map (pair x) (ys ~~ sets);
blanchet@49375
   584
                      val ppremss = map (mk_raw_prem_prems names_lthy') ys;
blanchet@49362
   585
                    in
blanchet@49375
   586
                      flat (map2 (map o apfst o cons) xysets ppremss)
blanchet@49362
   587
                    end)
blanchet@49376
   588
                | i => [([], (i + 1, x))])
blanchet@49375
   589
              | mk_raw_prem_prems _ _ = [];
blanchet@49342
   590
blanchet@49378
   591
            fun close_prem_prem xs t =
blanchet@49378
   592
              fold_rev Logic.all (map Free (drop (nn + length xs)
blanchet@49378
   593
                (rev (Term.add_frees t (map dest_Free xs @ phis'))))) t;
blanchet@49362
   594
blanchet@49378
   595
            fun mk_prem_prem xs (xysets, (j, x)) =
blanchet@49378
   596
              close_prem_prem xs (Logic.list_implies (map (fn (x', (y, set)) =>
blanchet@49376
   597
                  HOLogic.mk_Trueprop (HOLogic.mk_mem (y, set $ x'))) xysets,
blanchet@49376
   598
                HOLogic.mk_Trueprop (nth phis (j - 1) $ x)));
blanchet@49375
   599
blanchet@49372
   600
            fun mk_raw_prem phi ctr ctr_Ts =
blanchet@49362
   601
              let
blanchet@49362
   602
                val (xs, names_lthy') = names_lthy |> mk_Frees "x" ctr_Ts;
blanchet@49376
   603
                val pprems = maps (mk_raw_prem_prems names_lthy') xs;
blanchet@49378
   604
              in (xs, pprems, HOLogic.mk_Trueprop (phi $ Term.list_comb (ctr, xs))) end;
blanchet@49342
   605
blanchet@49376
   606
            fun mk_prem (xs, raw_pprems, concl) =
blanchet@49378
   607
              fold_rev Logic.all xs (Logic.list_implies (map (mk_prem_prem xs) raw_pprems, concl));
blanchet@49368
   608
blanchet@49389
   609
            val raw_premss = map3 (map2 o mk_raw_prem) phis ctrss ctr_Tsss;
blanchet@49389
   610
blanchet@49361
   611
            val goal =
blanchet@49372
   612
              Library.foldr (Logic.list_implies o apfst (map mk_prem)) (raw_premss,
blanchet@49498
   613
                HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj (map2 (curry (op $)) phis us)));
blanchet@49368
   614
blanchet@49429
   615
            val kksss = map (map (map (fst o snd) o #2)) raw_premss;
blanchet@49368
   616
blanchet@49501
   617
            val ctor_induct' = fp_induct OF (map mk_sumEN_tupled_balanced mss);
blanchet@49342
   618
blanchet@49342
   619
            val induct_thm =
blanchet@49361
   620
              Skip_Proof.prove lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@49501
   621
                mk_induct_tac ctxt ns mss kksss (flat ctr_defss) ctor_induct'
blanchet@49389
   622
                  nested_set_natural's pre_set_defss)
blanchet@49368
   623
              |> singleton (Proof_Context.export names_lthy lthy)
blanchet@49337
   624
          in
blanchet@49367
   625
            `(conj_dests nn) induct_thm
blanchet@49337
   626
          end;
blanchet@49201
   627
blanchet@49438
   628
        (* TODO: Generate nicer names in case of clashes *)
blanchet@49437
   629
        val induct_cases = Datatype_Prop.indexify_names (maps (map base_name_of_ctr) ctrss);
blanchet@49437
   630
blanchet@49504
   631
        val (fold_thmss, rec_thmss) =
blanchet@49207
   632
          let
blanchet@49337
   633
            val xctrss = map2 (map2 (curry Term.list_comb)) ctrss xsss;
blanchet@49504
   634
            val gfolds = map (lists_bmoc gss) folds;
blanchet@49337
   635
            val hrecs = map (lists_bmoc hss) recs;
blanchet@49337
   636
blanchet@49504
   637
            fun mk_goal fss frec_like xctr f xs fxs =
blanchet@49207
   638
              fold_rev (fold_rev Logic.all) (xs :: fss)
blanchet@49504
   639
                (mk_Trueprop_eq (frec_like $ xctr, Term.list_comb (f, fxs)));
blanchet@49204
   640
blanchet@49504
   641
            fun build_call frec_likes maybe_tick (T, U) =
blanchet@49234
   642
              if T = U then
blanchet@49368
   643
                id_const T
blanchet@49234
   644
              else
blanchet@49234
   645
                (case find_index (curry (op =) T) fpTs of
blanchet@49504
   646
                  ~1 => build_map (build_call frec_likes maybe_tick) T U
blanchet@49504
   647
                | j => maybe_tick (nth us j) (nth frec_likes j));
blanchet@49233
   648
blanchet@49274
   649
            fun mk_U maybe_mk_prodT =
blanchet@49274
   650
              typ_subst (map2 (fn fpT => fn C => (fpT, maybe_mk_prodT fpT C)) fpTs Cs);
blanchet@49214
   651
blanchet@49504
   652
            fun intr_calls frec_likes maybe_cons maybe_tick maybe_mk_prodT (x as Free (_, T)) =
blanchet@49214
   653
              if member (op =) fpTs T then
blanchet@49504
   654
                maybe_cons x [build_call frec_likes (K I) (T, mk_U (K I) T) $ x]
blanchet@49362
   655
              else if exists_fp_subtype T then
blanchet@49504
   656
                [build_call frec_likes maybe_tick (T, mk_U maybe_mk_prodT T) $ x]
blanchet@49214
   657
              else
blanchet@49214
   658
                [x];
blanchet@49214
   659
blanchet@49504
   660
            val gxsss = map (map (maps (intr_calls gfolds (K I) (K I) (K I)))) xsss;
blanchet@49342
   661
            val hxsss = map (map (maps (intr_calls hrecs cons tick (curry HOLogic.mk_prodT)))) xsss;
blanchet@49204
   662
blanchet@49504
   663
            val fold_goalss = map5 (map4 o mk_goal gss) gfolds xctrss gss xsss gxsss;
blanchet@49484
   664
            val rec_goalss = map5 (map4 o mk_goal hss) hrecs xctrss hss xsss hxsss;
blanchet@49204
   665
blanchet@49504
   666
            val fold_tacss =
blanchet@49504
   667
              map2 (map o mk_rec_like_tac pre_map_defs nesting_map_ids fold_defs) fp_fold_thms
blanchet@49363
   668
                ctr_defss;
blanchet@49203
   669
            val rec_tacss =
blanchet@49504
   670
              map2 (map o mk_rec_like_tac pre_map_defs nesting_map_ids rec_defs) fp_rec_thms
blanchet@49363
   671
                ctr_defss;
blanchet@49484
   672
blanchet@49484
   673
            fun prove goal tac = Skip_Proof.prove lthy [] [] goal (tac o #context);
blanchet@49202
   674
          in
blanchet@49504
   675
            (map2 (map2 prove) fold_goalss fold_tacss,
blanchet@49484
   676
             map2 (map2 prove) rec_goalss rec_tacss)
blanchet@49202
   677
          end;
blanchet@49201
   678
blanchet@49504
   679
        val simp_thmss = mk_simp_thmss wrap_ress rec_thmss fold_thmss;
blanchet@49438
   680
blanchet@49437
   681
        val induct_case_names_attr = Attrib.internal (K (Rule_Cases.case_names induct_cases));
blanchet@49437
   682
        fun induct_type_attr T_name = Attrib.internal (K (Induct.induct_type T_name));
blanchet@49437
   683
blanchet@49450
   684
        (* TODO: Also note "recs", "simps", and "splits" if "nn > 1" (for compatibility with the
blanchet@49479
   685
           old package)? And for codatatypes as well? *)
blanchet@49337
   686
        val common_notes =
blanchet@49437
   687
          (if nn > 1 then [(inductN, [induct_thm], [induct_case_names_attr])] else [])
blanchet@49337
   688
          |> map (fn (thmN, thms, attrs) =>
blanchet@49479
   689
            ((Binding.qualify true fp_common_name (Binding.name thmN), attrs), [(thms, [])]));
blanchet@49337
   690
blanchet@49226
   691
        val notes =
blanchet@49437
   692
          [(inductN, map single induct_thms,
blanchet@49437
   693
            fn T_name => [induct_case_names_attr, induct_type_attr T_name]),
blanchet@49504
   694
           (foldsN, fold_thmss, K (Code.add_default_eqn_attrib :: simp_attrs)),
blanchet@49438
   695
           (recsN, rec_thmss, K (Code.add_default_eqn_attrib :: simp_attrs)),
blanchet@49536
   696
           (simpsN, simp_thmss, K [])] (* TODO: Add relator simps *)
blanchet@49300
   697
          |> maps (fn (thmN, thmss, attrs) =>
blanchet@49437
   698
            map3 (fn b => fn Type (T_name, _) => fn thms =>
blanchet@49437
   699
              ((Binding.qualify true (Binding.name_of b) (Binding.name thmN), attrs T_name),
blanchet@49437
   700
                [(thms, [])])) fp_bs fpTs thmss);
blanchet@49202
   701
      in
blanchet@49337
   702
        lthy |> Local_Theory.notes (common_notes @ notes) |> snd
blanchet@49202
   703
      end;
blanchet@49202
   704
blanchet@49536
   705
    fun derive_coinduct_unfold_corec_thms_for_types ((wrap_ress, ctrss, unfolds, corecs, _, _,
blanchet@49504
   706
        ctr_defss, unfold_defs, corec_defs), lthy) =
blanchet@49212
   707
      let
blanchet@49484
   708
        val discss = map (map (mk_disc_or_sel As) o #1) wrap_ress;
blanchet@49484
   709
        val selsss = map #2 wrap_ress;
blanchet@49484
   710
        val disc_thmsss = map #6 wrap_ress;
blanchet@49484
   711
        val discIss = map #7 wrap_ress;
blanchet@49484
   712
        val sel_thmsss = map #8 wrap_ress;
blanchet@49438
   713
blanchet@49498
   714
        val (us', _) =
blanchet@49370
   715
          lthy
blanchet@49498
   716
          |> Variable.variant_fixes fp_b_names;
blanchet@49370
   717
blanchet@49498
   718
        val us = map2 (curry Free) us' fpTs;
blanchet@49370
   719
blanchet@49337
   720
        val (coinduct_thms, coinduct_thm) =
blanchet@49337
   721
          let
blanchet@49337
   722
            val coinduct_thm = fp_induct;
blanchet@49337
   723
          in
blanchet@49367
   724
            `(conj_dests nn) coinduct_thm
blanchet@49337
   725
          end;
blanchet@49212
   726
blanchet@49484
   727
        fun mk_maybe_not pos = not pos ? HOLogic.mk_not;
blanchet@49484
   728
blanchet@49484
   729
        val z = the_single zs;
blanchet@49504
   730
        val gunfolds = map (lists_bmoc pgss) unfolds;
blanchet@49484
   731
        val hcorecs = map (lists_bmoc phss) corecs;
blanchet@49484
   732
blanchet@49504
   733
        val (unfold_thmss, corec_thmss, safe_unfold_thmss, safe_corec_thmss) =
blanchet@49212
   734
          let
blanchet@49504
   735
            fun mk_goal pfss c cps fcorec_like n k ctr m cfs' =
blanchet@49212
   736
              fold_rev (fold_rev Logic.all) ([c] :: pfss)
blanchet@49484
   737
                (Logic.list_implies (seq_conds (HOLogic.mk_Trueprop oo mk_maybe_not) n k cps,
blanchet@49504
   738
                   mk_Trueprop_eq (fcorec_like $ c, Term.list_comb (ctr, take m cfs'))));
blanchet@49212
   739
blanchet@49504
   740
            fun build_call frec_likes maybe_tack (T, U) =
blanchet@49234
   741
              if T = U then
blanchet@49368
   742
                id_const T
blanchet@49234
   743
              else
blanchet@49234
   744
                (case find_index (curry (op =) U) fpTs of
blanchet@49504
   745
                  ~1 => build_map (build_call frec_likes maybe_tack) T U
blanchet@49504
   746
                | j => maybe_tack (nth cs j, nth us j) (nth frec_likes j));
blanchet@49233
   747
blanchet@49274
   748
            fun mk_U maybe_mk_sumT =
blanchet@49274
   749
              typ_subst (map2 (fn C => fn fpT => (maybe_mk_sumT fpT C, fpT)) Cs fpTs);
blanchet@49212
   750
blanchet@49504
   751
            fun intr_calls frec_likes maybe_mk_sumT maybe_tack cqf =
blanchet@49276
   752
              let val T = fastype_of cqf in
blanchet@49276
   753
                if exists_subtype (member (op =) Cs) T then
blanchet@49504
   754
                  build_call frec_likes maybe_tack (T, mk_U maybe_mk_sumT T) $ cqf
blanchet@49276
   755
                else
blanchet@49276
   756
                  cqf
blanchet@49276
   757
              end;
blanchet@49232
   758
blanchet@49504
   759
            val crgsss' = map (map (map (intr_calls gunfolds (K I) (K I)))) crgsss;
blanchet@49342
   760
            val cshsss' = map (map (map (intr_calls hcorecs (curry mk_sumT) (tack z)))) cshsss;
blanchet@49212
   761
blanchet@49504
   762
            val unfold_goalss =
blanchet@49504
   763
              map8 (map4 oooo mk_goal pgss) cs cpss gunfolds ns kss ctrss mss crgsss';
blanchet@49484
   764
            val corec_goalss =
blanchet@49484
   765
              map8 (map4 oooo mk_goal phss) cs cpss hcorecs ns kss ctrss mss cshsss';
blanchet@49213
   766
blanchet@49504
   767
            val unfold_tacss =
blanchet@49504
   768
              map3 (map oo mk_corec_like_tac unfold_defs nesting_map_ids) fp_fold_thms pre_map_defs
blanchet@49226
   769
                ctr_defss;
blanchet@49233
   770
            val corec_tacss =
blanchet@49504
   771
              map3 (map oo mk_corec_like_tac corec_defs nesting_map_ids) fp_rec_thms pre_map_defs
blanchet@49233
   772
                ctr_defss;
blanchet@49479
   773
blanchet@49484
   774
            fun prove goal tac =
blanchet@49484
   775
              Skip_Proof.prove lthy [] [] goal (tac o #context) |> Thm.close_derivation;
blanchet@49484
   776
blanchet@49504
   777
            val unfold_thmss = map2 (map2 prove) unfold_goalss unfold_tacss;
blanchet@49479
   778
            val corec_thmss =
blanchet@49484
   779
              map2 (map2 prove) corec_goalss corec_tacss
blanchet@49504
   780
              |> map (map (unfold_thms lthy @{thms sum_case_if}));
blanchet@49479
   781
blanchet@49504
   782
            val unfold_safesss = map2 (map2 (map2 (curry (op =)))) crgsss' crgsss;
blanchet@49479
   783
            val corec_safesss = map2 (map2 (map2 (curry (op =)))) cshsss' cshsss;
blanchet@49479
   784
blanchet@49479
   785
            val filter_safesss =
blanchet@49479
   786
              map2 (map_filter (fn (safes, thm) => if forall I safes then SOME thm else NONE) oo
blanchet@49479
   787
                curry (op ~~));
blanchet@49479
   788
blanchet@49504
   789
            val safe_unfold_thmss = filter_safesss unfold_safesss unfold_thmss;
blanchet@49479
   790
            val safe_corec_thmss = filter_safesss corec_safesss corec_thmss;
blanchet@49479
   791
          in
blanchet@49504
   792
            (unfold_thmss, corec_thmss, safe_unfold_thmss, safe_corec_thmss)
blanchet@49212
   793
          end;
blanchet@49212
   794
blanchet@49504
   795
        val (disc_unfold_iff_thmss, disc_corec_iff_thmss) =
blanchet@49482
   796
          let
blanchet@49504
   797
            fun mk_goal c cps fcorec_like n k disc =
blanchet@49504
   798
              mk_Trueprop_eq (disc $ (fcorec_like $ c),
blanchet@49484
   799
                if n = 1 then @{const True}
blanchet@49484
   800
                else Library.foldr1 HOLogic.mk_conj (seq_conds mk_maybe_not n k cps));
blanchet@49484
   801
blanchet@49504
   802
            val unfold_goalss = map6 (map2 oooo mk_goal) cs cpss gunfolds ns kss discss;
blanchet@49484
   803
            val corec_goalss = map6 (map2 oooo mk_goal) cs cpss hcorecs ns kss discss;
blanchet@49484
   804
blanchet@49484
   805
            fun mk_case_split' cp =
blanchet@49484
   806
              Drule.instantiate' [] [SOME (certify lthy cp)] @{thm case_split};
blanchet@49484
   807
blanchet@49484
   808
            val case_splitss' = map (map mk_case_split') cpss;
blanchet@49482
   809
blanchet@49504
   810
            val unfold_tacss =
blanchet@49504
   811
              map3 (map oo mk_disc_corec_like_iff_tac) case_splitss' unfold_thmss disc_thmsss;
blanchet@49484
   812
            val corec_tacss =
blanchet@49504
   813
              map3 (map oo mk_disc_corec_like_iff_tac) case_splitss' corec_thmss disc_thmsss;
blanchet@49484
   814
blanchet@49484
   815
            fun prove goal tac =
blanchet@49484
   816
              Skip_Proof.prove lthy [] [] goal (tac o #context)
blanchet@49484
   817
              |> Thm.close_derivation
blanchet@49484
   818
              |> singleton (Proof_Context.export names_lthy no_defs_lthy);
blanchet@49484
   819
blanchet@49484
   820
            fun proves [_] [_] = []
blanchet@49484
   821
              | proves goals tacs = map2 prove goals tacs;
blanchet@49482
   822
          in
blanchet@49504
   823
            (map2 proves unfold_goalss unfold_tacss,
blanchet@49484
   824
             map2 proves corec_goalss corec_tacss)
blanchet@49482
   825
          end;
blanchet@49482
   826
blanchet@49504
   827
        fun mk_disc_corec_like_thms corec_likes discIs =
blanchet@49504
   828
          map (op RS) (filter_out (is_triv_implies o snd) (corec_likes ~~ discIs));
blanchet@49266
   829
blanchet@49504
   830
        val disc_unfold_thmss = map2 mk_disc_corec_like_thms unfold_thmss discIss;
blanchet@49504
   831
        val disc_corec_thmss = map2 mk_disc_corec_like_thms corec_thmss discIss;
blanchet@49266
   832
blanchet@49504
   833
        fun mk_sel_corec_like_thm corec_like_thm sel sel_thm =
blanchet@49266
   834
          let
blanchet@49479
   835
            val (domT, ranT) = dest_funT (fastype_of sel);
blanchet@49266
   836
            val arg_cong' =
blanchet@49266
   837
              Drule.instantiate' (map (SOME o certifyT lthy) [domT, ranT])
blanchet@49479
   838
                [NONE, NONE, SOME (certify lthy sel)] arg_cong
blanchet@49267
   839
              |> Thm.varifyT_global;
blanchet@49266
   840
            val sel_thm' = sel_thm RSN (2, trans);
blanchet@49266
   841
          in
blanchet@49504
   842
            corec_like_thm RS arg_cong' RS sel_thm'
blanchet@49266
   843
          end;
blanchet@49266
   844
blanchet@49504
   845
        fun mk_sel_corec_like_thms corec_likess =
blanchet@49504
   846
          map3 (map3 (map2 o mk_sel_corec_like_thm)) corec_likess selsss sel_thmsss |> map flat;
blanchet@49479
   847
blanchet@49504
   848
        val sel_unfold_thmss = mk_sel_corec_like_thms unfold_thmss;
blanchet@49504
   849
        val sel_corec_thmss = mk_sel_corec_like_thms corec_thmss;
blanchet@49479
   850
blanchet@49504
   851
        fun zip_corec_like_thms corec_likes disc_corec_likes sel_corec_likes =
blanchet@49504
   852
          corec_likes @ disc_corec_likes @ sel_corec_likes;
blanchet@49479
   853
blanchet@49479
   854
        val simp_thmss =
blanchet@49479
   855
          mk_simp_thmss wrap_ress
blanchet@49504
   856
            (map3 zip_corec_like_thms safe_corec_thmss disc_corec_thmss sel_corec_thmss)
blanchet@49504
   857
            (map3 zip_corec_like_thms safe_unfold_thmss disc_unfold_thmss sel_unfold_thmss);
blanchet@49479
   858
blanchet@49479
   859
        val anonymous_notes =
blanchet@49504
   860
          [(flat safe_unfold_thmss @ flat safe_corec_thmss, simp_attrs)]
blanchet@49479
   861
          |> map (fn (thms, attrs) => ((Binding.empty, attrs), [(thms, [])]));
blanchet@49266
   862
blanchet@49342
   863
        val common_notes =
blanchet@49367
   864
          (if nn > 1 then [(coinductN, [coinduct_thm], [])] (* FIXME: attribs *) else [])
blanchet@49342
   865
          |> map (fn (thmN, thms, attrs) =>
blanchet@49479
   866
            ((Binding.qualify true fp_common_name (Binding.name thmN), attrs), [(thms, [])]));
blanchet@49342
   867
blanchet@49212
   868
        val notes =
blanchet@49342
   869
          [(coinductN, map single coinduct_thms, []), (* FIXME: attribs *)
blanchet@49482
   870
           (corecsN, corec_thmss, []),
blanchet@49504
   871
           (disc_unfold_iffN, disc_unfold_iff_thmss, simp_attrs),
blanchet@49504
   872
           (disc_unfoldsN, disc_unfold_thmss, simp_attrs),
blanchet@49484
   873
           (disc_corec_iffN, disc_corec_iff_thmss, simp_attrs),
blanchet@49482
   874
           (disc_corecsN, disc_corec_thmss, simp_attrs),
blanchet@49504
   875
           (sel_unfoldsN, sel_unfold_thmss, simp_attrs),
blanchet@49479
   876
           (sel_corecsN, sel_corec_thmss, simp_attrs),
blanchet@49536
   877
           (simpsN, simp_thmss, []), (* TODO: Add relator simps *)
blanchet@49518
   878
           (unfoldsN, unfold_thmss, [])]
blanchet@49300
   879
          |> maps (fn (thmN, thmss, attrs) =>
blanchet@49266
   880
            map_filter (fn (_, []) => NONE | (b, thms) =>
blanchet@49300
   881
              SOME ((Binding.qualify true (Binding.name_of b) (Binding.name thmN), attrs),
blanchet@49302
   882
                [(thms, [])])) (fp_bs ~~ thmss));
blanchet@49212
   883
      in
blanchet@49479
   884
        lthy |> Local_Theory.notes (anonymous_notes @ common_notes @ notes) |> snd
blanchet@49212
   885
      end;
blanchet@49212
   886
blanchet@49536
   887
    fun derive_rel_thms_for_types ((wrap_ress, ctrss, unfolds, corecs, xsss, ysss, ctr_defss,
blanchet@49536
   888
        unfold_defs, corec_defs), lthy) =
blanchet@49536
   889
      let
blanchet@49536
   890
        val selsss = map #2 wrap_ress;
blanchet@49536
   891
blanchet@49536
   892
        val theta_Ts =  [] (*###*)
blanchet@49536
   893
blanchet@49536
   894
        val (thetas, _) =
blanchet@49536
   895
          lthy
blanchet@49536
   896
          |> mk_Frees "Q" (map mk_pred1T theta_Ts);
blanchet@49536
   897
blanchet@49536
   898
        val (rel_thmss, rel_thmsss) =
blanchet@49536
   899
          let
blanchet@49536
   900
            val xctrss = map2 (map2 (curry Term.list_comb)) ctrss xsss;
blanchet@49536
   901
            val yctrss = map2 (map2 (curry Term.list_comb)) ctrss ysss;
blanchet@49536
   902
            val threls = map (fold_rev rapp thetas) rels;
blanchet@49536
   903
blanchet@49536
   904
            fun mk_goal threl (xctr, xs) (yctr, ys) =
blanchet@49536
   905
              let
blanchet@49536
   906
                val lhs = threl $ xctr $ yctr;
blanchet@49536
   907
blanchet@49536
   908
                (* ### fixme: lift rel *)
blanchet@49536
   909
                fun mk_conjunct x y = HOLogic.mk_eq (x, y);
blanchet@49536
   910
blanchet@49536
   911
                fun mk_rhs () =
blanchet@49536
   912
                  Library.foldr1 HOLogic.mk_conj (map2 mk_conjunct xs ys);
blanchet@49536
   913
              in
blanchet@49536
   914
                HOLogic.mk_Trueprop
blanchet@49536
   915
                  (if Term.head_of xctr = Term.head_of yctr then
blanchet@49536
   916
                     if null xs then
blanchet@49536
   917
                       lhs
blanchet@49536
   918
                     else
blanchet@49536
   919
                       HOLogic.mk_eq (lhs, mk_rhs ())
blanchet@49536
   920
                   else
blanchet@49536
   921
                     HOLogic.mk_not lhs)
blanchet@49536
   922
              end;
blanchet@49536
   923
blanchet@49536
   924
(*###*)
blanchet@49536
   925
          (* TODO: Prove and exploit symmetry of relators to halve the number of goals. *)
blanchet@49536
   926
          fun mk_goals threl xctrs xss yctrs yss =
blanchet@49536
   927
            map_product (mk_goal threl) (xctrs ~~ xss) (yctrs ~~ yss);
blanchet@49536
   928
blanchet@49536
   929
          val goalsss = map5 mk_goals threls xctrss xsss yctrss ysss;
blanchet@49536
   930
blanchet@49536
   931
(*###
blanchet@49536
   932
            val goalsss = map6 (fn threl =>
blanchet@49536
   933
              map5 (fn xctr => fn xs => fn sels =>
blanchet@49536
   934
                map2 (mk_goal threl xctr xs sels))) threls xctrss xsss selsss yctrss ysss;
blanchet@49536
   935
*)
blanchet@49536
   936
val _ = tracing ("goalsss: " ^ PolyML.makestring goalsss) (*###*)
blanchet@49536
   937
          in
blanchet@49536
   938
            ([], [])
blanchet@49536
   939
          end;
blanchet@49536
   940
blanchet@49536
   941
        val (sel_rel_thmss, sel_rel_thmsss) =
blanchet@49536
   942
          let
blanchet@49536
   943
          in
blanchet@49536
   944
            ([], [])
blanchet@49536
   945
          end;
blanchet@49536
   946
blanchet@49536
   947
        val notes =
blanchet@49536
   948
          [(* (relsN, rel_thmss, []),
blanchet@49536
   949
           (sel_relsN, sel_rel_thmss, []) *)]
blanchet@49536
   950
          |> maps (fn (thmN, thmss, attrs) =>
blanchet@49536
   951
            map2 (fn b => fn thms =>
blanchet@49536
   952
                ((Binding.qualify true (Binding.name_of b) (Binding.name thmN), attrs),
blanchet@49536
   953
              [(thms, [])])) fp_bs thmss);
blanchet@49536
   954
      in
blanchet@49536
   955
        lthy |> Local_Theory.notes notes |> snd
blanchet@49536
   956
      end;
blanchet@49287
   957
blanchet@49204
   958
    val lthy' = lthy
blanchet@49504
   959
      |> fold_map define_ctrs_case_for_type (fp_bs ~~ fpTs ~~ Cs ~~ ctors ~~ dtors ~~ fp_folds ~~
blanchet@49501
   960
        fp_recs ~~ ctor_dtors ~~ dtor_ctors ~~ ctor_injects ~~ ns ~~ kss ~~ mss ~~ ctr_bindingss ~~
blanchet@49370
   961
        ctr_mixfixess ~~ ctr_Tsss ~~ disc_bindingss ~~ sel_bindingsss ~~ raw_sel_defaultsss)
blanchet@49504
   962
      |>> split_list |> wrap_types_and_define_rec_likes
blanchet@49518
   963
      |> `(if lfp then derive_induct_fold_rec_thms_for_types
blanchet@49518
   964
           else derive_coinduct_unfold_corec_thms_for_types)
blanchet@49518
   965
      |> swap |>> fst
blanchet@49536
   966
      |> (if null rels then snd else derive_rel_thms_for_types);
blanchet@49167
   967
blanchet@49167
   968
    val timer = time (timer ("Constructors, discriminators, selectors, etc., for the new " ^
blanchet@49208
   969
      (if lfp then "" else "co") ^ "datatype"));
blanchet@49112
   970
  in
blanchet@49308
   971
    timer; lthy'
blanchet@49112
   972
  end;
blanchet@49112
   973
blanchet@49536
   974
val datatypes = define_datatypes (K I) (K I) (K I);
blanchet@49297
   975
blanchet@49536
   976
val datatype_cmd = define_datatypes Typedecl.read_constraint Syntax.parse_typ Syntax.read_term;
blanchet@49119
   977
blanchet@49112
   978
val parse_ctr_arg =
blanchet@49329
   979
  @{keyword "("} |-- parse_binding_colon -- Parse.typ --| @{keyword ")"} ||
traytel@49434
   980
  (Parse.typ >> pair Binding.empty);
blanchet@49112
   981
blanchet@49286
   982
val parse_defaults =
blanchet@49286
   983
  @{keyword "("} |-- @{keyword "defaults"} |-- Scan.repeat parse_bound_term --| @{keyword ")"};
blanchet@49286
   984
blanchet@49112
   985
val parse_single_spec =
blanchet@49112
   986
  Parse.type_args_constrained -- Parse.binding -- Parse.opt_mixfix --
blanchet@49119
   987
  (@{keyword "="} |-- Parse.enum1 "|" (parse_opt_binding_colon -- Parse.binding --
blanchet@49286
   988
    Scan.repeat parse_ctr_arg -- Scan.optional parse_defaults [] -- Parse.opt_mixfix));
blanchet@49112
   989
blanchet@49278
   990
val parse_datatype = parse_wrap_options -- Parse.and_list1 parse_single_spec;
blanchet@49278
   991
blanchet@49308
   992
fun parse_datatype_cmd lfp construct = parse_datatype >> datatype_cmd lfp construct;
blanchet@49112
   993
blanchet@49112
   994
end;