src/HOL/Tools/datatype_codegen.ML
author paulson
Tue May 22 17:56:06 2007 +0200 (2007-05-22)
changeset 23075 69e30a7e8880
parent 22921 475ff421a6a3
child 23513 2ebb50c0db4f
permissions -rw-r--r--
Some hacks for SPASS format
     1 (*  Title:      HOL/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 add_datatype_case_const: string -> theory -> theory
    15   val add_datatype_case_defs: string -> theory -> theory
    16 
    17   type hook = (string * (bool * ((string * sort) list * (string * typ list) list))) list
    18     -> theory -> theory
    19   val codetype_hook: hook
    20   val eq_hook: hook
    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 * (arity * term list)) list option
    27   val prove_codetypes_arities: tactic -> (string * bool) list -> sort
    28     -> (arity list -> (string * term list) list -> theory
    29       -> ((bstring * Attrib.src list) * term) list * theory)
    30     -> (arity list -> (string * term list) list -> theory -> theory)
    31     -> theory -> theory
    32 
    33   val setup: theory -> theory
    34   val setup_hooks: theory -> theory
    35 end;
    36 
    37 structure DatatypeCodegen : DATATYPE_CODEGEN =
    38 struct
    39 
    40 open Codegen;
    41 
    42 fun mk_tuple [p] = p
    43   | mk_tuple ps = Pretty.block (Pretty.str "(" ::
    44       List.concat (separate [Pretty.str ",", Pretty.brk 1] (map single ps)) @
    45         [Pretty.str ")"]);
    46 
    47 (**** datatype definition ****)
    48 
    49 (* find shortest path to constructor with no recursive arguments *)
    50 
    51 fun find_nonempty (descr: DatatypeAux.descr) is i =
    52   let
    53     val (_, _, constrs) = valOf (AList.lookup (op =) descr i);
    54     fun arg_nonempty (_, DatatypeAux.DtRec i) = if i mem is then NONE
    55           else Option.map (curry op + 1 o snd) (find_nonempty descr (i::is) i)
    56       | arg_nonempty _ = SOME 0;
    57     fun max xs = Library.foldl
    58       (fn (NONE, _) => NONE
    59         | (SOME i, SOME j) => SOME (Int.max (i, j))
    60         | (_, NONE) => NONE) (SOME 0, xs);
    61     val xs = sort (int_ord o pairself snd)
    62       (List.mapPartial (fn (s, dts) => Option.map (pair s)
    63         (max (map (arg_nonempty o DatatypeAux.strip_dtyp) dts))) constrs)
    64   in case xs of [] => NONE | x :: _ => SOME x end;
    65 
    66 fun add_dt_defs thy defs dep module gr (descr: DatatypeAux.descr) =
    67   let
    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      module')
   218   end;
   219 
   220 
   221 (**** case expressions ****)
   222 
   223 fun pretty_case thy defs gr dep module brack constrs (c as Const (_, T)) ts =
   224   let val i = length constrs
   225   in if length ts <= i then
   226        invoke_codegen thy defs dep module brack (gr, eta_expand c ts (i+1))
   227     else
   228       let
   229         val ts1 = Library.take (i, ts);
   230         val t :: ts2 = Library.drop (i, ts);
   231         val names = foldr add_term_names
   232           (map (fst o fst o dest_Var) (foldr add_term_vars [] ts1)) ts1;
   233         val (Ts, dT) = split_last (Library.take (i+1, fst (strip_type T)));
   234 
   235         fun pcase gr [] [] [] = ([], gr)
   236           | pcase gr ((cname, cargs)::cs) (t::ts) (U::Us) =
   237               let
   238                 val j = length cargs;
   239                 val xs = Name.variant_list names (replicate j "x");
   240                 val Us' = Library.take (j, fst (strip_type U));
   241                 val frees = map Free (xs ~~ Us');
   242                 val (gr0, cp) = invoke_codegen thy defs dep module false
   243                   (gr, list_comb (Const (cname, Us' ---> dT), frees));
   244                 val t' = Envir.beta_norm (list_comb (t, frees));
   245                 val (gr1, p) = invoke_codegen thy defs dep module false (gr0, t');
   246                 val (ps, gr2) = pcase gr1 cs ts Us;
   247               in
   248                 ([Pretty.block [cp, Pretty.str " =>", Pretty.brk 1, p]] :: ps, gr2)
   249               end;
   250 
   251         val (ps1, gr1) = pcase gr constrs ts1 Ts;
   252         val ps = List.concat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
   253         val (gr2, p) = invoke_codegen thy defs dep module false (gr1, t);
   254         val (gr3, ps2) = foldl_map (invoke_codegen thy defs dep module true) (gr2, ts2)
   255       in (gr3, (if not (null ts2) andalso brack then parens else I)
   256         (Pretty.block (separate (Pretty.brk 1)
   257           (Pretty.block ([Pretty.str "(case ", p, Pretty.str " of",
   258              Pretty.brk 1] @ ps @ [Pretty.str ")"]) :: ps2))))
   259       end
   260   end;
   261 
   262 
   263 (**** constructors ****)
   264 
   265 fun pretty_constr thy defs gr dep module brack args (c as Const (s, T)) ts =
   266   let val i = length args
   267   in if i > 1 andalso length ts < i then
   268       invoke_codegen thy defs dep module brack (gr, eta_expand c ts i)
   269      else
   270        let
   271          val id = mk_qual_id module (get_const_id s gr);
   272          val (gr', ps) = foldl_map
   273            (invoke_codegen thy defs dep module (i = 1)) (gr, ts);
   274        in (case args of
   275           _ :: _ :: _ => (gr', (if brack then parens else I)
   276             (Pretty.block [Pretty.str id, Pretty.brk 1, mk_tuple ps]))
   277         | _ => (gr', mk_app brack (Pretty.str id) ps))
   278        end
   279   end;
   280 
   281 
   282 (**** code generators for terms and types ****)
   283 
   284 fun datatype_codegen thy defs gr dep module brack t = (case strip_comb t of
   285    (c as Const (s, T), ts) =>
   286      (case DatatypePackage.datatype_of_case thy s of
   287         SOME {index, descr, ...} =>
   288           if is_some (get_assoc_code thy (s, T)) then NONE else
   289           SOME (pretty_case thy defs gr dep module brack
   290             (#3 (the (AList.lookup op = descr index))) c ts)
   291       | NONE => case (DatatypePackage.datatype_of_constr thy s, strip_type T) of
   292         (SOME {index, descr, ...}, (_, U as Type _)) =>
   293           if is_some (get_assoc_code thy (s, T)) then NONE else
   294           let val SOME args = AList.lookup op =
   295             (#3 (the (AList.lookup op = descr index))) s
   296           in
   297             SOME (pretty_constr thy defs
   298               (fst (invoke_tycodegen thy defs dep module false (gr, U)))
   299               dep module brack args c ts)
   300           end
   301       | _ => NONE)
   302  | _ => NONE);
   303 
   304 fun datatype_tycodegen thy defs gr dep module brack (Type (s, Ts)) =
   305       (case DatatypePackage.get_datatype thy s of
   306          NONE => NONE
   307        | SOME {descr, ...} =>
   308            if is_some (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'', module') = add_dt_defs thy defs dep module gr' descr;
   313              val (gr''', tyid) = mk_type_id module' s gr''
   314            in SOME (gr''',
   315              Pretty.block ((if null Ts then [] else
   316                [mk_tuple ps, Pretty.str " "]) @
   317                [Pretty.str (mk_qual_id module tyid)]))
   318            end)
   319   | datatype_tycodegen _ _ _ _ _ _ _ = NONE;
   320 
   321 
   322 (** datatypes for code 2nd generation **)
   323 
   324 fun dtyp_of_case_const thy c =
   325   Option.map (fn {descr, index, ...} => #1 (the (AList.lookup op = descr index)))
   326     (DatatypePackage.datatype_of_case thy c);
   327 
   328 fun dest_case_app cs ts tys =
   329   let
   330     val names = (Name.make_context o map fst) (fold Term.add_tfrees ts []);
   331     val abs = Name.names names "a" (Library.drop (length ts, tys));
   332     val (ts', t) = split_last (ts @ map Free abs);
   333     val (tys', sty) = split_last tys;
   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 case t'
   339        of Const ("HOL.undefined", _) => NONE
   340         | _ => SOME (c', t')
   341       end;
   342   in (abs, ((t, sty), map2 dest_case (cs ~~ tys') ts' |> map_filter I)) end;
   343 
   344 fun dest_case_expr thy t =
   345   case strip_comb t
   346    of (Const (c, ty), ts) =>
   347         (case dtyp_of_case_const thy c
   348          of SOME dtco =>
   349               let val (vs, cs) = (the o DatatypePackage.get_datatype_spec thy) dtco;
   350               in SOME (dest_case_app cs ts (Library.take (length cs + 1, (fst o strip_type) ty))) end
   351           | _ => NONE)
   352     | _ => NONE;
   353 
   354 fun mk_distinct cos =
   355   let
   356     fun sym_product [] = []
   357       | sym_product (x::xs) = map (pair x) xs @ sym_product xs;
   358     fun mk_co_args (co, tys) ctxt =
   359       let
   360         val names = Name.invents ctxt "a" (length tys);
   361         val ctxt' = fold Name.declare names ctxt;
   362         val vs = map2 (curry Free) names tys;
   363       in (vs, ctxt') end;
   364     fun mk_dist ((co1, tys1), (co2, tys2)) =
   365       let
   366         val ((xs1, xs2), _) = Name.context
   367           |> mk_co_args (co1, tys1)
   368           ||>> mk_co_args (co2, tys2);
   369         val prem = HOLogic.mk_eq
   370           (list_comb (co1, xs1), list_comb (co2, xs2));
   371         val t = HOLogic.mk_not prem;
   372       in HOLogic.mk_Trueprop t end;
   373   in map mk_dist (sym_product cos) end;
   374 
   375 local
   376   val not_sym = thm "HOL.not_sym";
   377   val not_false_true = iffD2 OF [nth (thms "HOL.simp_thms") 7, TrueI];
   378   val refl = thm "refl";
   379   val eqTrueI = thm "eqTrueI";
   380 in
   381 
   382 fun get_eq_datatype thy dtco =
   383   let
   384     val SOME (vs, cs) = DatatypePackage.get_datatype_spec thy dtco;
   385     fun mk_triv_inject co =
   386       let
   387         val ct' = Thm.cterm_of thy
   388           (Const (co, Type (dtco, map (fn (v, sort) => TVar ((v, 0), sort)) vs)))
   389         val cty' = Thm.ctyp_of_term ct';
   390         val SOME (ct, cty) = fold_aterms (fn Var (v, ty) =>
   391           (K o SOME) (Thm.cterm_of thy (Var (v, Thm.typ_of cty')), Thm.ctyp_of thy ty) | _ => I)
   392           (Thm.prop_of refl) NONE;
   393       in eqTrueI OF [Thm.instantiate ([(cty, cty')], [(ct, ct')]) refl] end;
   394     val inject1 = map_filter (fn (co, []) => SOME (mk_triv_inject co) | _ => NONE) cs
   395     val inject2 = (#inject o DatatypePackage.the_datatype thy) dtco;
   396     val ctxt = ProofContext.init thy;
   397     val simpset = Simplifier.context ctxt
   398       (MetaSimplifier.empty_ss addsimprocs [distinct_simproc]);
   399     val cos = map (fn (co, tys) =>
   400         (Const (co, tys ---> Type (dtco, map TFree vs)), tys)) cs;
   401     val tac = ALLGOALS (simp_tac simpset)
   402       THEN ALLGOALS (ProofContext.fact_tac [not_false_true, TrueI]);
   403     val distinct =
   404       mk_distinct cos
   405       |> map (fn t => Goal.prove_global thy [] [] t (K tac))
   406       |> (fn thms => thms @ map (fn thm => not_sym OF [thm]) thms)
   407   in inject1 @ inject2 @ distinct end;
   408 
   409 end;
   410 
   411 fun add_datatype_case_const dtco thy =
   412   let
   413     val {case_name, index, descr, ...} = DatatypePackage.the_datatype thy dtco;
   414   in
   415     CodegenPackage.add_appconst (case_name, CodegenPackage.appgen_case dest_case_expr) thy
   416   end;
   417 
   418 fun add_datatype_case_defs dtco thy =
   419   let
   420     val {case_rewrites, ...} = DatatypePackage.the_datatype thy dtco
   421   in
   422     fold_rev (CodegenData.add_func true) case_rewrites thy
   423   end;
   424 
   425 
   426 (** codetypes for code 2nd generation **)
   427 
   428 (* abstraction over datatypes vs. type copies *)
   429 
   430 fun codetypes_dependency thy =
   431   let
   432     val names =
   433       map (rpair true) (Symtab.keys (DatatypePackage.get_datatypes thy))
   434         @ map (rpair false) (TypecopyPackage.get_typecopies thy);
   435     fun add_node (name, is_dt) =
   436       let
   437         fun add_tycos (Type (tyco, tys)) = insert (op =) tyco #> fold add_tycos tys
   438           | add_tycos _ = I;
   439         val tys = if is_dt then
   440             (maps snd o snd o the o DatatypePackage.get_datatype_spec thy) name
   441           else
   442             [(#typ o the o TypecopyPackage.get_typecopy_info thy) name]
   443         val deps = (filter (AList.defined (op =) names) o maps (fn ty =>
   444           add_tycos ty [])) tys;
   445       in
   446         Graph.default_node (name, ())
   447         #> fold (fn name' =>
   448              Graph.default_node (name', ())
   449              #> Graph.add_edge (name', name)
   450            ) deps
   451       end
   452   in
   453     Graph.empty
   454     |> fold add_node names
   455     |> Graph.strong_conn
   456     |> map (AList.make (the o AList.lookup (op =) names))
   457   end;
   458 
   459 fun get_spec thy (dtco, true) =
   460       (the o DatatypePackage.get_datatype_spec thy) dtco
   461   | get_spec thy (tyco, false) =
   462       TypecopyPackage.get_spec thy tyco;
   463 
   464 local
   465   fun get_eq_thms thy tyco = case DatatypePackage.get_datatype thy tyco
   466    of SOME _ => get_eq_datatype thy tyco
   467     | NONE => [TypecopyPackage.get_eq thy tyco];
   468   fun constrain_op_eq_thms thy thms =
   469     let
   470       fun add_eq (Const ("op =", ty)) =
   471             fold (insert (eq_fst (op =)))
   472               (Term.add_tvarsT ty [])
   473         | add_eq _ =
   474             I
   475       val eqs = fold (fold_aterms add_eq o Thm.prop_of) thms [];
   476       val instT = map (fn (v_i, sort) =>
   477         (Thm.ctyp_of thy (TVar (v_i, sort)),
   478            Thm.ctyp_of thy (TVar (v_i, Sorts.inter_sort (Sign.classes_of thy) (sort, [HOLogic.class_eq]))))) eqs;
   479     in
   480       thms
   481       |> map (Thm.instantiate (instT, []))
   482     end;
   483 in
   484   fun get_eq thy tyco =
   485     get_eq_thms thy tyco
   486     |> maps ((#mk o #mk_rews o snd o MetaSimplifier.rep_ss o Simplifier.simpset_of) thy)
   487     |> constrain_op_eq_thms thy
   488 end;
   489 
   490 type hook = (string * (bool * ((string * sort) list * (string * typ list) list))) list
   491   -> theory -> theory;
   492 
   493 fun add_codetypes_hook_bootstrap hook thy =
   494   let
   495     fun add_spec thy (tyco, is_dt) =
   496       (tyco, (is_dt, get_spec thy (tyco, is_dt)));
   497     fun datatype_hook dtcos thy =
   498       hook (map (add_spec thy) (map (rpair true) dtcos)) thy;
   499     fun typecopy_hook ((tyco, _)) thy =
   500       hook ([(tyco, (false, TypecopyPackage.get_spec thy tyco))]) thy;
   501   in
   502     thy
   503     |> fold hook ((map o map) (add_spec thy) (codetypes_dependency thy))
   504     |> DatatypeHooks.add datatype_hook
   505     |> TypecopyPackage.add_hook typecopy_hook
   506   end;
   507 
   508 fun the_codetypes_mut_specs thy ([(tyco, is_dt)]) =
   509       let
   510         val (vs, cs) = get_spec thy (tyco, is_dt)
   511       in (vs, [(tyco, (is_dt, cs))]) end
   512   | the_codetypes_mut_specs thy (tycos' as (tyco, true) :: _) =
   513       let
   514         val tycos = map fst tycos';
   515         val tycos'' = (map (#1 o snd) o #descr o DatatypePackage.the_datatype thy) tyco;
   516         val _ = if gen_subset (op =) (tycos, tycos'') then () else
   517           error ("type constructors are not mutually recursive: " ^ (commas o map quote) tycos);
   518         val (vs::_, css) = split_list (map (the o DatatypePackage.get_datatype_spec thy) tycos);
   519       in (vs, map2 (fn (tyco, is_dt) => fn cs => (tyco, (is_dt, cs))) tycos' css) end;
   520 
   521 
   522 (* registering code types in code generator *)
   523 
   524 fun codetype_hook dtspecs =
   525   fold (fn (dtco, (_, spec)) => CodegenData.add_datatype (dtco, spec)) dtspecs;
   526 
   527 
   528 (* instrumentalizing the sort algebra *)
   529 
   530 fun get_codetypes_arities thy tycos sort =
   531   let
   532     val pp = Sign.pp thy;
   533     val algebra = Sign.classes_of thy;
   534     val (vs_proto, css_proto) = the_codetypes_mut_specs thy tycos;
   535     val vs = map (fn (v, vsort) => (v, Sorts.inter_sort algebra (vsort, sort))) vs_proto;
   536     val css = map (fn (tyco, (_, cs)) => (tyco, cs)) css_proto;
   537     val algebra' = algebra
   538       |> fold (fn (tyco, _) =>
   539            Sorts.add_arities pp (tyco, map (fn class => (class, map snd vs)) sort)) css;
   540     fun typ_sort_inst ty = CodegenConsts.typ_sort_inst algebra' (Logic.varifyT ty, sort);
   541     val venv = Vartab.empty
   542       |> fold (fn (v, sort) => Vartab.update_new ((v, 0), sort)) vs
   543       |> fold (fn (_, cs) => fold (fn (_, tys) => fold typ_sort_inst tys) cs) css;
   544     fun inst (v, _) = (v, (the o Vartab.lookup venv) (v, 0));
   545     val vs' = map inst vs;
   546     fun mk_arity tyco = (tyco, map snd vs', sort);
   547     fun mk_cons tyco (c, tys) =
   548       let
   549         val tys' = (map o Term.map_type_tfree) (TFree o inst) tys;
   550         val ts = Name.names Name.context "a" tys';
   551         val ty = (tys' ---> Type (tyco, map TFree vs'));
   552       in list_comb (Const (c, ty), map Free ts) end;
   553   in
   554     map (fn (tyco, cs) => (tyco, (mk_arity tyco, map (mk_cons tyco) cs))) css |> SOME
   555   end handle Class_Error => NONE;
   556 
   557 fun prove_codetypes_arities tac tycos sort f after_qed thy =
   558   case get_codetypes_arities thy tycos sort
   559    of NONE => thy
   560     | SOME insts => let
   561         fun proven (tyco, asorts, sort) =
   562           Sorts.of_sort (Sign.classes_of thy)
   563             (Type (tyco, map TFree (Name.names Name.context "'a" asorts)), sort);
   564         val (arities, css) = (split_list o map_filter
   565           (fn (tyco, (arity, cs)) => if proven arity
   566             then NONE else SOME (arity, (tyco, cs)))) insts;
   567       in
   568         thy
   569         |> not (null arities) ? (
   570             f arities css
   571             #-> (fn defs =>
   572               ClassPackage.prove_instance_arity tac arities defs
   573             #> after_qed arities css))
   574       end;
   575 
   576 
   577 (* operational equality *)
   578 
   579 fun eq_hook specs =
   580   let
   581     fun add_eq_thms (dtco, (_, (vs, cs))) thy =
   582       let
   583         val thy_ref = Theory.self_ref thy;
   584         val const = ("op =", SOME dtco);
   585         val get_thms = (fn () => get_eq (Theory.deref thy_ref) dtco |> rev);
   586       in
   587         CodegenData.add_funcl (const, CodegenData.lazy_thms get_thms) thy
   588       end;
   589   in
   590     prove_codetypes_arities (ClassPackage.intro_classes_tac [])
   591       (map (fn (tyco, (is_dt, _)) => (tyco, is_dt)) specs)
   592       [HOLogic.class_eq] ((K o K o pair) []) ((K o K) (fold add_eq_thms specs))
   593   end;
   594 
   595 
   596 
   597 (** theory setup **)
   598 
   599 val setup = 
   600   add_codegen "datatype" datatype_codegen
   601   #> add_tycodegen "datatype" datatype_tycodegen 
   602   #> DatatypeHooks.add (fold add_datatype_case_const)
   603   #> DatatypeHooks.add (fold add_datatype_case_defs)
   604 
   605 val setup_hooks =
   606   add_codetypes_hook_bootstrap codetype_hook
   607   #> add_codetypes_hook_bootstrap eq_hook
   608 
   609 
   610 end;