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