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