src/HOL/Tools/datatype_codegen.ML
author haftmann
Thu Oct 04 19:54:46 2007 +0200 (2007-10-04)
changeset 24845 abcd15369ffa
parent 24711 e8bba7723858
child 24976 821628d16552
permissions -rw-r--r--
tuned datatype_codegen 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 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 descr' = List.filter (can (map DatatypeAux.dest_DtTFree o #2 o snd)) descr;
    66     val rtnames = map (#1 o snd) (List.filter (fn (_, (_, _, cs)) =>
    67       exists (exists DatatypeAux.is_rec_type o snd) cs) descr');
    68 
    69     val (_, (tname, _, _)) :: _ = descr';
    70     val node_id = tname ^ " (type)";
    71     val module' = if_library (thyname_of_type tname thy) module;
    72 
    73     fun mk_dtdef gr prfx [] = (gr, [])
    74       | mk_dtdef gr prfx ((_, (tname, dts, cs))::xs) =
    75           let
    76             val tvs = map DatatypeAux.dest_DtTFree dts;
    77             val sorts = map (rpair []) tvs;
    78             val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
    79             val (gr', (_, type_id)) = mk_type_id module' tname gr;
    80             val (gr'', ps) =
    81               foldl_map (fn (gr, (cname, cargs)) =>
    82                 foldl_map (invoke_tycodegen thy defs node_id module' false)
    83                   (gr, cargs) |>>>
    84                 mk_const_id module' cname) (gr', cs');
    85             val (gr''', rest) = mk_dtdef gr'' "and " xs
    86           in
    87             (gr''',
    88              Pretty.block (Pretty.str prfx ::
    89                (if null tvs then [] else
    90                   [mk_tuple (map Pretty.str tvs), Pretty.str " "]) @
    91                [Pretty.str (type_id ^ " ="), Pretty.brk 1] @
    92                List.concat (separate [Pretty.brk 1, Pretty.str "| "]
    93                  (map (fn (ps', (_, cname)) => [Pretty.block
    94                    (Pretty.str cname ::
    95                     (if null ps' then [] else
    96                      List.concat ([Pretty.str " of", Pretty.brk 1] ::
    97                        separate [Pretty.str " *", Pretty.brk 1]
    98                          (map single ps'))))]) ps))) :: rest)
    99           end;
   100 
   101     fun mk_term_of_def gr prfx [] = []
   102       | mk_term_of_def gr prfx ((_, (tname, dts, cs)) :: xs) =
   103           let
   104             val tvs = map DatatypeAux.dest_DtTFree dts;
   105             val sorts = map (rpair []) tvs;
   106             val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
   107             val dts' = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
   108             val T = Type (tname, dts');
   109             val rest = mk_term_of_def gr "and " xs;
   110             val (_, eqs) = foldl_map (fn (prfx, (cname, Ts)) =>
   111               let val args = map (fn i =>
   112                 Pretty.str ("x" ^ string_of_int i)) (1 upto length Ts)
   113               in ("  | ", Pretty.blk (4,
   114                 [Pretty.str prfx, mk_term_of gr module' false T, Pretty.brk 1,
   115                  if null Ts then Pretty.str (snd (get_const_id cname gr))
   116                  else parens (Pretty.block
   117                    [Pretty.str (snd (get_const_id cname gr)),
   118                     Pretty.brk 1, mk_tuple args]),
   119                  Pretty.str " =", Pretty.brk 1] @
   120                  List.concat (separate [Pretty.str " $", Pretty.brk 1]
   121                    ([Pretty.str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
   122                      mk_type false (Ts ---> T), Pretty.str ")"] ::
   123                     map (fn (x, U) => [Pretty.block [mk_term_of gr module' false U,
   124                       Pretty.brk 1, x]]) (args ~~ Ts)))))
   125               end) (prfx, cs')
   126           in eqs @ rest end;
   127 
   128     fun mk_gen_of_def gr prfx [] = []
   129       | mk_gen_of_def gr prfx ((i, (tname, dts, cs)) :: xs) =
   130           let
   131             val tvs = map DatatypeAux.dest_DtTFree dts;
   132             val sorts = map (rpair []) tvs;
   133             val (cs1, cs2) =
   134               List.partition (exists DatatypeAux.is_rec_type o snd) cs;
   135             val SOME (cname, _) = find_nonempty descr [i] i;
   136 
   137             fun mk_delay p = Pretty.block
   138               [Pretty.str "fn () =>", Pretty.brk 1, p];
   139 
   140             fun mk_constr s b (cname, dts) =
   141               let
   142                 val gs = map (fn dt => mk_app false (mk_gen gr module' false rtnames s
   143                     (DatatypeAux.typ_of_dtyp descr sorts dt))
   144                   [Pretty.str (if b andalso DatatypeAux.is_rec_type dt then "0"
   145                      else "j")]) dts;
   146                 val (_, id) = get_const_id cname gr
   147               in case gs of
   148                   _ :: _ :: _ => Pretty.block
   149                     [Pretty.str id, Pretty.brk 1, mk_tuple gs]
   150                 | _ => mk_app false (Pretty.str id) (map parens gs)
   151               end;
   152 
   153             fun mk_choice [c] = mk_constr "(i-1)" false c
   154               | mk_choice cs = Pretty.block [Pretty.str "one_of",
   155                   Pretty.brk 1, Pretty.blk (1, Pretty.str "[" ::
   156                   List.concat (separate [Pretty.str ",", Pretty.fbrk]
   157                     (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
   158                   [Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"];
   159 
   160             val gs = map (Pretty.str o suffix "G" o strip_tname) tvs;
   161             val gen_name = "gen_" ^ snd (get_type_id tname gr)
   162 
   163           in
   164             Pretty.blk (4, separate (Pretty.brk 1) 
   165                 (Pretty.str (prfx ^ gen_name ^
   166                    (if null cs1 then "" else "'")) :: gs @
   167                  (if null cs1 then [] else [Pretty.str "i"]) @
   168                  [Pretty.str "j"]) @
   169               [Pretty.str " =", Pretty.brk 1] @
   170               (if not (null cs1) andalso not (null cs2)
   171                then [Pretty.str "frequency", Pretty.brk 1,
   172                  Pretty.blk (1, [Pretty.str "[",
   173                    mk_tuple [Pretty.str "i", mk_delay (mk_choice cs1)],
   174                    Pretty.str ",", Pretty.fbrk,
   175                    mk_tuple [Pretty.str "1", mk_delay (mk_choice cs2)],
   176                    Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"]
   177                else if null cs2 then
   178                  [Pretty.block [Pretty.str "(case", Pretty.brk 1,
   179                    Pretty.str "i", Pretty.brk 1, Pretty.str "of",
   180                    Pretty.brk 1, Pretty.str "0 =>", Pretty.brk 1,
   181                    mk_constr "0" true (cname, valOf (AList.lookup (op =) cs cname)),
   182                    Pretty.brk 1, Pretty.str "| _ =>", Pretty.brk 1,
   183                    mk_choice cs1, Pretty.str ")"]]
   184                else [mk_choice cs2])) ::
   185             (if null cs1 then []
   186              else [Pretty.blk (4, separate (Pretty.brk 1) 
   187                  (Pretty.str ("and " ^ gen_name) :: gs @ [Pretty.str "i"]) @
   188                [Pretty.str " =", Pretty.brk 1] @
   189                separate (Pretty.brk 1) (Pretty.str (gen_name ^ "'") :: gs @
   190                  [Pretty.str "i", Pretty.str "i"]))]) @
   191             mk_gen_of_def gr "and " xs
   192           end
   193 
   194   in
   195     ((add_edge_acyclic (node_id, dep) gr
   196         handle Graph.CYCLES _ => gr) handle Graph.UNDEF _ =>
   197          let
   198            val gr1 = add_edge (node_id, dep)
   199              (new_node (node_id, (NONE, "", "")) gr);
   200            val (gr2, dtdef) = mk_dtdef gr1 "datatype " descr';
   201          in
   202            map_node node_id (K (NONE, module',
   203              Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk dtdef @
   204                [Pretty.str ";"])) ^ "\n\n" ^
   205              (if "term_of" mem !mode then
   206                 Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
   207                   (mk_term_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
   208               else "") ^
   209              (if "test" mem !mode then
   210                 Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
   211                   (mk_gen_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
   212               else ""))) gr2
   213          end,
   214      module')
   215   end;
   216 
   217 
   218 (**** case expressions ****)
   219 
   220 fun pretty_case thy defs gr dep module brack constrs (c as Const (_, T)) ts =
   221   let val i = length constrs
   222   in if length ts <= i then
   223        invoke_codegen thy defs dep module brack (gr, eta_expand c ts (i+1))
   224     else
   225       let
   226         val ts1 = Library.take (i, ts);
   227         val t :: ts2 = Library.drop (i, ts);
   228         val names = foldr add_term_names
   229           (map (fst o fst o dest_Var) (foldr add_term_vars [] ts1)) ts1;
   230         val (Ts, dT) = split_last (Library.take (i+1, fst (strip_type T)));
   231 
   232         fun pcase gr [] [] [] = ([], gr)
   233           | pcase gr ((cname, cargs)::cs) (t::ts) (U::Us) =
   234               let
   235                 val j = length cargs;
   236                 val xs = Name.variant_list names (replicate j "x");
   237                 val Us' = Library.take (j, fst (strip_type U));
   238                 val frees = map Free (xs ~~ Us');
   239                 val (gr0, cp) = invoke_codegen thy defs dep module false
   240                   (gr, list_comb (Const (cname, Us' ---> dT), frees));
   241                 val t' = Envir.beta_norm (list_comb (t, frees));
   242                 val (gr1, p) = invoke_codegen thy defs dep module false (gr0, t');
   243                 val (ps, gr2) = pcase gr1 cs ts Us;
   244               in
   245                 ([Pretty.block [cp, Pretty.str " =>", Pretty.brk 1, p]] :: ps, gr2)
   246               end;
   247 
   248         val (ps1, gr1) = pcase gr constrs ts1 Ts;
   249         val ps = List.concat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
   250         val (gr2, p) = invoke_codegen thy defs dep module false (gr1, t);
   251         val (gr3, ps2) = foldl_map (invoke_codegen thy defs dep module true) (gr2, ts2)
   252       in (gr3, (if not (null ts2) andalso brack then parens else I)
   253         (Pretty.block (separate (Pretty.brk 1)
   254           (Pretty.block ([Pretty.str "(case ", p, Pretty.str " of",
   255              Pretty.brk 1] @ ps @ [Pretty.str ")"]) :: ps2))))
   256       end
   257   end;
   258 
   259 
   260 (**** constructors ****)
   261 
   262 fun pretty_constr thy defs gr dep module brack args (c as Const (s, T)) ts =
   263   let val i = length args
   264   in if i > 1 andalso length ts < i then
   265       invoke_codegen thy defs dep module brack (gr, eta_expand c ts i)
   266      else
   267        let
   268          val id = mk_qual_id module (get_const_id s gr);
   269          val (gr', ps) = foldl_map
   270            (invoke_codegen thy defs dep module (i = 1)) (gr, ts);
   271        in (case args of
   272           _ :: _ :: _ => (gr', (if brack then parens else I)
   273             (Pretty.block [Pretty.str id, Pretty.brk 1, mk_tuple ps]))
   274         | _ => (gr', mk_app brack (Pretty.str id) ps))
   275        end
   276   end;
   277 
   278 
   279 (**** code generators for terms and types ****)
   280 
   281 fun datatype_codegen thy defs gr dep module brack t = (case strip_comb t of
   282    (c as Const (s, T), ts) =>
   283      (case DatatypePackage.datatype_of_case thy s of
   284         SOME {index, descr, ...} =>
   285           if is_some (get_assoc_code thy (s, T)) then NONE else
   286           SOME (pretty_case thy defs gr dep module brack
   287             (#3 (the (AList.lookup op = descr index))) c ts)
   288       | NONE => case (DatatypePackage.datatype_of_constr thy s, strip_type T) of
   289         (SOME {index, descr, ...}, (_, U as Type _)) =>
   290           if is_some (get_assoc_code thy (s, T)) then NONE else
   291           let val SOME args = AList.lookup op =
   292             (#3 (the (AList.lookup op = descr index))) s
   293           in
   294             SOME (pretty_constr thy defs
   295               (fst (invoke_tycodegen thy defs dep module false (gr, U)))
   296               dep module brack args c ts)
   297           end
   298       | _ => NONE)
   299  | _ => NONE);
   300 
   301 fun datatype_tycodegen thy defs gr dep module brack (Type (s, Ts)) =
   302       (case DatatypePackage.get_datatype thy s of
   303          NONE => NONE
   304        | SOME {descr, ...} =>
   305            if is_some (get_assoc_type thy s) then NONE else
   306            let
   307              val (gr', ps) = foldl_map
   308                (invoke_tycodegen thy defs dep module false) (gr, Ts);
   309              val (gr'', module') = add_dt_defs thy defs dep module gr' descr;
   310              val (gr''', tyid) = mk_type_id module' s gr''
   311            in SOME (gr''',
   312              Pretty.block ((if null Ts then [] else
   313                [mk_tuple ps, Pretty.str " "]) @
   314                [Pretty.str (mk_qual_id module tyid)]))
   315            end)
   316   | datatype_tycodegen _ _ _ _ _ _ _ = NONE;
   317 
   318 
   319 (** datatypes for code 2nd generation **)
   320 
   321 fun dtyp_of_case_const thy c =
   322   Option.map (fn {descr, index, ...} => #1 (the (AList.lookup op = descr index)))
   323     (DatatypePackage.datatype_of_case thy c);
   324 
   325 fun dest_case_app cs ts tys =
   326   let
   327     val names = (Name.make_context o map fst) (fold Term.add_tfrees ts []);
   328     val abs = Name.names names "a" (Library.drop (length ts, tys));
   329     val (ts', t) = split_last (ts @ map Free abs);
   330     val (tys', sty) = split_last tys;
   331     fun dest_case ((c, tys_decl), ty) t =
   332       let
   333         val (vs, t') = Term.strip_abs_eta (length tys_decl) t;
   334         val c' = list_comb (Const (c, map snd vs ---> sty), map Free vs);
   335       in case t'
   336        of Const ("HOL.undefined", _) => NONE
   337         | _ => SOME (c', t')
   338       end;
   339   in (abs, ((t, sty), map2 dest_case (cs ~~ tys') ts' |> map_filter I)) 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_sym = thm "HOL.not_sym";
   374   val not_false_true = iffD2 OF [nth (thms "HOL.simp_thms") 7, TrueI];
   375   val refl = thm "refl";
   376   val eqTrueI = thm "eqTrueI";
   377 in
   378 
   379 fun get_eq_datatype thy dtco =
   380   let
   381     val SOME (vs, cs) = DatatypePackage.get_datatype_spec thy dtco;
   382     fun mk_triv_inject co =
   383       let
   384         val ct' = Thm.cterm_of thy
   385           (Const (co, Type (dtco, map (fn (v, sort) => TVar ((v, 0), sort)) vs)))
   386         val cty' = Thm.ctyp_of_term ct';
   387         val SOME (ct, cty) = fold_aterms (fn Var (v, ty) =>
   388           (K o SOME) (Thm.cterm_of thy (Var (v, Thm.typ_of cty')), Thm.ctyp_of thy ty) | _ => I)
   389           (Thm.prop_of refl) NONE;
   390       in eqTrueI OF [Thm.instantiate ([(cty, cty')], [(ct, ct')]) refl] end;
   391     val inject1 = map_filter (fn (co, []) => SOME (mk_triv_inject co) | _ => NONE) cs
   392     val inject2 = (#inject o DatatypePackage.the_datatype thy) dtco;
   393     val ctxt = ProofContext.init thy;
   394     val simpset = Simplifier.context ctxt
   395       (MetaSimplifier.empty_ss addsimprocs [distinct_simproc]);
   396     val cos = map (fn (co, tys) =>
   397         (Const (co, tys ---> Type (dtco, map TFree vs)), tys)) cs;
   398     val tac = ALLGOALS (simp_tac simpset)
   399       THEN ALLGOALS (ProofContext.fact_tac [not_false_true, TrueI]);
   400     val distinct =
   401       mk_distinct cos
   402       |> map (fn t => Goal.prove_global thy [] [] t (K tac))
   403       |> (fn thms => thms @ map (fn thm => not_sym OF [thm]) thms)
   404   in inject1 @ inject2 @ distinct end;
   405 
   406 end;
   407 
   408 fun get_case_cert thy tyco =
   409   let
   410     val raw_thms =
   411       (#case_rewrites o DatatypePackage.the_datatype thy) tyco;
   412     val thms as hd_thm :: _ = raw_thms
   413       |> Conjunction.intr_balanced
   414       |> Drule.unvarify
   415       |> Conjunction.elim_balanced (length raw_thms)
   416       |> map Simpdata.mk_meta_eq
   417       |> map Drule.zero_var_indexes
   418     val params = fold_aterms (fn (Free (v, _)) => insert (op =) v
   419       | _ => I) (Thm.prop_of hd_thm) [];
   420     val rhs = hd_thm
   421       |> Thm.prop_of
   422       |> Logic.dest_equals
   423       |> fst
   424       |> Term.strip_comb
   425       |> apsnd (fst o split_last)
   426       |> list_comb;
   427     val lhs = Free (Name.variant params "case", Term.fastype_of rhs);
   428     val asm = (Thm.cterm_of thy o Logic.mk_equals) (lhs, rhs);
   429   in
   430     thms
   431     |> Conjunction.intr_balanced
   432     |> MetaSimplifier.rewrite_rule [(Thm.symmetric o Thm.assume) asm]
   433     |> Thm.implies_intr asm
   434     |> Thm.generalize ([], params) 0
   435     |> Conv.fconv_rule (Class.unoverload thy)
   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_defs dtco thy =
   591   let
   592     val {case_rewrites, ...} = DatatypePackage.the_datatype thy dtco
   593   in
   594     fold_rev Code.add_default_func case_rewrites thy
   595   end;
   596 
   597 fun add_datatype_case_certs dtco thy =
   598   Code.add_case (get_case_cert thy dtco) thy;
   599 
   600 val setup = 
   601   add_codegen "datatype" datatype_codegen
   602   #> add_tycodegen "datatype" datatype_tycodegen
   603   #> DatatypePackage.interpretation (fold add_datatype_case_certs)
   604   #> DatatypePackage.interpretation (fold add_datatype_case_defs)
   605   #> add_codetypes_hook codetype_hook
   606   #> add_codetypes_hook eq_hook
   607 
   608 end;