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