src/HOL/Codatatype/Tools/bnf_fp_sugar.ML
author blanchet
Sat Sep 08 21:04:26 2012 +0200 (2012-09-08)
changeset 49208 3f73424f86a7
parent 49207 4634c217b77b
child 49209 3c0deda51b32
permissions -rw-r--r--
tuning
blanchet@49112
     1
(*  Title:      HOL/Codatatype/Tools/bnf_fp_sugar.ML
blanchet@49112
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@49112
     3
    Copyright   2012
blanchet@49112
     4
blanchet@49112
     5
Sugar for constructing LFPs and GFPs.
blanchet@49112
     6
*)
blanchet@49112
     7
blanchet@49112
     8
signature BNF_FP_SUGAR =
blanchet@49112
     9
sig
blanchet@49205
    10
  (* TODO: programmatic interface *)
blanchet@49112
    11
end;
blanchet@49112
    12
blanchet@49112
    13
structure BNF_FP_Sugar : BNF_FP_SUGAR =
blanchet@49112
    14
struct
blanchet@49112
    15
blanchet@49119
    16
open BNF_Util
blanchet@49119
    17
open BNF_Wrap
blanchet@49119
    18
open BNF_FP_Util
blanchet@49119
    19
open BNF_LFP
blanchet@49119
    20
open BNF_GFP
blanchet@49123
    21
open BNF_FP_Sugar_Tactics
blanchet@49119
    22
blanchet@49129
    23
val caseN = "case";
blanchet@49202
    24
val itersN = "iters";
blanchet@49202
    25
val recsN = "recs";
blanchet@49129
    26
blanchet@49205
    27
fun split_list7 xs = (map #1 xs, map #2 xs, map #3 xs, map #4 xs, map #5 xs, map #6 xs, map #7 xs);
blanchet@49205
    28
blanchet@49199
    29
fun retype_free (Free (s, _)) T = Free (s, T);
blanchet@49199
    30
blanchet@49202
    31
fun flat_list_comb (f, xss) = fold (fn xs => fn t => Term.list_comb (t, xs)) xss f
blanchet@49202
    32
blanchet@49200
    33
fun mk_tupled_fun x f xs = HOLogic.tupled_lambda x (Term.list_comb (f, xs));
blanchet@49200
    34
fun mk_uncurried_fun f xs = mk_tupled_fun (HOLogic.mk_tuple xs) f xs;
blanchet@49202
    35
fun mk_uncurried2_fun f xss =
blanchet@49200
    36
  mk_tupled_fun (HOLogic.mk_tuple (map HOLogic.mk_tuple xss)) f (flat xss);
blanchet@49200
    37
blanchet@49124
    38
fun cannot_merge_types () = error "Mutually recursive types must have the same type parameters";
blanchet@49119
    39
blanchet@49119
    40
fun merge_type_arg_constrained ctxt (T, c) (T', c') =
blanchet@49119
    41
  if T = T' then
blanchet@49119
    42
    (case (c, c') of
blanchet@49119
    43
      (_, NONE) => (T, c)
blanchet@49119
    44
    | (NONE, _) => (T, c')
blanchet@49119
    45
    | _ =>
blanchet@49119
    46
      if c = c' then
blanchet@49119
    47
        (T, c)
blanchet@49119
    48
      else
blanchet@49119
    49
        error ("Inconsistent sort constraints for type variable " ^
blanchet@49119
    50
          quote (Syntax.string_of_typ ctxt T)))
blanchet@49119
    51
  else
blanchet@49119
    52
    cannot_merge_types ();
blanchet@49119
    53
blanchet@49119
    54
fun merge_type_args_constrained ctxt (cAs, cAs') =
blanchet@49119
    55
  if length cAs = length cAs' then map2 (merge_type_arg_constrained ctxt) cAs cAs'
blanchet@49119
    56
  else cannot_merge_types ();
blanchet@49119
    57
blanchet@49121
    58
fun type_args_constrained_of (((cAs, _), _), _) = cAs;
blanchet@49121
    59
val type_args_of = map fst o type_args_constrained_of;
blanchet@49129
    60
fun type_binder_of (((_, b), _), _) = b;
blanchet@49181
    61
fun mixfix_of ((_, mx), _) = mx;
blanchet@49121
    62
fun ctr_specs_of (_, ctr_specs) = ctr_specs;
blanchet@49119
    63
blanchet@49121
    64
fun disc_of (((disc, _), _), _) = disc;
blanchet@49121
    65
fun ctr_of (((_, ctr), _), _) = ctr;
blanchet@49121
    66
fun args_of ((_, args), _) = args;
blanchet@49181
    67
fun ctr_mixfix_of (_, mx) = mx;
blanchet@49119
    68
blanchet@49208
    69
fun prepare_datatype prepare_typ lfp specs fake_lthy no_defs_lthy =
blanchet@49112
    70
  let
blanchet@49121
    71
    val constrained_As =
blanchet@49121
    72
      map (map (apfst (prepare_typ fake_lthy)) o type_args_constrained_of) specs
blanchet@49204
    73
      |> Library.foldr1 (merge_type_args_constrained no_defs_lthy);
blanchet@49121
    74
    val As = map fst constrained_As;
blanchet@49134
    75
    val As' = map dest_TFree As;
blanchet@49119
    76
blanchet@49121
    77
    val _ = (case duplicates (op =) As of [] => ()
blanchet@49204
    78
      | A :: _ => error ("Duplicate type parameter " ^
blanchet@49204
    79
          quote (Syntax.string_of_typ no_defs_lthy A)));
blanchet@49119
    80
blanchet@49119
    81
    (* TODO: use sort constraints on type args *)
blanchet@49119
    82
blanchet@49119
    83
    val N = length specs;
blanchet@49119
    84
blanchet@49182
    85
    fun mk_fake_T b =
blanchet@49121
    86
      Type (fst (Term.dest_Type (Proof_Context.read_type_name fake_lthy true (Binding.name_of b))),
blanchet@49121
    87
        As);
blanchet@49121
    88
blanchet@49129
    89
    val bs = map type_binder_of specs;
blanchet@49204
    90
    val fakeTs = map mk_fake_T bs;
blanchet@49121
    91
blanchet@49181
    92
    val mixfixes = map mixfix_of specs;
blanchet@49119
    93
blanchet@49119
    94
    val _ = (case duplicates Binding.eq_name bs of [] => ()
blanchet@49119
    95
      | b :: _ => error ("Duplicate type name declaration " ^ quote (Binding.name_of b)));
blanchet@49119
    96
blanchet@49121
    97
    val ctr_specss = map ctr_specs_of specs;
blanchet@49119
    98
blanchet@49129
    99
    val disc_binderss = map (map disc_of) ctr_specss;
blanchet@49129
   100
    val ctr_binderss = map (map ctr_of) ctr_specss;
blanchet@49121
   101
    val ctr_argsss = map (map args_of) ctr_specss;
blanchet@49181
   102
    val ctr_mixfixess = map (map ctr_mixfix_of) ctr_specss;
blanchet@49119
   103
blanchet@49129
   104
    val sel_bindersss = map (map (map fst)) ctr_argsss;
blanchet@49183
   105
    val fake_ctr_Tsss = map (map (map (prepare_typ fake_lthy o snd))) ctr_argsss;
blanchet@49121
   106
blanchet@49183
   107
    val rhs_As' = fold (fold (fold Term.add_tfreesT)) fake_ctr_Tsss [];
blanchet@49167
   108
    val _ = (case subtract (op =) As' rhs_As' of
blanchet@49165
   109
        [] => ()
blanchet@49165
   110
      | A' :: _ => error ("Extra type variables on rhs: " ^
blanchet@49204
   111
          quote (Syntax.string_of_typ no_defs_lthy (TFree A'))));
blanchet@49165
   112
blanchet@49176
   113
    val ((Cs, Xs), _) =
blanchet@49204
   114
      no_defs_lthy
blanchet@49121
   115
      |> fold (fold (fn s => Variable.declare_typ (TFree (s, dummyS))) o type_args_of) specs
blanchet@49121
   116
      |> mk_TFrees N
blanchet@49176
   117
      ||>> mk_TFrees N;
blanchet@49119
   118
blanchet@49204
   119
    fun eq_fpT (T as Type (s, Us)) (Type (s', Us')) =
blanchet@49146
   120
        s = s' andalso (Us = Us' orelse error ("Illegal occurrence of recursive type " ^
blanchet@49146
   121
          quote (Syntax.string_of_typ fake_lthy T)))
blanchet@49204
   122
      | eq_fpT _ _ = false;
blanchet@49146
   123
blanchet@49204
   124
    fun freeze_fp (T as Type (s, Us)) =
blanchet@49204
   125
        (case find_index (eq_fpT T) fakeTs of ~1 => Type (s, map freeze_fp Us) | j => nth Xs j)
blanchet@49204
   126
      | freeze_fp T = T;
blanchet@49121
   127
blanchet@49204
   128
    val ctr_TsssXs = map (map (map freeze_fp)) fake_ctr_Tsss;
blanchet@49176
   129
    val sum_prod_TsXs = map (mk_sumTN o map HOLogic.mk_tupleT) ctr_TsssXs;
blanchet@49119
   130
blanchet@49176
   131
    val eqs = map dest_TFree Xs ~~ sum_prod_TsXs;
blanchet@49121
   132
blanchet@49207
   133
    val (pre_map_defs, ((unfs0, flds0, fp_iters0, fp_recs0, unf_flds, fld_unfs, fld_injects,
blanchet@49207
   134
        fp_iter_thms, fp_rec_thms), lthy)) =
blanchet@49208
   135
      fp_bnf (if lfp then bnf_lfp else bnf_gfp) bs mixfixes As' eqs no_defs_lthy;
blanchet@49121
   136
blanchet@49167
   137
    val timer = time (Timer.startRealTimer ());
blanchet@49167
   138
blanchet@49176
   139
    fun mk_unf_or_fld get_T Ts t =
blanchet@49176
   140
      let val Type (_, Ts0) = get_T (fastype_of t) in
blanchet@49124
   141
        Term.subst_atomic_types (Ts0 ~~ Ts) t
blanchet@49121
   142
      end;
blanchet@49119
   143
blanchet@49126
   144
    val mk_unf = mk_unf_or_fld domain_type;
blanchet@49126
   145
    val mk_fld = mk_unf_or_fld range_type;
blanchet@49121
   146
blanchet@49203
   147
    val unfs = map (mk_unf As) unfs0;
blanchet@49203
   148
    val flds = map (mk_fld As) flds0;
blanchet@49124
   149
blanchet@49201
   150
    val fpTs = map (domain_type o fastype_of) unfs;
blanchet@49204
   151
    val is_fpT = member (op =) fpTs;
blanchet@49204
   152
blanchet@49201
   153
    val ctr_Tsss = map (map (map (Term.typ_subst_atomic (Xs ~~ fpTs)))) ctr_TsssXs;
blanchet@49203
   154
    val ns = map length ctr_Tsss;
blanchet@49203
   155
    val mss = map (map length) ctr_Tsss;
blanchet@49203
   156
    val Css = map2 replicate ns Cs;
blanchet@49203
   157
    val Cs' = flat Css;
blanchet@49203
   158
blanchet@49203
   159
    fun mk_iter_or_rec Ts Us c =
blanchet@49121
   160
      let
blanchet@49201
   161
        val (binders, body) = strip_type (fastype_of c);
blanchet@49203
   162
        val (fst_binders, last_binder) = split_last binders;
blanchet@49208
   163
        val Type (_, Ts0) = if lfp then last_binder else body;
blanchet@49208
   164
        val Us0 = map (if lfp then body_type else domain_type) fst_binders;
blanchet@49176
   165
      in
blanchet@49201
   166
        Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) c
blanchet@49176
   167
      end;
blanchet@49176
   168
blanchet@49204
   169
    val fp_iters as fp_iter1 :: _ = map (mk_iter_or_rec As Cs) fp_iters0;
blanchet@49204
   170
    val fp_recs as fp_rec1 :: _ = map (mk_iter_or_rec As Cs) fp_recs0;
blanchet@49204
   171
blanchet@49204
   172
    fun dest_rec_pair (T as Type (@{type_name prod}, Us as [_, U])) =
blanchet@49204
   173
        if member (op =) Cs U then Us else [T]
blanchet@49204
   174
      | dest_rec_pair T = [T];
blanchet@49204
   175
blanchet@49208
   176
    val ((gss, g_Tss, ysss, y_Tsss), (hss, h_Tss, zssss, z_Tssss)) =
blanchet@49208
   177
      if lfp then
blanchet@49208
   178
        let
blanchet@49208
   179
          val y_Tsss =
blanchet@49208
   180
            map3 (fn ms => fn n => map2 dest_tupleT ms o dest_sumTN n o domain_type) mss ns
blanchet@49208
   181
              (fst (split_last (binder_types (fastype_of fp_iter1))));
blanchet@49208
   182
          val g_Tss = map2 (map2 (curry (op --->))) y_Tsss Css;
blanchet@49208
   183
blanchet@49208
   184
          val ((gss, ysss), _) =
blanchet@49208
   185
            lthy
blanchet@49208
   186
            |> mk_Freess "f" g_Tss
blanchet@49208
   187
            ||>> mk_Freesss "x" y_Tsss;
blanchet@49204
   188
blanchet@49208
   189
          val z_Tssss =
blanchet@49208
   190
            map3 (fn ms => fn n => map2 (map dest_rec_pair oo dest_tupleT) ms o dest_sumTN n o domain_type) mss ns
blanchet@49208
   191
              (fst (split_last (binder_types (fastype_of fp_rec1))));
blanchet@49208
   192
          val h_Tss = map2 (map2 (fold_rev (curry (op --->)))) z_Tssss Css;
blanchet@49204
   193
blanchet@49208
   194
          val hss = map2 (map2 retype_free) gss h_Tss;
blanchet@49208
   195
          val (zssss, _) =
blanchet@49208
   196
            lthy
blanchet@49208
   197
            |> mk_Freessss "x" z_Tssss;
blanchet@49208
   198
        in ((gss, g_Tss, ysss, y_Tsss), (hss, h_Tss, zssss, z_Tssss)) end
blanchet@49208
   199
      else
blanchet@49208
   200
        (([], [], [], []), ([], [], [], [])); (* ### *)
blanchet@49176
   201
blanchet@49201
   202
    fun pour_sugar_on_type ((((((((((((((b, fpT), C), fld), unf), fp_iter), fp_rec), fld_unf),
blanchet@49176
   203
          unf_fld), fld_inject), ctr_binders), ctr_mixfixes), ctr_Tss), disc_binders), sel_binderss)
blanchet@49176
   204
        no_defs_lthy =
blanchet@49176
   205
      let
blanchet@49176
   206
        val n = length ctr_Tss;
blanchet@49121
   207
        val ks = 1 upto n;
blanchet@49121
   208
        val ms = map length ctr_Tss;
blanchet@49121
   209
blanchet@49201
   210
        val unfT = domain_type (fastype_of fld);
blanchet@49121
   211
        val prod_Ts = map HOLogic.mk_tupleT ctr_Tss;
blanchet@49134
   212
        val case_Ts = map (fn Ts => Ts ---> C) ctr_Tss;
blanchet@49119
   213
blanchet@49176
   214
        val ((((u, v), fs), xss), _) =
blanchet@49204
   215
          no_defs_lthy
blanchet@49201
   216
          |> yield_singleton (mk_Frees "u") unfT
blanchet@49201
   217
          ||>> yield_singleton (mk_Frees "v") fpT
blanchet@49176
   218
          ||>> mk_Frees "f" case_Ts
blanchet@49124
   219
          ||>> mk_Freess "x" ctr_Tss;
blanchet@49121
   220
blanchet@49129
   221
        val ctr_rhss =
blanchet@49121
   222
          map2 (fn k => fn xs =>
blanchet@49121
   223
            fold_rev Term.lambda xs (fld $ mk_InN prod_Ts (HOLogic.mk_tuple xs) k)) ks xss;
blanchet@49121
   224
blanchet@49130
   225
        val case_binder = Binding.suffix_name ("_" ^ caseN) b;
blanchet@49129
   226
blanchet@49134
   227
        val case_rhs =
blanchet@49176
   228
          fold_rev Term.lambda (fs @ [v]) (mk_sum_caseN (map2 mk_uncurried_fun fs xss) $ (unf $ v));
blanchet@49129
   229
blanchet@49201
   230
        val ((raw_case :: raw_ctrs, raw_case_def :: raw_ctr_defs), (lthy', lthy)) = no_defs_lthy
blanchet@49169
   231
          |> apfst split_list o fold_map3 (fn b => fn mx => fn rhs =>
blanchet@49169
   232
               Local_Theory.define ((b, mx), ((Thm.def_binding b, []), rhs)) #>> apsnd snd)
blanchet@49201
   233
             (case_binder :: ctr_binders) (NoSyn :: ctr_mixfixes) (case_rhs :: ctr_rhss)
blanchet@49121
   234
          ||> `Local_Theory.restore;
blanchet@49121
   235
blanchet@49121
   236
        (*transforms defined frees into consts (and more)*)
blanchet@49121
   237
        val phi = Proof_Context.export_morphism lthy lthy';
blanchet@49121
   238
blanchet@49121
   239
        val ctr_defs = map (Morphism.thm phi) raw_ctr_defs;
blanchet@49130
   240
        val case_def = Morphism.thm phi raw_case_def;
blanchet@49130
   241
blanchet@49203
   242
        val ctrs0 = map (Morphism.term phi) raw_ctrs;
blanchet@49203
   243
        val casex0 = Morphism.term phi raw_case;
blanchet@49203
   244
blanchet@49203
   245
        val ctrs = map (mk_ctr As) ctrs0;
blanchet@49121
   246
blanchet@49135
   247
        fun exhaust_tac {context = ctxt, ...} =
blanchet@49123
   248
          let
blanchet@49135
   249
            val fld_iff_unf_thm =
blanchet@49135
   250
              let
blanchet@49135
   251
                val goal =
blanchet@49135
   252
                  fold_rev Logic.all [u, v]
blanchet@49135
   253
                    (mk_Trueprop_eq (HOLogic.mk_eq (v, fld $ u), HOLogic.mk_eq (unf $ v, u)));
blanchet@49135
   254
              in
blanchet@49135
   255
                Skip_Proof.prove lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@49201
   256
                  mk_fld_iff_unf_tac ctxt (map (SOME o certifyT lthy) [unfT, fpT])
blanchet@49176
   257
                    (certify lthy fld) (certify lthy unf) fld_unf unf_fld)
blanchet@49135
   258
                |> Thm.close_derivation
blanchet@49135
   259
                |> Morphism.thm phi
blanchet@49135
   260
              end;
blanchet@49135
   261
blanchet@49135
   262
            val sumEN_thm' =
blanchet@49135
   263
              Local_Defs.unfold lthy @{thms all_unit_eq}
blanchet@49135
   264
                (Drule.instantiate' (map (SOME o certifyT lthy) prod_Ts) [] (mk_sumEN n))
blanchet@49135
   265
              |> Morphism.thm phi;
blanchet@49123
   266
          in
blanchet@49161
   267
            mk_exhaust_tac ctxt n ctr_defs fld_iff_unf_thm sumEN_thm'
blanchet@49123
   268
          end;
blanchet@49121
   269
blanchet@49126
   270
        val inject_tacss =
blanchet@49205
   271
          map2 (fn 0 => K [] | _ => fn ctr_def => [fn {context = ctxt, ...} =>
blanchet@49205
   272
              mk_inject_tac ctxt ctr_def fld_inject]) ms ctr_defs;
blanchet@49126
   273
blanchet@49127
   274
        val half_distinct_tacss =
blanchet@49127
   275
          map (map (fn (def, def') => fn {context = ctxt, ...} =>
blanchet@49127
   276
            mk_half_distinct_tac ctxt fld_inject [def, def'])) (mk_half_pairss ctr_defs);
blanchet@49127
   277
blanchet@49130
   278
        val case_tacs =
blanchet@49130
   279
          map3 (fn k => fn m => fn ctr_def => fn {context = ctxt, ...} =>
blanchet@49130
   280
            mk_case_tac ctxt n k m case_def ctr_def unf_fld) ks ms ctr_defs;
blanchet@49121
   281
blanchet@49121
   282
        val tacss = [exhaust_tac] :: inject_tacss @ half_distinct_tacss @ [case_tacs];
blanchet@49134
   283
blanchet@49199
   284
        fun sugar_datatype no_defs_lthy =
blanchet@49134
   285
          let
blanchet@49208
   286
            val fpT_to_C = fpT --> C;
blanchet@49208
   287
            val iter_T = fold_rev (curry (op --->)) g_Tss fpT_to_C;
blanchet@49208
   288
            val rec_T = fold_rev (curry (op --->)) h_Tss fpT_to_C;
blanchet@49199
   289
blanchet@49199
   290
            val iter_binder = Binding.suffix_name ("_" ^ iterN) b;
blanchet@49199
   291
            val rec_binder = Binding.suffix_name ("_" ^ recN) b;
blanchet@49199
   292
blanchet@49199
   293
            val iter_free = Free (Binding.name_of iter_binder, iter_T);
blanchet@49199
   294
            val rec_free = Free (Binding.name_of rec_binder, rec_T);
blanchet@49199
   295
blanchet@49199
   296
            val iter_spec =
blanchet@49202
   297
              mk_Trueprop_eq (flat_list_comb (iter_free, gss),
blanchet@49199
   298
                Term.list_comb (fp_iter, map2 (mk_sum_caseN oo map2 mk_uncurried_fun) gss ysss));
blanchet@49199
   299
            val rec_spec =
blanchet@49202
   300
              mk_Trueprop_eq (flat_list_comb (rec_free, hss),
blanchet@49202
   301
                Term.list_comb (fp_rec, map2 (mk_sum_caseN oo map2 mk_uncurried2_fun) hss zssss));
blanchet@49199
   302
blanchet@49199
   303
            val (([raw_iter, raw_rec], [raw_iter_def, raw_rec_def]), (lthy', lthy)) = no_defs_lthy
blanchet@49201
   304
              |> apfst split_list o fold_map2 (fn b => fn spec =>
blanchet@49199
   305
                Specification.definition (SOME (b, NONE, NoSyn), ((Thm.def_binding b, []), spec))
blanchet@49201
   306
                #>> apsnd snd) [iter_binder, rec_binder] [iter_spec, rec_spec]
blanchet@49199
   307
              ||> `Local_Theory.restore;
blanchet@49201
   308
blanchet@49201
   309
            (*transforms defined frees into consts (and more)*)
blanchet@49201
   310
            val phi = Proof_Context.export_morphism lthy lthy';
blanchet@49201
   311
blanchet@49201
   312
            val iter_def = Morphism.thm phi raw_iter_def;
blanchet@49201
   313
            val rec_def = Morphism.thm phi raw_rec_def;
blanchet@49201
   314
blanchet@49203
   315
            val iter0 = Morphism.term phi raw_iter;
blanchet@49203
   316
            val rec0 = Morphism.term phi raw_rec;
blanchet@49203
   317
blanchet@49203
   318
            val iter = mk_iter_or_rec As Cs' iter0;
blanchet@49203
   319
            val recx = mk_iter_or_rec As Cs' rec0;
blanchet@49134
   320
          in
blanchet@49205
   321
            ((ctrs, iter, recx, xss, ctr_defs, iter_def, rec_def), lthy)
blanchet@49134
   322
          end;
blanchet@49134
   323
blanchet@49205
   324
        fun sugar_codatatype no_defs_lthy =
blanchet@49205
   325
          (([], @{term True}, @{term True}, [], [], TrueI, TrueI), no_defs_lthy);
blanchet@49119
   326
      in
blanchet@49203
   327
        wrap_datatype tacss ((ctrs0, casex0), (disc_binders, sel_binderss)) lthy'
blanchet@49208
   328
        |> (if lfp then sugar_datatype else sugar_codatatype)
blanchet@49119
   329
      end;
blanchet@49167
   330
blanchet@49205
   331
    fun pour_more_sugar_on_datatypes ((ctrss, iters, recs, xsss, ctr_defss, iter_defs, rec_defs),
blanchet@49205
   332
        lthy) =
blanchet@49202
   333
      let
blanchet@49202
   334
        val xctrss = map2 (map2 (curry Term.list_comb)) ctrss xsss;
blanchet@49204
   335
        val giters = map (fn iter => flat_list_comb (iter, gss)) iters;
blanchet@49204
   336
        val hrecs = map (fn recx => flat_list_comb (recx, hss)) recs;
blanchet@49201
   337
blanchet@49202
   338
        val (iter_thmss, rec_thmss) =
blanchet@49207
   339
          let
blanchet@49204
   340
            fun mk_goal_iter_or_rec fss fc xctr f xs xs' =
blanchet@49207
   341
              fold_rev (fold_rev Logic.all) (xs :: fss)
blanchet@49207
   342
                (mk_Trueprop_eq (fc $ xctr, Term.list_comb (f, xs')));
blanchet@49204
   343
blanchet@49204
   344
            fun fix_iter_free (x as Free (_, T)) =
blanchet@49204
   345
              (case find_index (eq_fpT T) fpTs of ~1 => x | j => nth giters j $ x);
blanchet@49204
   346
            fun fix_rec_free (x as Free (_, T)) =
blanchet@49204
   347
              (case find_index (eq_fpT T) fpTs of ~1 => [x] | j => [x, nth hrecs j $ x]);
blanchet@49201
   348
blanchet@49204
   349
            val iter_xsss = map (map (map fix_iter_free)) xsss;
blanchet@49204
   350
            val rec_xsss = map (map (maps fix_rec_free)) xsss;
blanchet@49204
   351
blanchet@49204
   352
            val goal_iterss =
blanchet@49204
   353
              map5 (map4 o mk_goal_iter_or_rec gss) giters xctrss gss xsss iter_xsss;
blanchet@49204
   354
            val goal_recss =
blanchet@49204
   355
              map5 (map4 o mk_goal_iter_or_rec hss) hrecs xctrss hss xsss rec_xsss;
blanchet@49204
   356
blanchet@49203
   357
            val iter_tacss =
blanchet@49207
   358
              map2 (map o mk_iter_or_rec_tac pre_map_defs iter_defs) fp_iter_thms ctr_defss;
blanchet@49203
   359
            val rec_tacss =
blanchet@49207
   360
              map2 (map o mk_iter_or_rec_tac pre_map_defs rec_defs) fp_rec_thms ctr_defss;
blanchet@49202
   361
          in
blanchet@49205
   362
            (map2 (map2 (fn goal => fn tac => Skip_Proof.prove lthy [] [] goal (tac o #context)))
blanchet@49205
   363
               goal_iterss iter_tacss,
blanchet@49205
   364
             map2 (map2 (fn goal => fn tac => Skip_Proof.prove lthy [] [] goal (tac o #context)))
blanchet@49205
   365
               goal_recss rec_tacss)
blanchet@49202
   366
          end;
blanchet@49201
   367
blanchet@49202
   368
        val notes =
blanchet@49202
   369
          [(itersN, iter_thmss),
blanchet@49202
   370
           (recsN, rec_thmss)]
blanchet@49202
   371
          |> maps (fn (thmN, thmss) =>
blanchet@49202
   372
            map2 (fn b => fn thms =>
blanchet@49202
   373
                ((Binding.qualify true (Binding.name_of b) (Binding.name thmN), []), [(thms, [])]))
blanchet@49202
   374
              bs thmss);
blanchet@49202
   375
      in
blanchet@49202
   376
        lthy |> Local_Theory.notes notes |> snd
blanchet@49202
   377
      end;
blanchet@49202
   378
blanchet@49204
   379
    val lthy' = lthy
blanchet@49202
   380
      |> fold_map pour_sugar_on_type (bs ~~ fpTs ~~ Cs ~~ flds ~~ unfs ~~ fp_iters ~~ fp_recs ~~
blanchet@49176
   381
        fld_unfs ~~ unf_flds ~~ fld_injects ~~ ctr_binderss ~~ ctr_mixfixess ~~ ctr_Tsss ~~
blanchet@49202
   382
        disc_binderss ~~ sel_bindersss)
blanchet@49205
   383
      |>> split_list7
blanchet@49208
   384
      |> (if lfp then pour_more_sugar_on_datatypes else snd);
blanchet@49167
   385
blanchet@49167
   386
    val timer = time (timer ("Constructors, discriminators, selectors, etc., for the new " ^
blanchet@49208
   387
      (if lfp then "" else "co") ^ "datatype"));
blanchet@49112
   388
  in
blanchet@49204
   389
    (timer; lthy')
blanchet@49112
   390
  end;
blanchet@49112
   391
blanchet@49199
   392
fun datatype_cmd info specs lthy =
blanchet@49121
   393
  let
blanchet@49184
   394
    (*the "perhaps o try" below helps gracefully handles the case where the new type is defined in a
blanchet@49184
   395
      locale and shadows an existing global type*)
blanchet@49179
   396
    val fake_thy = Theory.copy
blanchet@49184
   397
      #> fold (fn spec => perhaps (try (Sign.add_type lthy
blanchet@49184
   398
        (type_binder_of spec, length (type_args_constrained_of spec), mixfix_of spec)))) specs;
blanchet@49179
   399
    val fake_lthy = Proof_Context.background_theory fake_thy lthy;
blanchet@49121
   400
  in
blanchet@49199
   401
    prepare_datatype Syntax.read_typ info specs fake_lthy lthy
blanchet@49121
   402
  end;
blanchet@49119
   403
blanchet@49129
   404
val parse_opt_binding_colon = Scan.optional (Parse.binding --| Parse.$$$ ":") no_binder
blanchet@49119
   405
blanchet@49112
   406
val parse_ctr_arg =
blanchet@49119
   407
  Parse.$$$ "(" |-- parse_opt_binding_colon -- Parse.typ --| Parse.$$$ ")" ||
blanchet@49129
   408
  (Parse.typ >> pair no_binder);
blanchet@49112
   409
blanchet@49112
   410
val parse_single_spec =
blanchet@49112
   411
  Parse.type_args_constrained -- Parse.binding -- Parse.opt_mixfix --
blanchet@49119
   412
  (@{keyword "="} |-- Parse.enum1 "|" (parse_opt_binding_colon -- Parse.binding --
blanchet@49119
   413
    Scan.repeat parse_ctr_arg -- Parse.opt_mixfix));
blanchet@49112
   414
blanchet@49112
   415
val _ =
blanchet@49112
   416
  Outer_Syntax.local_theory @{command_spec "data"} "define BNF-based inductive datatypes"
blanchet@49208
   417
    (Parse.and_list1 parse_single_spec >> datatype_cmd true);
blanchet@49112
   418
blanchet@49112
   419
val _ =
blanchet@49112
   420
  Outer_Syntax.local_theory @{command_spec "codata"} "define BNF-based coinductive datatypes"
blanchet@49208
   421
    (Parse.and_list1 parse_single_spec >> datatype_cmd false);
blanchet@49112
   422
blanchet@49112
   423
end;