src/HOL/Codatatype/Tools/bnf_fp_sugar.ML
author blanchet
Sat Sep 08 21:04:26 2012 +0200 (2012-09-08)
changeset 49213 975ccb0130cb
parent 49212 ca59649170b0
child 49214 2a3cb4c71b87
permissions -rw-r--r--
some work on coiter tactic
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@49213
    24
val coitersN = "coiters";
blanchet@49213
    25
val corecsN = "corecs";
blanchet@49202
    26
val itersN = "iters";
blanchet@49202
    27
val recsN = "recs";
blanchet@49129
    28
blanchet@49205
    29
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
    30
blanchet@49199
    31
fun retype_free (Free (s, _)) T = Free (s, T);
blanchet@49199
    32
blanchet@49212
    33
val lists_bmoc = fold (fn xs => fn t => Term.list_comb (t, xs))
blanchet@49202
    34
blanchet@49200
    35
fun mk_tupled_fun x f xs = HOLogic.tupled_lambda x (Term.list_comb (f, xs));
blanchet@49200
    36
fun mk_uncurried_fun f xs = mk_tupled_fun (HOLogic.mk_tuple xs) f xs;
blanchet@49202
    37
fun mk_uncurried2_fun f xss =
blanchet@49200
    38
  mk_tupled_fun (HOLogic.mk_tuple (map HOLogic.mk_tuple xss)) f (flat xss);
blanchet@49200
    39
blanchet@49212
    40
fun popescu_zip [] [fs] = fs
blanchet@49212
    41
  | popescu_zip (p :: ps) (fs :: fss) = p :: fs @ popescu_zip ps fss;
blanchet@49212
    42
blanchet@49124
    43
fun cannot_merge_types () = error "Mutually recursive types must have the same type parameters";
blanchet@49119
    44
blanchet@49119
    45
fun merge_type_arg_constrained ctxt (T, c) (T', c') =
blanchet@49119
    46
  if T = T' then
blanchet@49119
    47
    (case (c, c') of
blanchet@49119
    48
      (_, NONE) => (T, c)
blanchet@49119
    49
    | (NONE, _) => (T, c')
blanchet@49119
    50
    | _ =>
blanchet@49119
    51
      if c = c' then
blanchet@49119
    52
        (T, c)
blanchet@49119
    53
      else
blanchet@49119
    54
        error ("Inconsistent sort constraints for type variable " ^
blanchet@49119
    55
          quote (Syntax.string_of_typ ctxt T)))
blanchet@49119
    56
  else
blanchet@49119
    57
    cannot_merge_types ();
blanchet@49119
    58
blanchet@49119
    59
fun merge_type_args_constrained ctxt (cAs, cAs') =
blanchet@49119
    60
  if length cAs = length cAs' then map2 (merge_type_arg_constrained ctxt) cAs cAs'
blanchet@49119
    61
  else cannot_merge_types ();
blanchet@49119
    62
blanchet@49121
    63
fun type_args_constrained_of (((cAs, _), _), _) = cAs;
blanchet@49121
    64
val type_args_of = map fst o type_args_constrained_of;
blanchet@49129
    65
fun type_binder_of (((_, b), _), _) = b;
blanchet@49181
    66
fun mixfix_of ((_, mx), _) = mx;
blanchet@49121
    67
fun ctr_specs_of (_, ctr_specs) = ctr_specs;
blanchet@49119
    68
blanchet@49121
    69
fun disc_of (((disc, _), _), _) = disc;
blanchet@49121
    70
fun ctr_of (((_, ctr), _), _) = ctr;
blanchet@49121
    71
fun args_of ((_, args), _) = args;
blanchet@49181
    72
fun ctr_mixfix_of (_, mx) = mx;
blanchet@49119
    73
blanchet@49208
    74
fun prepare_datatype prepare_typ lfp specs fake_lthy no_defs_lthy =
blanchet@49112
    75
  let
blanchet@49121
    76
    val constrained_As =
blanchet@49121
    77
      map (map (apfst (prepare_typ fake_lthy)) o type_args_constrained_of) specs
blanchet@49204
    78
      |> Library.foldr1 (merge_type_args_constrained no_defs_lthy);
blanchet@49121
    79
    val As = map fst constrained_As;
blanchet@49134
    80
    val As' = map dest_TFree As;
blanchet@49119
    81
blanchet@49121
    82
    val _ = (case duplicates (op =) As of [] => ()
blanchet@49204
    83
      | A :: _ => error ("Duplicate type parameter " ^
blanchet@49204
    84
          quote (Syntax.string_of_typ no_defs_lthy A)));
blanchet@49119
    85
blanchet@49119
    86
    (* TODO: use sort constraints on type args *)
blanchet@49119
    87
blanchet@49119
    88
    val N = length specs;
blanchet@49119
    89
blanchet@49182
    90
    fun mk_fake_T b =
blanchet@49121
    91
      Type (fst (Term.dest_Type (Proof_Context.read_type_name fake_lthy true (Binding.name_of b))),
blanchet@49121
    92
        As);
blanchet@49121
    93
blanchet@49129
    94
    val bs = map type_binder_of specs;
blanchet@49204
    95
    val fakeTs = map mk_fake_T bs;
blanchet@49121
    96
blanchet@49181
    97
    val mixfixes = map mixfix_of specs;
blanchet@49119
    98
blanchet@49119
    99
    val _ = (case duplicates Binding.eq_name bs of [] => ()
blanchet@49119
   100
      | b :: _ => error ("Duplicate type name declaration " ^ quote (Binding.name_of b)));
blanchet@49119
   101
blanchet@49121
   102
    val ctr_specss = map ctr_specs_of specs;
blanchet@49119
   103
blanchet@49129
   104
    val disc_binderss = map (map disc_of) ctr_specss;
blanchet@49129
   105
    val ctr_binderss = map (map ctr_of) ctr_specss;
blanchet@49121
   106
    val ctr_argsss = map (map args_of) ctr_specss;
blanchet@49181
   107
    val ctr_mixfixess = map (map ctr_mixfix_of) ctr_specss;
blanchet@49119
   108
blanchet@49129
   109
    val sel_bindersss = map (map (map fst)) ctr_argsss;
blanchet@49183
   110
    val fake_ctr_Tsss = map (map (map (prepare_typ fake_lthy o snd))) ctr_argsss;
blanchet@49121
   111
blanchet@49183
   112
    val rhs_As' = fold (fold (fold Term.add_tfreesT)) fake_ctr_Tsss [];
blanchet@49167
   113
    val _ = (case subtract (op =) As' rhs_As' of
blanchet@49165
   114
        [] => ()
blanchet@49165
   115
      | A' :: _ => error ("Extra type variables on rhs: " ^
blanchet@49204
   116
          quote (Syntax.string_of_typ no_defs_lthy (TFree A'))));
blanchet@49165
   117
blanchet@49176
   118
    val ((Cs, Xs), _) =
blanchet@49204
   119
      no_defs_lthy
blanchet@49121
   120
      |> fold (fold (fn s => Variable.declare_typ (TFree (s, dummyS))) o type_args_of) specs
blanchet@49121
   121
      |> mk_TFrees N
blanchet@49176
   122
      ||>> mk_TFrees N;
blanchet@49119
   123
blanchet@49204
   124
    fun eq_fpT (T as Type (s, Us)) (Type (s', Us')) =
blanchet@49146
   125
        s = s' andalso (Us = Us' orelse error ("Illegal occurrence of recursive type " ^
blanchet@49146
   126
          quote (Syntax.string_of_typ fake_lthy T)))
blanchet@49204
   127
      | eq_fpT _ _ = false;
blanchet@49146
   128
blanchet@49204
   129
    fun freeze_fp (T as Type (s, Us)) =
blanchet@49204
   130
        (case find_index (eq_fpT T) fakeTs of ~1 => Type (s, map freeze_fp Us) | j => nth Xs j)
blanchet@49204
   131
      | freeze_fp T = T;
blanchet@49121
   132
blanchet@49204
   133
    val ctr_TsssXs = map (map (map freeze_fp)) fake_ctr_Tsss;
blanchet@49176
   134
    val sum_prod_TsXs = map (mk_sumTN o map HOLogic.mk_tupleT) ctr_TsssXs;
blanchet@49119
   135
blanchet@49176
   136
    val eqs = map dest_TFree Xs ~~ sum_prod_TsXs;
blanchet@49121
   137
blanchet@49207
   138
    val (pre_map_defs, ((unfs0, flds0, fp_iters0, fp_recs0, unf_flds, fld_unfs, fld_injects,
blanchet@49207
   139
        fp_iter_thms, fp_rec_thms), lthy)) =
blanchet@49208
   140
      fp_bnf (if lfp then bnf_lfp else bnf_gfp) bs mixfixes As' eqs no_defs_lthy;
blanchet@49121
   141
blanchet@49167
   142
    val timer = time (Timer.startRealTimer ());
blanchet@49167
   143
blanchet@49176
   144
    fun mk_unf_or_fld get_T Ts t =
blanchet@49176
   145
      let val Type (_, Ts0) = get_T (fastype_of t) in
blanchet@49124
   146
        Term.subst_atomic_types (Ts0 ~~ Ts) t
blanchet@49121
   147
      end;
blanchet@49119
   148
blanchet@49126
   149
    val mk_unf = mk_unf_or_fld domain_type;
blanchet@49126
   150
    val mk_fld = mk_unf_or_fld range_type;
blanchet@49121
   151
blanchet@49203
   152
    val unfs = map (mk_unf As) unfs0;
blanchet@49203
   153
    val flds = map (mk_fld As) flds0;
blanchet@49124
   154
blanchet@49201
   155
    val fpTs = map (domain_type o fastype_of) unfs;
blanchet@49204
   156
blanchet@49201
   157
    val ctr_Tsss = map (map (map (Term.typ_subst_atomic (Xs ~~ fpTs)))) ctr_TsssXs;
blanchet@49203
   158
    val ns = map length ctr_Tsss;
blanchet@49212
   159
    val kss = map (fn n => 1 upto n) ns;
blanchet@49203
   160
    val mss = map (map length) ctr_Tsss;
blanchet@49203
   161
    val Css = map2 replicate ns Cs;
blanchet@49203
   162
blanchet@49210
   163
    fun mk_iter_like Ts Us c =
blanchet@49121
   164
      let
blanchet@49201
   165
        val (binders, body) = strip_type (fastype_of c);
blanchet@49210
   166
        val (f_Us, prebody) = split_last binders;
blanchet@49210
   167
        val Type (_, Ts0) = if lfp then prebody else body;
blanchet@49210
   168
        val Us0 = distinct (op =) (map (if lfp then body_type else domain_type) f_Us);
blanchet@49176
   169
      in
blanchet@49201
   170
        Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) c
blanchet@49176
   171
      end;
blanchet@49176
   172
blanchet@49210
   173
    val fp_iters as fp_iter1 :: _ = map (mk_iter_like As Cs) fp_iters0;
blanchet@49210
   174
    val fp_recs as fp_rec1 :: _ = map (mk_iter_like As Cs) fp_recs0;
blanchet@49210
   175
blanchet@49212
   176
    val fp_iter_fun_Ts = fst (split_last (binder_types (fastype_of fp_iter1)));
blanchet@49212
   177
    val fp_rec_fun_Ts = fst (split_last (binder_types (fastype_of fp_rec1)));
blanchet@49204
   178
blanchet@49204
   179
    fun dest_rec_pair (T as Type (@{type_name prod}, Us as [_, U])) =
blanchet@49204
   180
        if member (op =) Cs U then Us else [T]
blanchet@49204
   181
      | dest_rec_pair T = [T];
blanchet@49204
   182
blanchet@49212
   183
    val (((gss, g_Tss, ysss), (hss, h_Tss, zssss)),
blanchet@49212
   184
         (cs, cpss, p_Tss, coiter_extra as ((pgss, cgsss), g_sum_prod_Ts, g_prod_Tss, g_Tsss),
blanchet@49212
   185
          corec_extra as ((phss, chsss), h_sum_prod_Ts, h_prod_Tss, h_Tsss))) =
blanchet@49208
   186
      if lfp then
blanchet@49208
   187
        let
blanchet@49208
   188
          val y_Tsss =
blanchet@49210
   189
            map3 (fn n => fn ms => map2 dest_tupleT ms o dest_sumTN n o domain_type)
blanchet@49212
   190
              ns mss fp_iter_fun_Ts;
blanchet@49208
   191
          val g_Tss = map2 (map2 (curry (op --->))) y_Tsss Css;
blanchet@49208
   192
blanchet@49208
   193
          val ((gss, ysss), _) =
blanchet@49208
   194
            lthy
blanchet@49208
   195
            |> mk_Freess "f" g_Tss
blanchet@49208
   196
            ||>> mk_Freesss "x" y_Tsss;
blanchet@49204
   197
blanchet@49208
   198
          val z_Tssss =
blanchet@49210
   199
            map3 (fn n => fn ms => map2 (map dest_rec_pair oo dest_tupleT) ms o dest_sumTN n
blanchet@49212
   200
              o domain_type) ns mss fp_rec_fun_Ts;
blanchet@49208
   201
          val h_Tss = map2 (map2 (fold_rev (curry (op --->)))) z_Tssss Css;
blanchet@49204
   202
blanchet@49208
   203
          val hss = map2 (map2 retype_free) gss h_Tss;
blanchet@49208
   204
          val (zssss, _) =
blanchet@49208
   205
            lthy
blanchet@49208
   206
            |> mk_Freessss "x" z_Tssss;
blanchet@49210
   207
        in
blanchet@49212
   208
          (((gss, g_Tss, ysss), (hss, h_Tss, zssss)),
blanchet@49212
   209
           ([], [], [], (([], []), [], [], []), (([], []), [], [], [])))
blanchet@49210
   210
        end
blanchet@49208
   211
      else
blanchet@49210
   212
        let
blanchet@49211
   213
          val p_Tss =
blanchet@49210
   214
            map2 (fn C => fn n => replicate (Int.max (0, n - 1)) (C --> HOLogic.boolT)) Cs ns;
blanchet@49211
   215
blanchet@49212
   216
          fun mk_types fun_Ts =
blanchet@49212
   217
            let
blanchet@49212
   218
              val f_sum_prod_Ts = map range_type fun_Ts;
blanchet@49212
   219
              val f_prod_Tss = map2 dest_sumTN ns f_sum_prod_Ts;
blanchet@49212
   220
              val f_Tsss =
blanchet@49212
   221
                map3 (fn C => map2 (map (curry (op -->) C) oo dest_tupleT)) Cs mss f_prod_Tss;
blanchet@49212
   222
              val pf_Tss = map2 popescu_zip p_Tss f_Tsss
blanchet@49212
   223
            in (f_sum_prod_Ts, f_prod_Tss, f_Tsss, pf_Tss) end;
blanchet@49176
   224
blanchet@49212
   225
          val (g_sum_prod_Ts, g_prod_Tss, g_Tsss, pg_Tss) = mk_types fp_iter_fun_Ts;
blanchet@49212
   226
          val (h_sum_prod_Ts, h_prod_Tss, h_Tsss, ph_Tss) = mk_types fp_rec_fun_Ts;
blanchet@49211
   227
blanchet@49211
   228
          val (((c, pss), gsss), _) =
blanchet@49210
   229
            lthy
blanchet@49210
   230
            |> yield_singleton (mk_Frees "c") dummyT
blanchet@49211
   231
            ||>> mk_Freess "p" p_Tss
blanchet@49210
   232
            ||>> mk_Freesss "g" g_Tsss;
blanchet@49210
   233
blanchet@49211
   234
          val hsss = map2 (map2 (map2 retype_free)) gsss h_Tsss;
blanchet@49211
   235
blanchet@49210
   236
          val cs = map (retype_free c) Cs;
blanchet@49212
   237
          val cpss = map2 (fn c => map (fn p => p $ c)) cs pss;
blanchet@49212
   238
blanchet@49212
   239
          fun mk_terms fsss =
blanchet@49212
   240
            let
blanchet@49212
   241
              val pfss = map2 popescu_zip pss fsss;
blanchet@49212
   242
              val cfsss = map2 (fn c => map (map (fn f => f $ c))) cs fsss
blanchet@49212
   243
            in (pfss, cfsss) end;
blanchet@49210
   244
        in
blanchet@49212
   245
          ((([], [], []), ([], [], [])),
blanchet@49212
   246
           (cs, cpss, p_Tss, (mk_terms gsss, g_sum_prod_Ts, g_prod_Tss, pg_Tss),
blanchet@49212
   247
            (mk_terms hsss, h_sum_prod_Ts, h_prod_Tss, ph_Tss)))
blanchet@49210
   248
        end;
blanchet@49210
   249
blanchet@49212
   250
    fun pour_some_sugar_on_type (((((((((((((((((b, fpT), C), fld), unf), fp_iter), fp_rec),
blanchet@49212
   251
          fld_unf), unf_fld), fld_inject), n), ks), ms), ctr_binders), ctr_mixfixes), ctr_Tss),
blanchet@49212
   252
        disc_binders), sel_binderss) no_defs_lthy =
blanchet@49176
   253
      let
blanchet@49201
   254
        val unfT = domain_type (fastype_of fld);
blanchet@49210
   255
        val ctr_prod_Ts = map HOLogic.mk_tupleT ctr_Tss;
blanchet@49134
   256
        val case_Ts = map (fn Ts => Ts ---> C) ctr_Tss;
blanchet@49119
   257
blanchet@49176
   258
        val ((((u, v), fs), xss), _) =
blanchet@49204
   259
          no_defs_lthy
blanchet@49201
   260
          |> yield_singleton (mk_Frees "u") unfT
blanchet@49201
   261
          ||>> yield_singleton (mk_Frees "v") fpT
blanchet@49176
   262
          ||>> mk_Frees "f" case_Ts
blanchet@49124
   263
          ||>> mk_Freess "x" ctr_Tss;
blanchet@49121
   264
blanchet@49129
   265
        val ctr_rhss =
blanchet@49121
   266
          map2 (fn k => fn xs =>
blanchet@49210
   267
            fold_rev Term.lambda xs (fld $ mk_InN ctr_prod_Ts (HOLogic.mk_tuple xs) k)) ks xss;
blanchet@49121
   268
blanchet@49130
   269
        val case_binder = Binding.suffix_name ("_" ^ caseN) b;
blanchet@49129
   270
blanchet@49134
   271
        val case_rhs =
blanchet@49176
   272
          fold_rev Term.lambda (fs @ [v]) (mk_sum_caseN (map2 mk_uncurried_fun fs xss) $ (unf $ v));
blanchet@49129
   273
blanchet@49201
   274
        val ((raw_case :: raw_ctrs, raw_case_def :: raw_ctr_defs), (lthy', lthy)) = no_defs_lthy
blanchet@49169
   275
          |> apfst split_list o fold_map3 (fn b => fn mx => fn rhs =>
blanchet@49169
   276
               Local_Theory.define ((b, mx), ((Thm.def_binding b, []), rhs)) #>> apsnd snd)
blanchet@49201
   277
             (case_binder :: ctr_binders) (NoSyn :: ctr_mixfixes) (case_rhs :: ctr_rhss)
blanchet@49121
   278
          ||> `Local_Theory.restore;
blanchet@49121
   279
blanchet@49121
   280
        (*transforms defined frees into consts (and more)*)
blanchet@49121
   281
        val phi = Proof_Context.export_morphism lthy lthy';
blanchet@49121
   282
blanchet@49121
   283
        val ctr_defs = map (Morphism.thm phi) raw_ctr_defs;
blanchet@49130
   284
        val case_def = Morphism.thm phi raw_case_def;
blanchet@49130
   285
blanchet@49203
   286
        val ctrs0 = map (Morphism.term phi) raw_ctrs;
blanchet@49203
   287
        val casex0 = Morphism.term phi raw_case;
blanchet@49203
   288
blanchet@49203
   289
        val ctrs = map (mk_ctr As) ctrs0;
blanchet@49121
   290
blanchet@49135
   291
        fun exhaust_tac {context = ctxt, ...} =
blanchet@49123
   292
          let
blanchet@49135
   293
            val fld_iff_unf_thm =
blanchet@49135
   294
              let
blanchet@49135
   295
                val goal =
blanchet@49135
   296
                  fold_rev Logic.all [u, v]
blanchet@49135
   297
                    (mk_Trueprop_eq (HOLogic.mk_eq (v, fld $ u), HOLogic.mk_eq (unf $ v, u)));
blanchet@49135
   298
              in
blanchet@49135
   299
                Skip_Proof.prove lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@49201
   300
                  mk_fld_iff_unf_tac ctxt (map (SOME o certifyT lthy) [unfT, fpT])
blanchet@49176
   301
                    (certify lthy fld) (certify lthy unf) fld_unf unf_fld)
blanchet@49135
   302
                |> Thm.close_derivation
blanchet@49135
   303
                |> Morphism.thm phi
blanchet@49135
   304
              end;
blanchet@49135
   305
blanchet@49135
   306
            val sumEN_thm' =
blanchet@49135
   307
              Local_Defs.unfold lthy @{thms all_unit_eq}
blanchet@49210
   308
                (Drule.instantiate' (map (SOME o certifyT lthy) ctr_prod_Ts) [] (mk_sumEN n))
blanchet@49135
   309
              |> Morphism.thm phi;
blanchet@49123
   310
          in
blanchet@49161
   311
            mk_exhaust_tac ctxt n ctr_defs fld_iff_unf_thm sumEN_thm'
blanchet@49123
   312
          end;
blanchet@49121
   313
blanchet@49126
   314
        val inject_tacss =
blanchet@49205
   315
          map2 (fn 0 => K [] | _ => fn ctr_def => [fn {context = ctxt, ...} =>
blanchet@49205
   316
              mk_inject_tac ctxt ctr_def fld_inject]) ms ctr_defs;
blanchet@49126
   317
blanchet@49127
   318
        val half_distinct_tacss =
blanchet@49127
   319
          map (map (fn (def, def') => fn {context = ctxt, ...} =>
blanchet@49127
   320
            mk_half_distinct_tac ctxt fld_inject [def, def'])) (mk_half_pairss ctr_defs);
blanchet@49127
   321
blanchet@49130
   322
        val case_tacs =
blanchet@49130
   323
          map3 (fn k => fn m => fn ctr_def => fn {context = ctxt, ...} =>
blanchet@49130
   324
            mk_case_tac ctxt n k m case_def ctr_def unf_fld) ks ms ctr_defs;
blanchet@49121
   325
blanchet@49121
   326
        val tacss = [exhaust_tac] :: inject_tacss @ half_distinct_tacss @ [case_tacs];
blanchet@49134
   327
blanchet@49210
   328
        fun some_lfp_sugar no_defs_lthy =
blanchet@49134
   329
          let
blanchet@49208
   330
            val fpT_to_C = fpT --> C;
blanchet@49208
   331
            val iter_T = fold_rev (curry (op --->)) g_Tss fpT_to_C;
blanchet@49208
   332
            val rec_T = fold_rev (curry (op --->)) h_Tss fpT_to_C;
blanchet@49199
   333
blanchet@49199
   334
            val iter_binder = Binding.suffix_name ("_" ^ iterN) b;
blanchet@49199
   335
            val rec_binder = Binding.suffix_name ("_" ^ recN) b;
blanchet@49199
   336
blanchet@49199
   337
            val iter_spec =
blanchet@49212
   338
              mk_Trueprop_eq (lists_bmoc gss (Free (Binding.name_of iter_binder, iter_T)),
blanchet@49199
   339
                Term.list_comb (fp_iter, map2 (mk_sum_caseN oo map2 mk_uncurried_fun) gss ysss));
blanchet@49199
   340
            val rec_spec =
blanchet@49212
   341
              mk_Trueprop_eq (lists_bmoc hss (Free (Binding.name_of rec_binder, rec_T)),
blanchet@49202
   342
                Term.list_comb (fp_rec, map2 (mk_sum_caseN oo map2 mk_uncurried2_fun) hss zssss));
blanchet@49199
   343
blanchet@49199
   344
            val (([raw_iter, raw_rec], [raw_iter_def, raw_rec_def]), (lthy', lthy)) = no_defs_lthy
blanchet@49201
   345
              |> apfst split_list o fold_map2 (fn b => fn spec =>
blanchet@49199
   346
                Specification.definition (SOME (b, NONE, NoSyn), ((Thm.def_binding b, []), spec))
blanchet@49201
   347
                #>> apsnd snd) [iter_binder, rec_binder] [iter_spec, rec_spec]
blanchet@49199
   348
              ||> `Local_Theory.restore;
blanchet@49201
   349
blanchet@49201
   350
            (*transforms defined frees into consts (and more)*)
blanchet@49201
   351
            val phi = Proof_Context.export_morphism lthy lthy';
blanchet@49201
   352
blanchet@49201
   353
            val iter_def = Morphism.thm phi raw_iter_def;
blanchet@49201
   354
            val rec_def = Morphism.thm phi raw_rec_def;
blanchet@49201
   355
blanchet@49203
   356
            val iter0 = Morphism.term phi raw_iter;
blanchet@49203
   357
            val rec0 = Morphism.term phi raw_rec;
blanchet@49203
   358
blanchet@49210
   359
            val iter = mk_iter_like As Cs iter0;
blanchet@49210
   360
            val recx = mk_iter_like As Cs rec0;
blanchet@49134
   361
          in
blanchet@49205
   362
            ((ctrs, iter, recx, xss, ctr_defs, iter_def, rec_def), lthy)
blanchet@49134
   363
          end;
blanchet@49134
   364
blanchet@49210
   365
        fun some_gfp_sugar no_defs_lthy =
blanchet@49210
   366
          let
blanchet@49210
   367
            val B_to_fpT = C --> fpT;
blanchet@49211
   368
blanchet@49212
   369
            fun generate_coiter_like (suf, fp_iter_like, ((pfss, cfsss), f_sum_prod_Ts, f_prod_Tss,
blanchet@49212
   370
                pf_Tss)) =
blanchet@49211
   371
              let
blanchet@49211
   372
                val res_T = fold_rev (curry (op --->)) pf_Tss B_to_fpT;
blanchet@49210
   373
blanchet@49211
   374
                val binder = Binding.suffix_name ("_" ^ suf) b;
blanchet@49210
   375
blanchet@49211
   376
                fun mk_join c n cps sum_prod_T prod_Ts cfss =
blanchet@49211
   377
                  Term.lambda c (mk_IfN sum_prod_T cps
blanchet@49211
   378
                    (map2 (mk_InN prod_Ts) (map HOLogic.mk_tuple cfss) (1 upto n)));
blanchet@49210
   379
blanchet@49211
   380
                val spec =
blanchet@49212
   381
                  mk_Trueprop_eq (lists_bmoc pfss (Free (Binding.name_of binder, res_T)),
blanchet@49211
   382
                    Term.list_comb (fp_iter_like,
blanchet@49211
   383
                      map6 mk_join cs ns cpss f_sum_prod_Ts f_prod_Tss cfsss));
blanchet@49211
   384
              in (binder, spec) end;
blanchet@49210
   385
blanchet@49212
   386
            val coiter_likes =
blanchet@49212
   387
              [(coiterN, fp_iter, coiter_extra),
blanchet@49212
   388
               (corecN, fp_rec, corec_extra)];
blanchet@49212
   389
blanchet@49211
   390
            val (binders, specs) = map generate_coiter_like coiter_likes |> split_list;
blanchet@49211
   391
blanchet@49211
   392
            val ((csts, defs), (lthy', lthy)) = no_defs_lthy
blanchet@49210
   393
              |> apfst split_list o fold_map2 (fn b => fn spec =>
blanchet@49210
   394
                Specification.definition (SOME (b, NONE, NoSyn), ((Thm.def_binding b, []), spec))
blanchet@49211
   395
                #>> apsnd snd) binders specs
blanchet@49210
   396
              ||> `Local_Theory.restore;
blanchet@49210
   397
blanchet@49210
   398
            (*transforms defined frees into consts (and more)*)
blanchet@49210
   399
            val phi = Proof_Context.export_morphism lthy lthy';
blanchet@49210
   400
blanchet@49211
   401
            val [coiter_def, corec_def] = map (Morphism.thm phi) defs;
blanchet@49210
   402
blanchet@49211
   403
            val [coiter, corec] = map (mk_iter_like As Cs o Morphism.term phi) csts;
blanchet@49210
   404
          in
blanchet@49210
   405
            ((ctrs, coiter, corec, xss, ctr_defs, coiter_def, corec_def), lthy)
blanchet@49210
   406
          end;
blanchet@49119
   407
      in
blanchet@49203
   408
        wrap_datatype tacss ((ctrs0, casex0), (disc_binders, sel_binderss)) lthy'
blanchet@49210
   409
        |> (if lfp then some_lfp_sugar else some_gfp_sugar)
blanchet@49119
   410
      end;
blanchet@49167
   411
blanchet@49212
   412
    fun pour_more_sugar_on_lfps ((ctrss, iters, recs, xsss, ctr_defss, iter_defs, rec_defs),
blanchet@49205
   413
        lthy) =
blanchet@49202
   414
      let
blanchet@49202
   415
        val xctrss = map2 (map2 (curry Term.list_comb)) ctrss xsss;
blanchet@49212
   416
        val giters = map (lists_bmoc gss) iters;
blanchet@49212
   417
        val hrecs = map (lists_bmoc hss) recs;
blanchet@49201
   418
blanchet@49202
   419
        val (iter_thmss, rec_thmss) =
blanchet@49207
   420
          let
blanchet@49212
   421
            fun mk_goal_iter_like fss fiter_like xctr f xs fxs =
blanchet@49207
   422
              fold_rev (fold_rev Logic.all) (xs :: fss)
blanchet@49212
   423
                (mk_Trueprop_eq (fiter_like $ xctr, Term.list_comb (f, fxs)));
blanchet@49204
   424
blanchet@49212
   425
            fun repair_iter_call (x as Free (_, T)) =
blanchet@49212
   426
              (case find_index (curry (op =) T) fpTs of ~1 => x | j => nth giters j $ x);
blanchet@49212
   427
            fun repair_rec_call (x as Free (_, T)) =
blanchet@49212
   428
              (case find_index (curry (op =) T) fpTs of ~1 => [x] | j => [x, nth hrecs j $ x]);
blanchet@49201
   429
blanchet@49212
   430
            val gxsss = map (map (map repair_iter_call)) xsss;
blanchet@49212
   431
            val hxsss = map (map (maps repair_rec_call)) xsss;
blanchet@49204
   432
blanchet@49212
   433
            val goal_iterss = map5 (map4 o mk_goal_iter_like gss) giters xctrss gss xsss gxsss;
blanchet@49212
   434
            val goal_recss = map5 (map4 o mk_goal_iter_like hss) hrecs xctrss hss xsss hxsss;
blanchet@49204
   435
blanchet@49203
   436
            val iter_tacss =
blanchet@49211
   437
              map2 (map o mk_iter_like_tac pre_map_defs iter_defs) fp_iter_thms ctr_defss;
blanchet@49203
   438
            val rec_tacss =
blanchet@49211
   439
              map2 (map o mk_iter_like_tac pre_map_defs rec_defs) fp_rec_thms ctr_defss;
blanchet@49202
   440
          in
blanchet@49205
   441
            (map2 (map2 (fn goal => fn tac => Skip_Proof.prove lthy [] [] goal (tac o #context)))
blanchet@49205
   442
               goal_iterss iter_tacss,
blanchet@49205
   443
             map2 (map2 (fn goal => fn tac => Skip_Proof.prove lthy [] [] goal (tac o #context)))
blanchet@49205
   444
               goal_recss rec_tacss)
blanchet@49202
   445
          end;
blanchet@49201
   446
blanchet@49202
   447
        val notes =
blanchet@49202
   448
          [(itersN, iter_thmss),
blanchet@49202
   449
           (recsN, rec_thmss)]
blanchet@49202
   450
          |> maps (fn (thmN, thmss) =>
blanchet@49202
   451
            map2 (fn b => fn thms =>
blanchet@49202
   452
                ((Binding.qualify true (Binding.name_of b) (Binding.name thmN), []), [(thms, [])]))
blanchet@49202
   453
              bs thmss);
blanchet@49202
   454
      in
blanchet@49202
   455
        lthy |> Local_Theory.notes notes |> snd
blanchet@49202
   456
      end;
blanchet@49202
   457
blanchet@49212
   458
    fun pour_more_sugar_on_gfps ((ctrss, coiters, corecs, xsss, ctr_defss, coiter_defs, corec_defs),
blanchet@49212
   459
        lthy) =
blanchet@49212
   460
      let
blanchet@49212
   461
        val gcoiters = map (lists_bmoc pgss) coiters;
blanchet@49212
   462
        val hcorecs = map (lists_bmoc phss) corecs;
blanchet@49212
   463
blanchet@49212
   464
        val (coiter_thmss, corec_thmss) =
blanchet@49212
   465
          let
blanchet@49212
   466
            fun mk_cond pos = HOLogic.mk_Trueprop o (not pos ? HOLogic.mk_not);
blanchet@49212
   467
blanchet@49212
   468
            fun mk_goal_coiter_like pfss c cps fcoiter_like n k ctr cfs' =
blanchet@49212
   469
              fold_rev (fold_rev Logic.all) ([c] :: pfss)
blanchet@49212
   470
                (Logic.list_implies (seq_conds mk_cond n k cps,
blanchet@49212
   471
                   mk_Trueprop_eq (fcoiter_like $ c, Term.list_comb (ctr, cfs'))));
blanchet@49212
   472
blanchet@49212
   473
            fun repair_coiter_like_call fcoiter_likes (cf as Free (_, Type (_, [_, T])) $ _) =
blanchet@49212
   474
              (case find_index (curry (op =) T) Cs of ~1 => cf | j => nth fcoiter_likes j $ cf);
blanchet@49212
   475
blanchet@49212
   476
            val cgsss = map (map (map (repair_coiter_like_call gcoiters))) cgsss;
blanchet@49212
   477
            val chsss = map (map (map (repair_coiter_like_call hcorecs))) chsss;
blanchet@49212
   478
blanchet@49212
   479
            val goal_coiterss =
blanchet@49212
   480
              map7 (map3 oooo mk_goal_coiter_like pgss) cs cpss gcoiters ns kss ctrss cgsss;
blanchet@49212
   481
            val goal_corecss =
blanchet@49212
   482
              map7 (map3 oooo mk_goal_coiter_like phss) cs cpss hcorecs ns kss ctrss chsss;
blanchet@49213
   483
blanchet@49213
   484
            val coiter_tacss =
blanchet@49213
   485
              map3 (map oo mk_coiter_like_tac coiter_defs) fp_iter_thms pre_map_defs ctr_defss;
blanchet@49212
   486
          in
blanchet@49213
   487
            (map2 (map2 (fn goal => fn tac => Skip_Proof.prove lthy [] [] goal (tac o #context)))
blanchet@49213
   488
               goal_coiterss coiter_tacss,
blanchet@49213
   489
             map2 (map2 (fn goal => fn tac => Skip_Proof.prove lthy [] [] goal (tac o #context)))
blanchet@49213
   490
               goal_coiterss coiter_tacss (* TODO: should be corecs *))
blanchet@49212
   491
          end;
blanchet@49212
   492
blanchet@49212
   493
        val notes =
blanchet@49212
   494
          [(coitersN, coiter_thmss),
blanchet@49212
   495
           (corecsN, corec_thmss)]
blanchet@49212
   496
          |> maps (fn (thmN, thmss) =>
blanchet@49212
   497
            map2 (fn b => fn thms =>
blanchet@49212
   498
                ((Binding.qualify true (Binding.name_of b) (Binding.name thmN), []), [(thms, [])]))
blanchet@49212
   499
              bs thmss);
blanchet@49212
   500
      in
blanchet@49212
   501
        lthy |> Local_Theory.notes notes |> snd
blanchet@49212
   502
      end;
blanchet@49212
   503
blanchet@49204
   504
    val lthy' = lthy
blanchet@49210
   505
      |> fold_map pour_some_sugar_on_type (bs ~~ fpTs ~~ Cs ~~ flds ~~ unfs ~~ fp_iters ~~
blanchet@49212
   506
        fp_recs ~~ fld_unfs ~~ unf_flds ~~ fld_injects ~~ ns ~~ kss ~~ mss ~~ ctr_binderss ~~
blanchet@49212
   507
        ctr_mixfixess ~~ ctr_Tsss ~~ disc_binderss ~~ sel_bindersss)
blanchet@49205
   508
      |>> split_list7
blanchet@49212
   509
      |> (if lfp then pour_more_sugar_on_lfps else pour_more_sugar_on_gfps);
blanchet@49167
   510
blanchet@49167
   511
    val timer = time (timer ("Constructors, discriminators, selectors, etc., for the new " ^
blanchet@49208
   512
      (if lfp then "" else "co") ^ "datatype"));
blanchet@49112
   513
  in
blanchet@49204
   514
    (timer; lthy')
blanchet@49112
   515
  end;
blanchet@49112
   516
blanchet@49199
   517
fun datatype_cmd info specs lthy =
blanchet@49121
   518
  let
blanchet@49209
   519
    (* TODO: cleaner handling of fake contexts, without "background_theory" *)
blanchet@49184
   520
    (*the "perhaps o try" below helps gracefully handles the case where the new type is defined in a
blanchet@49184
   521
      locale and shadows an existing global type*)
blanchet@49179
   522
    val fake_thy = Theory.copy
blanchet@49184
   523
      #> fold (fn spec => perhaps (try (Sign.add_type lthy
blanchet@49184
   524
        (type_binder_of spec, length (type_args_constrained_of spec), mixfix_of spec)))) specs;
blanchet@49179
   525
    val fake_lthy = Proof_Context.background_theory fake_thy lthy;
blanchet@49121
   526
  in
blanchet@49199
   527
    prepare_datatype Syntax.read_typ info specs fake_lthy lthy
blanchet@49121
   528
  end;
blanchet@49119
   529
blanchet@49129
   530
val parse_opt_binding_colon = Scan.optional (Parse.binding --| Parse.$$$ ":") no_binder
blanchet@49119
   531
blanchet@49112
   532
val parse_ctr_arg =
blanchet@49119
   533
  Parse.$$$ "(" |-- parse_opt_binding_colon -- Parse.typ --| Parse.$$$ ")" ||
blanchet@49129
   534
  (Parse.typ >> pair no_binder);
blanchet@49112
   535
blanchet@49112
   536
val parse_single_spec =
blanchet@49112
   537
  Parse.type_args_constrained -- Parse.binding -- Parse.opt_mixfix --
blanchet@49119
   538
  (@{keyword "="} |-- Parse.enum1 "|" (parse_opt_binding_colon -- Parse.binding --
blanchet@49119
   539
    Scan.repeat parse_ctr_arg -- Parse.opt_mixfix));
blanchet@49112
   540
blanchet@49112
   541
val _ =
blanchet@49112
   542
  Outer_Syntax.local_theory @{command_spec "data"} "define BNF-based inductive datatypes"
blanchet@49208
   543
    (Parse.and_list1 parse_single_spec >> datatype_cmd true);
blanchet@49112
   544
blanchet@49112
   545
val _ =
blanchet@49112
   546
  Outer_Syntax.local_theory @{command_spec "codata"} "define BNF-based coinductive datatypes"
blanchet@49208
   547
    (Parse.and_list1 parse_single_spec >> datatype_cmd false);
blanchet@49112
   548
blanchet@49112
   549
end;