src/HOL/Tools/datatype_codegen.ML
author haftmann
Tue Aug 29 14:31:13 2006 +0200 (2006-08-29)
changeset 20426 9ffea7a8b31c
parent 20389 8b6ecb22ef35
child 20435 d2a30fed7596
permissions -rw-r--r--
added typecopy_package
     1 (*  Title:      HOL/datatype_codegen.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer & Florian Haftmann, TU Muenchen
     4 
     5 Code generator for inductive datatypes and type copies ("code types").
     6 *)
     7 
     8 signature DATATYPE_CODEGEN =
     9 sig
    10   val get_eq: theory -> string -> thm list
    11   val get_datatype_spec_thms: theory -> string
    12     -> (((string * sort) list * (string * typ list) list) * tactic) option
    13   val datatype_tac: theory -> string -> tactic
    14   val dest_case_expr: theory -> term
    15     -> ((string * typ) list * ((term * typ) * (term * term) list)) option
    16   val add_datatype_case_const: string -> theory -> theory
    17   val add_datatype_case_defs: string -> theory -> theory
    18 
    19   type hook = (string * (bool * ((string * sort) list * (string * typ list) list))) list
    20     -> theory -> theory
    21   val codetypes_dependency: theory -> (string * bool) list list
    22   val add_codetypes_hook_bootstrap: hook -> theory -> theory
    23   val the_codetypes_mut_specs: theory -> (string * bool) list
    24     -> ((string * sort) list * (string * (bool * (string * typ list) list)) list)
    25   val get_codetypes_arities: theory -> (string * bool) list -> sort
    26     -> (string * (((string * sort list) * sort) * term list)) list option
    27   val prove_codetypes_arities: (thm list -> tactic) -> (string * bool) list -> sort
    28     -> (theory -> ((string * sort list) * sort) list -> (string * term list) list
    29     -> ((bstring * attribute list) * term) list) -> theory -> theory
    30 
    31   val setup: theory -> theory
    32 end;
    33 
    34 structure DatatypeCodegen : DATATYPE_CODEGEN =
    35 struct
    36 
    37 open Codegen;
    38 
    39 fun mk_tuple [p] = p
    40   | mk_tuple ps = Pretty.block (Pretty.str "(" ::
    41       List.concat (separate [Pretty.str ",", Pretty.brk 1] (map single ps)) @
    42         [Pretty.str ")"]);
    43 
    44 (**** datatype definition ****)
    45 
    46 (* find shortest path to constructor with no recursive arguments *)
    47 
    48 fun find_nonempty (descr: DatatypeAux.descr) is i =
    49   let
    50     val (_, _, constrs) = valOf (AList.lookup (op =) descr i);
    51     fun arg_nonempty (_, DatatypeAux.DtRec i) = if i mem is then NONE
    52           else Option.map (curry op + 1 o snd) (find_nonempty descr (i::is) i)
    53       | arg_nonempty _ = SOME 0;
    54     fun max xs = Library.foldl
    55       (fn (NONE, _) => NONE
    56         | (SOME i, SOME j) => SOME (Int.max (i, j))
    57         | (_, NONE) => NONE) (SOME 0, xs);
    58     val xs = sort (int_ord o pairself snd)
    59       (List.mapPartial (fn (s, dts) => Option.map (pair s)
    60         (max (map (arg_nonempty o DatatypeAux.strip_dtyp) dts))) constrs)
    61   in case xs of [] => NONE | x :: _ => SOME x end;
    62 
    63 fun add_dt_defs thy defs dep module gr (descr: DatatypeAux.descr) =
    64   let
    65     val sg = sign_of thy;
    66     val tab = DatatypePackage.get_datatypes thy;
    67 
    68     val descr' = List.filter (can (map DatatypeAux.dest_DtTFree o #2 o snd)) descr;
    69     val rtnames = map (#1 o snd) (List.filter (fn (_, (_, _, cs)) =>
    70       exists (exists DatatypeAux.is_rec_type o snd) cs) descr');
    71 
    72     val (_, (tname, _, _)) :: _ = descr';
    73     val node_id = tname ^ " (type)";
    74     val module' = if_library (thyname_of_type tname thy) module;
    75 
    76     fun mk_dtdef gr prfx [] = (gr, [])
    77       | mk_dtdef gr prfx ((_, (tname, dts, cs))::xs) =
    78           let
    79             val tvs = map DatatypeAux.dest_DtTFree dts;
    80             val sorts = map (rpair []) tvs;
    81             val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
    82             val (gr', (_, type_id)) = mk_type_id module' tname gr;
    83             val (gr'', ps) =
    84               foldl_map (fn (gr, (cname, cargs)) =>
    85                 foldl_map (invoke_tycodegen thy defs node_id module' false)
    86                   (gr, cargs) |>>>
    87                 mk_const_id module' cname) (gr', cs');
    88             val (gr''', rest) = mk_dtdef gr'' "and " xs
    89           in
    90             (gr''',
    91              Pretty.block (Pretty.str prfx ::
    92                (if null tvs then [] else
    93                   [mk_tuple (map Pretty.str tvs), Pretty.str " "]) @
    94                [Pretty.str (type_id ^ " ="), Pretty.brk 1] @
    95                List.concat (separate [Pretty.brk 1, Pretty.str "| "]
    96                  (map (fn (ps', (_, cname)) => [Pretty.block
    97                    (Pretty.str cname ::
    98                     (if null ps' then [] else
    99                      List.concat ([Pretty.str " of", Pretty.brk 1] ::
   100                        separate [Pretty.str " *", Pretty.brk 1]
   101                          (map single ps'))))]) ps))) :: rest)
   102           end;
   103 
   104     fun mk_term_of_def gr prfx [] = []
   105       | mk_term_of_def gr prfx ((_, (tname, dts, cs)) :: xs) =
   106           let
   107             val tvs = map DatatypeAux.dest_DtTFree dts;
   108             val sorts = map (rpair []) tvs;
   109             val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
   110             val dts' = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
   111             val T = Type (tname, dts');
   112             val rest = mk_term_of_def gr "and " xs;
   113             val (_, eqs) = foldl_map (fn (prfx, (cname, Ts)) =>
   114               let val args = map (fn i =>
   115                 Pretty.str ("x" ^ string_of_int i)) (1 upto length Ts)
   116               in ("  | ", Pretty.blk (4,
   117                 [Pretty.str prfx, mk_term_of gr module' false T, Pretty.brk 1,
   118                  if null Ts then Pretty.str (snd (get_const_id cname gr))
   119                  else parens (Pretty.block
   120                    [Pretty.str (snd (get_const_id cname gr)),
   121                     Pretty.brk 1, mk_tuple args]),
   122                  Pretty.str " =", Pretty.brk 1] @
   123                  List.concat (separate [Pretty.str " $", Pretty.brk 1]
   124                    ([Pretty.str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
   125                      mk_type false (Ts ---> T), Pretty.str ")"] ::
   126                     map (fn (x, U) => [Pretty.block [mk_term_of gr module' false U,
   127                       Pretty.brk 1, x]]) (args ~~ Ts)))))
   128               end) (prfx, cs')
   129           in eqs @ rest end;
   130 
   131     fun mk_gen_of_def gr prfx [] = []
   132       | mk_gen_of_def gr prfx ((i, (tname, dts, cs)) :: xs) =
   133           let
   134             val tvs = map DatatypeAux.dest_DtTFree dts;
   135             val sorts = map (rpair []) tvs;
   136             val (cs1, cs2) =
   137               List.partition (exists DatatypeAux.is_rec_type o snd) cs;
   138             val SOME (cname, _) = find_nonempty descr [i] i;
   139 
   140             fun mk_delay p = Pretty.block
   141               [Pretty.str "fn () =>", Pretty.brk 1, p];
   142 
   143             fun mk_constr s b (cname, dts) =
   144               let
   145                 val gs = map (fn dt => mk_app false (mk_gen gr module' false rtnames s
   146                     (DatatypeAux.typ_of_dtyp descr sorts dt))
   147                   [Pretty.str (if b andalso DatatypeAux.is_rec_type dt then "0"
   148                      else "j")]) dts;
   149                 val (_, id) = get_const_id cname gr
   150               in case gs of
   151                   _ :: _ :: _ => Pretty.block
   152                     [Pretty.str id, Pretty.brk 1, mk_tuple gs]
   153                 | _ => mk_app false (Pretty.str id) (map parens gs)
   154               end;
   155 
   156             fun mk_choice [c] = mk_constr "(i-1)" false c
   157               | mk_choice cs = Pretty.block [Pretty.str "one_of",
   158                   Pretty.brk 1, Pretty.blk (1, Pretty.str "[" ::
   159                   List.concat (separate [Pretty.str ",", Pretty.fbrk]
   160                     (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
   161                   [Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"];
   162 
   163             val gs = map (Pretty.str o suffix "G" o strip_tname) tvs;
   164             val gen_name = "gen_" ^ snd (get_type_id tname gr)
   165 
   166           in
   167             Pretty.blk (4, separate (Pretty.brk 1) 
   168                 (Pretty.str (prfx ^ gen_name ^
   169                    (if null cs1 then "" else "'")) :: gs @
   170                  (if null cs1 then [] else [Pretty.str "i"]) @
   171                  [Pretty.str "j"]) @
   172               [Pretty.str " =", Pretty.brk 1] @
   173               (if not (null cs1) andalso not (null cs2)
   174                then [Pretty.str "frequency", Pretty.brk 1,
   175                  Pretty.blk (1, [Pretty.str "[",
   176                    mk_tuple [Pretty.str "i", mk_delay (mk_choice cs1)],
   177                    Pretty.str ",", Pretty.fbrk,
   178                    mk_tuple [Pretty.str "1", mk_delay (mk_choice cs2)],
   179                    Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"]
   180                else if null cs2 then
   181                  [Pretty.block [Pretty.str "(case", Pretty.brk 1,
   182                    Pretty.str "i", Pretty.brk 1, Pretty.str "of",
   183                    Pretty.brk 1, Pretty.str "0 =>", Pretty.brk 1,
   184                    mk_constr "0" true (cname, valOf (AList.lookup (op =) cs cname)),
   185                    Pretty.brk 1, Pretty.str "| _ =>", Pretty.brk 1,
   186                    mk_choice cs1, Pretty.str ")"]]
   187                else [mk_choice cs2])) ::
   188             (if null cs1 then []
   189              else [Pretty.blk (4, separate (Pretty.brk 1) 
   190                  (Pretty.str ("and " ^ gen_name) :: gs @ [Pretty.str "i"]) @
   191                [Pretty.str " =", Pretty.brk 1] @
   192                separate (Pretty.brk 1) (Pretty.str (gen_name ^ "'") :: gs @
   193                  [Pretty.str "i", Pretty.str "i"]))]) @
   194             mk_gen_of_def gr "and " xs
   195           end
   196 
   197   in
   198     (add_edge_acyclic (node_id, dep) gr
   199         handle Graph.CYCLES _ => gr) handle Graph.UNDEF _ =>
   200          let
   201            val gr1 = add_edge (node_id, dep)
   202              (new_node (node_id, (NONE, "", "")) gr);
   203            val (gr2, dtdef) = mk_dtdef gr1 "datatype " descr';
   204          in
   205            map_node node_id (K (NONE, module',
   206              Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk dtdef @
   207                [Pretty.str ";"])) ^ "\n\n" ^
   208              (if "term_of" mem !mode then
   209                 Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
   210                   (mk_term_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
   211               else "") ^
   212              (if "test" mem !mode then
   213                 Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
   214                   (mk_gen_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
   215               else ""))) gr2
   216          end
   217   end;
   218 
   219 
   220 (**** case expressions ****)
   221 
   222 fun pretty_case thy defs gr dep module brack constrs (c as Const (_, T)) ts =
   223   let val i = length constrs
   224   in if length ts <= i then
   225        invoke_codegen thy defs dep module brack (gr, eta_expand c ts (i+1))
   226     else
   227       let
   228         val ts1 = Library.take (i, ts);
   229         val t :: ts2 = Library.drop (i, ts);
   230         val names = foldr add_term_names
   231           (map (fst o fst o dest_Var) (foldr add_term_vars [] ts1)) ts1;
   232         val (Ts, dT) = split_last (Library.take (i+1, fst (strip_type T)));
   233 
   234         fun pcase gr [] [] [] = ([], gr)
   235           | pcase gr ((cname, cargs)::cs) (t::ts) (U::Us) =
   236               let
   237                 val j = length cargs;
   238                 val xs = Name.variant_list names (replicate j "x");
   239                 val Us' = Library.take (j, fst (strip_type U));
   240                 val frees = map Free (xs ~~ Us');
   241                 val (gr0, cp) = invoke_codegen thy defs dep module false
   242                   (gr, list_comb (Const (cname, Us' ---> dT), frees));
   243                 val t' = Envir.beta_norm (list_comb (t, frees));
   244                 val (gr1, p) = invoke_codegen thy defs dep module false (gr0, t');
   245                 val (ps, gr2) = pcase gr1 cs ts Us;
   246               in
   247                 ([Pretty.block [cp, Pretty.str " =>", Pretty.brk 1, p]] :: ps, gr2)
   248               end;
   249 
   250         val (ps1, gr1) = pcase gr constrs ts1 Ts;
   251         val ps = List.concat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
   252         val (gr2, p) = invoke_codegen thy defs dep module false (gr1, t);
   253         val (gr3, ps2) = foldl_map (invoke_codegen thy defs dep module true) (gr2, ts2)
   254       in (gr3, (if not (null ts2) andalso brack then parens else I)
   255         (Pretty.block (separate (Pretty.brk 1)
   256           (Pretty.block ([Pretty.str "(case ", p, Pretty.str " of",
   257              Pretty.brk 1] @ ps @ [Pretty.str ")"]) :: ps2))))
   258       end
   259   end;
   260 
   261 
   262 (**** constructors ****)
   263 
   264 fun pretty_constr thy defs gr dep module brack args (c as Const (s, T)) ts =
   265   let val i = length args
   266   in if i > 1 andalso length ts < i then
   267       invoke_codegen thy defs dep module brack (gr, eta_expand c ts i)
   268      else
   269        let
   270          val id = mk_qual_id module (get_const_id s gr);
   271          val (gr', ps) = foldl_map
   272            (invoke_codegen thy defs dep module (i = 1)) (gr, ts);
   273        in (case args of
   274           _ :: _ :: _ => (gr', (if brack then parens else I)
   275             (Pretty.block [Pretty.str id, Pretty.brk 1, mk_tuple ps]))
   276         | _ => (gr', mk_app brack (Pretty.str id) ps))
   277        end
   278   end;
   279 
   280 
   281 (**** code generators for terms and types ****)
   282 
   283 fun datatype_codegen thy defs gr dep module brack t = (case strip_comb t of
   284    (c as Const (s, T), ts) =>
   285        (case Library.find_first (fn (_, {index, descr, case_name, ...}) =>
   286          s = case_name orelse
   287            AList.defined (op =) ((#3 o the o AList.lookup (op =) descr) index) s)
   288              (Symtab.dest (DatatypePackage.get_datatypes thy)) of
   289           NONE => NONE
   290         | SOME (tname, {index, descr, ...}) =>
   291            if is_some (get_assoc_code thy s T) then NONE else
   292            let val SOME (_, _, constrs) = AList.lookup (op =) descr index
   293            in (case (AList.lookup (op =) constrs s, strip_type T) of
   294                (NONE, _) => SOME (pretty_case thy defs gr dep module brack
   295                  ((#3 o the o AList.lookup (op =) descr) index) c ts)
   296              | (SOME args, (_, Type _)) => SOME (pretty_constr thy defs
   297                  (fst (invoke_tycodegen thy defs dep module false
   298                     (gr, snd (strip_type T))))
   299                  dep module brack args c ts)
   300              | _ => NONE)
   301            end)
   302  |  _ => NONE);
   303 
   304 fun datatype_tycodegen thy defs gr dep module brack (Type (s, Ts)) =
   305       (case Symtab.lookup (DatatypePackage.get_datatypes thy) s of
   306          NONE => NONE
   307        | SOME {descr, ...} =>
   308            if isSome (get_assoc_type thy s) then NONE else
   309            let
   310              val (gr', ps) = foldl_map
   311                (invoke_tycodegen thy defs dep module false) (gr, Ts);
   312              val gr'' = add_dt_defs thy defs dep module gr' descr
   313            in SOME (gr'',
   314              Pretty.block ((if null Ts then [] else
   315                [mk_tuple ps, Pretty.str " "]) @
   316                [Pretty.str (mk_qual_id module (get_type_id s gr''))]))
   317            end)
   318   | datatype_tycodegen _ _ _ _ _ _ _ = NONE;
   319 
   320 
   321 (** datatypes for code 2nd generation **)
   322 
   323 fun dtyp_of_case_const thy c =
   324   get_first (fn (dtco, { case_name, ... }) => if case_name = c then SOME dtco else NONE)
   325     ((Symtab.dest o DatatypePackage.get_datatypes) thy);
   326 
   327 fun dest_case_app cs ts tys =
   328   let
   329     val abs = Name.names Name.context "a" (Library.drop (length ts, tys));
   330     val (ts', t) = split_last (ts @ map Free abs);
   331     val (tys', sty) = split_last tys;
   332     fun freenames_of t = fold_aterms
   333       (fn Free (v, _) => insert (op =) v | _ => I) t [];
   334     fun dest_case ((c, tys_decl), ty) t =
   335       let
   336         val (vs, t') = Term.strip_abs_eta (length tys_decl) t;
   337         val c' = list_comb (Const (c, map snd vs ---> sty), map Free vs);
   338       in (c', t') end;
   339   in (abs, ((t, sty), map2 dest_case (cs ~~ tys') ts')) end;
   340 
   341 fun dest_case_expr thy t =
   342   case strip_comb t
   343    of (Const (c, ty), ts) =>
   344         (case dtyp_of_case_const thy c
   345          of SOME dtco =>
   346               let val (vs, cs) = (the o DatatypePackage.get_datatype_spec thy) dtco;
   347               in SOME (dest_case_app cs ts (Library.take (length cs + 1, (fst o strip_type) ty))) end
   348           | _ => NONE)
   349     | _ => NONE;
   350 
   351 fun mk_distinct cos =
   352   let
   353     fun sym_product [] = []
   354       | sym_product (x::xs) = map (pair x) xs @ sym_product xs;
   355     fun mk_co_args (co, tys) ctxt =
   356       let
   357         val names = Name.invents ctxt "a" (length tys);
   358         val ctxt' = fold Name.declare names ctxt;
   359         val vs = map2 (curry Free) names tys;
   360       in (vs, ctxt) end;
   361     fun mk_dist ((co1, tys1), (co2, tys2)) =
   362       let
   363         val ((xs1, xs2), _) = Name.context
   364           |> mk_co_args (co1, tys1)
   365           ||>> mk_co_args (co2, tys2);
   366         val prem = HOLogic.mk_eq
   367           (list_comb (co1, xs1), list_comb (co2, xs2));
   368         val t = HOLogic.mk_not prem;
   369       in HOLogic.mk_Trueprop t end;
   370   in map mk_dist (sym_product cos) end;
   371 
   372 local
   373   val not_false_true = iffD2 OF [nth (thms "HOL.simp_thms") 7, TrueI];
   374 in fun get_eq thy dtco =
   375   let
   376     val SOME (vs, cs) = DatatypePackage.get_datatype_spec thy dtco;
   377     fun mk_triv_inject co =
   378       let
   379         val ct' = Thm.cterm_of thy
   380           (Const (co, Type (dtco, map (fn (v, sort) => TVar ((v, 0), sort)) vs)))
   381         val cty' = Thm.ctyp_of_term ct';
   382         val refl = Thm.prop_of HOL.refl;
   383         val SOME (ct, cty) = fold_aterms (fn Var (v, ty) =>
   384           (K o SOME) (Thm.cterm_of thy (Var (v, Thm.typ_of cty')), Thm.ctyp_of thy ty) | _ => I)
   385           refl NONE;
   386       in eqTrueI OF [Thm.instantiate ([(cty, cty')], [(ct, ct')]) HOL.refl] end;
   387     val inject1 = map_filter (fn (co, []) => SOME (mk_triv_inject co) | _ => NONE) cs
   388     val inject2 = (#inject o DatatypePackage.the_datatype thy) dtco;
   389     val ctxt = Context.init_proof thy;
   390     val simpset = Simplifier.context ctxt
   391       (MetaSimplifier.empty_ss addsimprocs [distinct_simproc]);
   392     val cos = map (fn (co, tys) =>
   393         (Const (co, tys ---> Type (dtco, map TFree vs)), tys)) cs;
   394     val tac = ALLGOALS (simp_tac simpset)
   395       THEN ALLGOALS (ProofContext.fact_tac [not_false_true, TrueI]);
   396     val distinct =
   397       mk_distinct cos
   398       |> map (fn t => Goal.prove_global thy [] [] t (K tac))
   399   in inject1 @ inject2 @ distinct end;
   400 end (*local*);
   401 
   402 fun datatype_tac thy dtco =
   403   let
   404     val ctxt = Context.init_proof thy;
   405     val inject = (#inject o DatatypePackage.the_datatype thy) dtco;
   406     val simpset = Simplifier.context ctxt
   407       (MetaSimplifier.empty_ss addsimprocs [distinct_simproc]);
   408   in
   409     (TRY o ALLGOALS o match_tac) [HOL.eq_reflection]
   410     THEN (
   411       (ALLGOALS o match_tac) (eqTrueI :: inject)
   412       ORELSE (ALLGOALS o simp_tac) simpset
   413     )
   414     THEN (ALLGOALS o match_tac) [HOL.refl, Drule.reflexive_thm]
   415   end;
   416 
   417 fun get_datatype_spec_thms thy dtco =
   418   case DatatypePackage.get_datatype_spec thy dtco
   419    of SOME vs_cos =>
   420         SOME (vs_cos, datatype_tac thy dtco)
   421     | NONE => NONE;
   422 
   423 fun add_datatype_case_const dtco thy =
   424   let
   425     val {case_name, index, descr, ...} = DatatypePackage.the_datatype thy dtco;
   426   in
   427     CodegenPackage.add_appconst_i (case_name, CodegenPackage.appgen_case dest_case_expr) thy
   428   end;
   429 
   430 fun add_datatype_case_defs dtco thy =
   431   let
   432     val {case_rewrites, ...} = DatatypePackage.the_datatype thy dtco
   433   in
   434     fold CodegenTheorems.add_fun case_rewrites thy
   435   end;
   436 
   437 
   438 (** codetypes for code 2nd generation **)
   439 
   440 type hook = (string * (bool * ((string * sort) list * (string * typ list) list))) list
   441   -> theory -> theory;
   442 
   443 fun codetypes_dependency thy =
   444   let
   445     val names =
   446       map (rpair true) (Symtab.keys (DatatypePackage.get_datatypes thy))
   447         @ map (rpair false) (TypecopyPackage.get_typecopies thy);
   448     fun add_node (name, is_dt) =
   449       let
   450         fun add_tycos (Type (tyco, tys)) = insert (op =) tyco #> fold add_tycos tys
   451           | add_tycos _ = I;
   452         val tys = if is_dt then
   453             (maps snd o snd o the o DatatypePackage.get_datatype_spec thy) name
   454           else
   455             [(#typ o the o TypecopyPackage.get_typecopy_info thy) name]
   456         val deps = (filter (AList.defined (op =) names) o maps (fn ty =>
   457           add_tycos ty [])) tys;
   458       in
   459         Graph.default_node (name, ())
   460         #> fold (fn name' =>
   461              Graph.default_node (name', ())
   462              #> Graph.add_edge (name', name)
   463            ) deps
   464       end
   465   in
   466     Graph.empty
   467     |> fold add_node names
   468     |> Graph.strong_conn
   469     |> map (AList.make (the o AList.lookup (op =) names))
   470   end;
   471 
   472 fun mk_typecopy_spec ({ vs, constr, typ, ... } : TypecopyPackage.info) =
   473   (vs, [(constr, [typ])]);
   474 
   475 fun get_spec thy (dtco, true) =
   476       (the o DatatypePackage.get_datatype_spec thy) dtco
   477   | get_spec thy (tyco, false) =
   478       (mk_typecopy_spec o the o TypecopyPackage.get_typecopy_info thy) tyco;
   479 
   480 fun add_spec thy (tyco, is_dt) =
   481   (tyco, (is_dt, get_spec thy (tyco, is_dt)));
   482 
   483 fun add_codetypes_hook_bootstrap hook thy =
   484   let
   485     fun datatype_hook dtcos thy =
   486       hook (map (add_spec thy) (map (rpair true) dtcos)) thy;
   487     fun typecopy_hook ((tyco, info )) thy =
   488       hook ([(tyco, (false, mk_typecopy_spec info))]) thy;
   489   in
   490     thy
   491     |> fold hook ((map o map) (add_spec thy) (codetypes_dependency thy))
   492     |> DatatypeHooks.add datatype_hook
   493     |> TypecopyPackage.add_hook typecopy_hook
   494   end;
   495 
   496 fun the_codetypes_mut_specs thy ([(tyco, is_dt)]) =
   497       let
   498         val (vs, cs) = get_spec thy (tyco, is_dt)
   499       in (vs, [(tyco, (is_dt, cs))]) end
   500   | the_codetypes_mut_specs thy (tycos' as (tyco, true) :: _) =
   501       let
   502         val tycos = map fst tycos';
   503         val tycos'' = (map (#1 o snd) o #descr o DatatypePackage.the_datatype thy) tyco;
   504         val _ = if gen_subset (op =) (tycos, tycos'') then () else
   505           error ("datatype constructors are not mutually recursive: " ^ (commas o map quote) tycos);
   506         val (vs::_, css) = split_list (map (the o DatatypePackage.get_datatype_spec thy) tycos);
   507       in (vs, map2 (fn (tyco, is_dt) => fn cs => (tyco, (is_dt, cs))) tycos' css) end;
   508 
   509 fun get_codetypes_arities thy tycos sort =
   510   let
   511     val algebra = Sign.classes_of thy;
   512     val (vs_proto, css_proto) = the_codetypes_mut_specs thy tycos;
   513     val vs = map (fn (v, vsort) => (v, Sorts.inter_sort algebra (vsort, sort))) vs_proto;
   514     fun inst_type tyco (c, tys) =
   515       let
   516         val tys' = (map o map_atyps)
   517           (fn TFree (v, _) => TFree (v, the (AList.lookup (op =) vs v))) tys
   518       in (c, tys') end;
   519     val css = map (fn (tyco, (_, cs)) => (tyco, (map (inst_type tyco) cs))) css_proto;
   520     fun mk_arity tyco =
   521       ((tyco, map snd vs), sort);
   522     fun typ_of_sort ty =
   523       let
   524         val arities = map (fn (tyco, _) => ((tyco, map snd vs), sort)) css;
   525       in ClassPackage.assume_arities_of_sort thy arities (ty, sort) end;
   526     fun mk_cons tyco (c, tys) =
   527       let
   528         val ts = Name.names Name.context "a" tys;
   529         val ty = tys ---> Type (tyco, map TFree vs);
   530       in list_comb (Const (c, ty), map Free ts) end;
   531   in if forall (fn (_, cs) => forall (fn (_, tys) => forall typ_of_sort tys) cs) css
   532     then SOME (
   533       map (fn (tyco, cs) => (tyco, (mk_arity tyco, map (mk_cons tyco) cs))) css
   534     ) else NONE
   535   end;
   536 
   537 fun prove_codetypes_arities tac tycos sort f thy =
   538   case get_codetypes_arities thy tycos sort
   539    of NONE => thy
   540     | SOME insts => let
   541         fun proven ((tyco, asorts), sort) =
   542           Sorts.of_sort (Sign.classes_of thy)
   543             (Type (tyco, map TFree (Name.names Name.context "'a" asorts)), sort);
   544         val (arities, css) = (split_list o map_filter
   545           (fn (tyco, (arity, cs)) => if proven arity
   546             then NONE else SOME (arity, (tyco, cs)))) insts;
   547       in
   548         thy
   549         |> K ((not o null) arities) ? ClassPackage.prove_instance_arity tac
   550              arities ("", []) (f thy arities css)
   551       end;
   552 
   553 
   554 
   555 (** theory setup **)
   556 
   557 val setup = 
   558   add_codegen "datatype" datatype_codegen #>
   559   add_tycodegen "datatype" datatype_tycodegen #>
   560   CodegenTheorems.add_datatype_extr
   561     get_datatype_spec_thms #>
   562   DatatypeHooks.add (fold add_datatype_case_const) #>
   563   DatatypeHooks.add (fold add_datatype_case_defs)
   564 
   565 end;