src/HOL/Tools/datatype_codegen.ML
author haftmann
Wed Jan 10 09:28:24 2007 +0100 (2007-01-10)
changeset 22052 792c18b8f214
parent 22051 2b8909d9d66a
child 22175 d9e3e4c30d6b
permissions -rw-r--r--
improved case patterns
     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 get_cert: theory -> bool * string -> thm list
    13   val get_cert_datatype: theory -> string -> thm list
    14   val dest_case_expr: theory -> term
    15     -> ((string * typ) list * ((term * typ) * (term * term) list)) option
    16   val add_datatype_case_const: string -> theory -> theory
    17   val add_datatype_case_defs: string -> theory -> theory
    18 
    19   type hook = (string * (bool * ((string * sort) list * (string * typ list) list))) list
    20     -> theory -> theory
    21   val codetype_hook: hook
    22   val eq_hook: hook
    23   val codetypes_dependency: theory -> (string * bool) list list
    24   val add_codetypes_hook_bootstrap: hook -> theory -> theory
    25   val the_codetypes_mut_specs: theory -> (string * bool) list
    26     -> ((string * sort) list * (string * (bool * (string * typ list) list)) list)
    27   val get_codetypes_arities: theory -> (string * bool) list -> sort
    28     -> (string * (((string * sort list) * sort) * term list)) list option
    29   val prove_codetypes_arities: tactic -> (string * bool) list -> sort
    30     -> (((string * sort list) * sort) list -> (string * term list) list -> theory
    31     -> ((bstring * attribute list) * term) list * theory)
    32     -> (((string * sort list) * sort) list -> (string * term list) list -> theory -> theory)
    33     -> theory -> theory
    34 
    35   val setup: theory -> theory
    36   val setup_hooks: 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      module')
   223   end;
   224 
   225 
   226 (**** case expressions ****)
   227 
   228 fun pretty_case thy defs gr dep module brack constrs (c as Const (_, T)) ts =
   229   let val i = length constrs
   230   in if length ts <= i then
   231        invoke_codegen thy defs dep module brack (gr, eta_expand c ts (i+1))
   232     else
   233       let
   234         val ts1 = Library.take (i, ts);
   235         val t :: ts2 = Library.drop (i, ts);
   236         val names = foldr add_term_names
   237           (map (fst o fst o dest_Var) (foldr add_term_vars [] ts1)) ts1;
   238         val (Ts, dT) = split_last (Library.take (i+1, fst (strip_type T)));
   239 
   240         fun pcase gr [] [] [] = ([], gr)
   241           | pcase gr ((cname, cargs)::cs) (t::ts) (U::Us) =
   242               let
   243                 val j = length cargs;
   244                 val xs = Name.variant_list names (replicate j "x");
   245                 val Us' = Library.take (j, fst (strip_type U));
   246                 val frees = map Free (xs ~~ Us');
   247                 val (gr0, cp) = invoke_codegen thy defs dep module false
   248                   (gr, list_comb (Const (cname, Us' ---> dT), frees));
   249                 val t' = Envir.beta_norm (list_comb (t, frees));
   250                 val (gr1, p) = invoke_codegen thy defs dep module false (gr0, t');
   251                 val (ps, gr2) = pcase gr1 cs ts Us;
   252               in
   253                 ([Pretty.block [cp, Pretty.str " =>", Pretty.brk 1, p]] :: ps, gr2)
   254               end;
   255 
   256         val (ps1, gr1) = pcase gr constrs ts1 Ts;
   257         val ps = List.concat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
   258         val (gr2, p) = invoke_codegen thy defs dep module false (gr1, t);
   259         val (gr3, ps2) = foldl_map (invoke_codegen thy defs dep module true) (gr2, ts2)
   260       in (gr3, (if not (null ts2) andalso brack then parens else I)
   261         (Pretty.block (separate (Pretty.brk 1)
   262           (Pretty.block ([Pretty.str "(case ", p, Pretty.str " of",
   263              Pretty.brk 1] @ ps @ [Pretty.str ")"]) :: ps2))))
   264       end
   265   end;
   266 
   267 
   268 (**** constructors ****)
   269 
   270 fun pretty_constr thy defs gr dep module brack args (c as Const (s, T)) ts =
   271   let val i = length args
   272   in if i > 1 andalso length ts < i then
   273       invoke_codegen thy defs dep module brack (gr, eta_expand c ts i)
   274      else
   275        let
   276          val id = mk_qual_id module (get_const_id s gr);
   277          val (gr', ps) = foldl_map
   278            (invoke_codegen thy defs dep module (i = 1)) (gr, ts);
   279        in (case args of
   280           _ :: _ :: _ => (gr', (if brack then parens else I)
   281             (Pretty.block [Pretty.str id, Pretty.brk 1, mk_tuple ps]))
   282         | _ => (gr', mk_app brack (Pretty.str id) ps))
   283        end
   284   end;
   285 
   286 
   287 (**** code generators for terms and types ****)
   288 
   289 fun datatype_codegen thy defs gr dep module brack t = (case strip_comb t of
   290    (c as Const (s, T), ts) =>
   291        (case Library.find_first (fn (_, {index, descr, case_name, ...}) =>
   292          s = case_name orelse
   293            AList.defined (op =) ((#3 o the o AList.lookup (op =) descr) index) s)
   294              (Symtab.dest (DatatypePackage.get_datatypes thy)) of
   295           NONE => NONE
   296         | SOME (tname, {index, descr, ...}) =>
   297            if is_some (get_assoc_code thy s T) then NONE else
   298            let val SOME (_, _, constrs) = AList.lookup (op =) descr index
   299            in (case (AList.lookup (op =) constrs s, strip_type T) of
   300                (NONE, _) => SOME (pretty_case thy defs gr dep module brack
   301                  ((#3 o the o AList.lookup (op =) descr) index) c ts)
   302              | (SOME args, (_, Type _)) => SOME (pretty_constr thy defs
   303                  (fst (invoke_tycodegen thy defs dep module false
   304                     (gr, snd (strip_type T))))
   305                  dep module brack args c ts)
   306              | _ => NONE)
   307            end)
   308  |  _ => NONE);
   309 
   310 fun datatype_tycodegen thy defs gr dep module brack (Type (s, Ts)) =
   311       (case Symtab.lookup (DatatypePackage.get_datatypes thy) s of
   312          NONE => NONE
   313        | SOME {descr, ...} =>
   314            if isSome (get_assoc_type thy s) then NONE else
   315            let
   316              val (gr', ps) = foldl_map
   317                (invoke_tycodegen thy defs dep module false) (gr, Ts);
   318              val (gr'', module') = add_dt_defs thy defs dep module gr' descr;
   319              val (gr''', tyid) = mk_type_id module' s gr''
   320            in SOME (gr''',
   321              Pretty.block ((if null Ts then [] else
   322                [mk_tuple ps, Pretty.str " "]) @
   323                [Pretty.str (mk_qual_id module tyid)]))
   324            end)
   325   | datatype_tycodegen _ _ _ _ _ _ _ = NONE;
   326 
   327 
   328 (** datatypes for code 2nd generation **)
   329 
   330 fun dtyp_of_case_const thy c =
   331   get_first (fn (dtco, { case_name, ... }) => if case_name = c then SOME dtco else NONE)
   332     ((Symtab.dest o DatatypePackage.get_datatypes) thy);
   333 
   334 fun dest_case_app cs ts tys =
   335   let
   336     val names = (Name.make_context o map fst) (fold Term.add_tfrees ts []);
   337     val abs = Name.names names "a" (Library.drop (length ts, tys));
   338     val (ts', t) = split_last (ts @ map Free abs);
   339     val (tys', sty) = split_last tys;
   340     fun dest_case ((c, tys_decl), ty) t =
   341       let
   342         val (vs, t') = Term.strip_abs_eta (length tys_decl) t;
   343         val c' = list_comb (Const (c, map snd vs ---> sty), map Free vs);
   344       in case t'
   345        of Const ("undefined", _) => NONE
   346         | _ => SOME (c', t')
   347       end;
   348   in (abs, ((t, sty), map2 dest_case (cs ~~ tys') ts' |> map_filter I)) end;
   349 
   350 fun dest_case_expr thy t =
   351   case strip_comb t
   352    of (Const (c, ty), ts) =>
   353         (case dtyp_of_case_const thy c
   354          of SOME dtco =>
   355               let val (vs, cs) = (the o DatatypePackage.get_datatype_spec thy) dtco;
   356               in SOME (dest_case_app cs ts (Library.take (length cs + 1, (fst o strip_type) ty))) end
   357           | _ => NONE)
   358     | _ => NONE;
   359 
   360 fun mk_distinct cos =
   361   let
   362     fun sym_product [] = []
   363       | sym_product (x::xs) = map (pair x) xs @ sym_product xs;
   364     fun mk_co_args (co, tys) ctxt =
   365       let
   366         val names = Name.invents ctxt "a" (length tys);
   367         val ctxt' = fold Name.declare names ctxt;
   368         val vs = map2 (curry Free) names tys;
   369       in (vs, ctxt') end;
   370     fun mk_dist ((co1, tys1), (co2, tys2)) =
   371       let
   372         val ((xs1, xs2), _) = Name.context
   373           |> mk_co_args (co1, tys1)
   374           ||>> mk_co_args (co2, tys2);
   375         val prem = HOLogic.mk_eq
   376           (list_comb (co1, xs1), list_comb (co2, xs2));
   377         val t = HOLogic.mk_not prem;
   378       in HOLogic.mk_Trueprop t end;
   379   in map mk_dist (sym_product cos) end;
   380 
   381 local
   382   val bool_eq_implies = iffD1;
   383   val rew_eq = thm "HOL.atomize_eq" |> Thm.symmetric;
   384   val rew_conj = thm "HOL.atomize_conj" |> Thm.symmetric;
   385   val not_false_true = iffD2 OF [nth (thms "HOL.simp_thms") 7, TrueI];
   386   val not_eq_quodlibet = thm "not_eq_quodlibet";
   387 in
   388 
   389 fun get_cert_datatype thy dtco =
   390   let
   391     val SOME (vs, cs) = DatatypePackage.get_datatype_spec thy dtco;
   392     val inject = (#inject o DatatypePackage.the_datatype thy) dtco
   393       |> map (fn thm => bool_eq_implies OF [thm] )
   394       |> map (MetaSimplifier.rewrite_rule [rew_eq, rew_conj]);
   395     val ctxt = ProofContext.init thy;
   396     val simpset = Simplifier.context ctxt
   397       (MetaSimplifier.empty_ss addsimprocs [DatatypePackage.distinct_simproc]);
   398     val cos = map (fn (co, tys) =>
   399         (Const (co, tys ---> Type (dtco, map TFree vs)), tys)) cs;
   400     val tac = ALLGOALS (simp_tac simpset)
   401       THEN ALLGOALS (ProofContext.fact_tac [not_false_true, TrueI]);
   402     val distinct =
   403       mk_distinct cos
   404       |> map (fn t => Goal.prove_global thy [] [] t (K tac))
   405       |> map (fn thm => not_eq_quodlibet OF [thm])
   406   in inject @ distinct end
   407 
   408 end;
   409 
   410 local
   411   val not_sym = thm "HOL.not_sym";
   412   val not_false_true = iffD2 OF [nth (thms "HOL.simp_thms") 7, TrueI];
   413   val refl = thm "refl";
   414   val eqTrueI = thm "eqTrueI";
   415 in
   416 
   417 fun get_eq_datatype thy dtco =
   418   let
   419     val SOME (vs, cs) = DatatypePackage.get_datatype_spec thy dtco;
   420     fun mk_triv_inject co =
   421       let
   422         val ct' = Thm.cterm_of thy
   423           (Const (co, Type (dtco, map (fn (v, sort) => TVar ((v, 0), sort)) vs)))
   424         val cty' = Thm.ctyp_of_term ct';
   425         val SOME (ct, cty) = fold_aterms (fn Var (v, ty) =>
   426           (K o SOME) (Thm.cterm_of thy (Var (v, Thm.typ_of cty')), Thm.ctyp_of thy ty) | _ => I)
   427           (Thm.prop_of refl) NONE;
   428       in eqTrueI OF [Thm.instantiate ([(cty, cty')], [(ct, ct')]) refl] end;
   429     val inject1 = map_filter (fn (co, []) => SOME (mk_triv_inject co) | _ => NONE) cs
   430     val inject2 = (#inject o DatatypePackage.the_datatype thy) dtco;
   431     val ctxt = ProofContext.init thy;
   432     val simpset = Simplifier.context ctxt
   433       (MetaSimplifier.empty_ss addsimprocs [distinct_simproc]);
   434     val cos = map (fn (co, tys) =>
   435         (Const (co, tys ---> Type (dtco, map TFree vs)), tys)) cs;
   436     val tac = ALLGOALS (simp_tac simpset)
   437       THEN ALLGOALS (ProofContext.fact_tac [not_false_true, TrueI]);
   438     val distinct =
   439       mk_distinct cos
   440       |> map (fn t => Goal.prove_global thy [] [] t (K tac))
   441       |> (fn thms => thms @ map (fn thm => not_sym OF [thm]) thms)
   442   in inject1 @ inject2 @ distinct end;
   443 
   444 end;
   445 
   446 fun add_datatype_case_const dtco thy =
   447   let
   448     val {case_name, index, descr, ...} = DatatypePackage.the_datatype thy dtco;
   449   in
   450     CodegenPackage.add_appconst (case_name, CodegenPackage.appgen_case dest_case_expr) thy
   451   end;
   452 
   453 fun add_datatype_case_defs dtco thy =
   454   let
   455     val {case_rewrites, ...} = DatatypePackage.the_datatype thy dtco
   456   in
   457     fold_rev CodegenData.add_func case_rewrites thy
   458   end;
   459 
   460 
   461 (** codetypes for code 2nd generation **)
   462 
   463 (* abstraction over datatypes vs. type copies *)
   464 
   465 fun codetypes_dependency thy =
   466   let
   467     val names =
   468       map (rpair true) (Symtab.keys (DatatypePackage.get_datatypes thy))
   469         @ map (rpair false) (TypecopyPackage.get_typecopies thy);
   470     fun add_node (name, is_dt) =
   471       let
   472         fun add_tycos (Type (tyco, tys)) = insert (op =) tyco #> fold add_tycos tys
   473           | add_tycos _ = I;
   474         val tys = if is_dt then
   475             (maps snd o snd o the o DatatypePackage.get_datatype_spec thy) name
   476           else
   477             [(#typ o the o TypecopyPackage.get_typecopy_info thy) name]
   478         val deps = (filter (AList.defined (op =) names) o maps (fn ty =>
   479           add_tycos ty [])) tys;
   480       in
   481         Graph.default_node (name, ())
   482         #> fold (fn name' =>
   483              Graph.default_node (name', ())
   484              #> Graph.add_edge (name', name)
   485            ) deps
   486       end
   487   in
   488     Graph.empty
   489     |> fold add_node names
   490     |> Graph.strong_conn
   491     |> map (AList.make (the o AList.lookup (op =) names))
   492   end;
   493 
   494 fun get_spec thy (dtco, true) =
   495       (the o DatatypePackage.get_datatype_spec thy) dtco
   496   | get_spec thy (tyco, false) =
   497       TypecopyPackage.get_spec thy tyco;
   498 
   499 fun get_cert thy (true, dtco) = get_cert_datatype thy dtco
   500   | get_cert thy (false, dtco) = [TypecopyPackage.get_cert thy dtco];
   501 
   502 local
   503   fun get_eq_thms thy tyco = case DatatypePackage.get_datatype thy tyco
   504    of SOME _ => get_eq_datatype thy tyco
   505     | NONE => [TypecopyPackage.get_eq thy tyco];
   506   fun constrain_op_eq_thms thy thms =
   507     let
   508       fun add_eq (Const ("op =", ty)) =
   509             fold (insert (eq_fst (op =)))
   510               (Term.add_tvarsT ty [])
   511         | add_eq _ =
   512             I
   513       val eqs = fold (fold_aterms add_eq o Thm.prop_of) thms [];
   514       val instT = map (fn (v_i, sort) =>
   515         (Thm.ctyp_of thy (TVar (v_i, sort)),
   516            Thm.ctyp_of thy (TVar (v_i, Sorts.inter_sort (Sign.classes_of thy) (sort, [HOLogic.class_eq]))))) eqs;
   517     in
   518       thms
   519       |> map (Thm.instantiate (instT, []))
   520     end;
   521 in
   522   fun get_eq thy tyco =
   523     get_eq_thms thy tyco
   524     |> maps ((#mk o #mk_rews o snd o MetaSimplifier.rep_ss o Simplifier.simpset_of) thy)
   525     |> constrain_op_eq_thms thy
   526 end;
   527 
   528 type hook = (string * (bool * ((string * sort) list * (string * typ list) list))) list
   529   -> theory -> theory;
   530 
   531 fun add_codetypes_hook_bootstrap hook thy =
   532   let
   533     fun add_spec thy (tyco, is_dt) =
   534       (tyco, (is_dt, get_spec thy (tyco, is_dt)));
   535     fun datatype_hook dtcos thy =
   536       hook (map (add_spec thy) (map (rpair true) dtcos)) thy;
   537     fun typecopy_hook ((tyco, _)) thy =
   538       hook ([(tyco, (false, TypecopyPackage.get_spec thy tyco))]) thy;
   539   in
   540     thy
   541     |> fold hook ((map o map) (add_spec thy) (codetypes_dependency thy))
   542     |> DatatypeHooks.add datatype_hook
   543     |> TypecopyPackage.add_hook typecopy_hook
   544   end;
   545 
   546 fun the_codetypes_mut_specs thy ([(tyco, is_dt)]) =
   547       let
   548         val (vs, cs) = get_spec thy (tyco, is_dt)
   549       in (vs, [(tyco, (is_dt, cs))]) end
   550   | the_codetypes_mut_specs thy (tycos' as (tyco, true) :: _) =
   551       let
   552         val tycos = map fst tycos';
   553         val tycos'' = (map (#1 o snd) o #descr o DatatypePackage.the_datatype thy) tyco;
   554         val _ = if gen_subset (op =) (tycos, tycos'') then () else
   555           error ("datatype constructors are not mutually recursive: " ^ (commas o map quote) tycos);
   556         val (vs::_, css) = split_list (map (the o DatatypePackage.get_datatype_spec thy) tycos);
   557       in (vs, map2 (fn (tyco, is_dt) => fn cs => (tyco, (is_dt, cs))) tycos' css) end;
   558 
   559 
   560 (* registering code types in code generator *)
   561 
   562 fun codetype_hook specs =
   563   let
   564     fun add (dtco, (flag, spec)) thy =
   565       let
   566         fun cert thy_ref = (fn () => get_cert (Theory.deref thy_ref) (flag, dtco));
   567       in
   568         CodegenData.add_datatype
   569           (dtco, (spec, CodegenData.lazy (cert (Theory.self_ref thy)))) thy
   570       end;
   571   in fold add specs end;
   572 
   573 
   574 (* instrumentalizing the sort algebra *)
   575 
   576 fun get_codetypes_arities thy tycos sort =
   577   let
   578     val algebra = Sign.classes_of thy;
   579     val (vs_proto, css_proto) = the_codetypes_mut_specs thy tycos;
   580     val vs = map (fn (v, vsort) => (v, Sorts.inter_sort algebra (vsort, sort))) vs_proto;
   581     fun inst_type tyco (c, tys) =
   582       let
   583         val tys' = (map o map_atyps)
   584           (fn TFree (v, _) => TFree (v, the (AList.lookup (op =) vs v))) tys
   585       in (c, tys') end;
   586     val css = map (fn (tyco, (_, cs)) => (tyco, (map (inst_type tyco) cs))) css_proto;
   587     fun mk_arity tyco =
   588       ((tyco, map snd vs), sort);
   589     fun typ_of_sort ty =
   590       let
   591         val arities = map (fn (tyco, _) => ((tyco, map snd vs), sort)) css;
   592       in ClassPackage.assume_arities_of_sort thy arities (ty, sort) end;
   593     fun mk_cons tyco (c, tys) =
   594       let
   595         val ts = Name.names Name.context "a" tys;
   596         val ty = tys ---> Type (tyco, map TFree vs);
   597       in list_comb (Const (c, ty), map Free ts) end;
   598   in if forall (fn (_, cs) => forall (fn (_, tys) => forall typ_of_sort tys) cs) css
   599     then SOME (
   600       map (fn (tyco, cs) => (tyco, (mk_arity tyco, map (mk_cons tyco) cs))) css
   601     ) else NONE
   602   end;
   603 
   604 fun prove_codetypes_arities tac tycos sort f after_qed thy =
   605   case get_codetypes_arities thy tycos sort
   606    of NONE => thy
   607     | SOME insts => let
   608         fun proven ((tyco, asorts), sort) =
   609           Sorts.of_sort (Sign.classes_of thy)
   610             (Type (tyco, map TFree (Name.names Name.context "'a" asorts)), sort);
   611         val (arities, css) = (split_list o map_filter
   612           (fn (tyco, (arity, cs)) => if proven arity
   613             then NONE else SOME (arity, (tyco, cs)))) insts;
   614       in
   615         thy
   616         |> not (null arities) ? (
   617             f arities css
   618             #-> (fn defs =>
   619               ClassPackage.prove_instance_arity tac arities defs
   620             #> after_qed arities css))
   621       end;
   622 
   623 
   624 (* operational equality *)
   625 
   626 fun eq_hook specs =
   627   let
   628     fun add_eq_thms (dtco, (_, (vs, cs))) thy =
   629       let
   630         val thy_ref = Theory.self_ref thy;
   631         val ty = Type (dtco, map TFree vs) |> Logic.varifyT;
   632         val c = CodegenConsts.norm thy ("op =", [ty]);
   633         val get_thms = (fn () => get_eq (Theory.deref thy_ref) dtco |> rev);
   634       in
   635         CodegenData.add_funcl (c, CodegenData.lazy get_thms) thy
   636       end;
   637   in
   638     prove_codetypes_arities (ClassPackage.intro_classes_tac [])
   639       (map (fn (tyco, (is_dt, _)) => (tyco, is_dt)) specs)
   640       [HOLogic.class_eq] ((K o K o pair) []) ((K o K) (fold add_eq_thms specs))
   641   end;
   642 
   643 
   644 
   645 (** theory setup **)
   646 
   647 val setup = 
   648   add_codegen "datatype" datatype_codegen
   649   #> add_tycodegen "datatype" datatype_tycodegen 
   650   #> DatatypeHooks.add (fold add_datatype_case_const)
   651   #> DatatypeHooks.add (fold add_datatype_case_defs)
   652 
   653 val setup_hooks =
   654   add_codetypes_hook_bootstrap codetype_hook
   655   #> add_codetypes_hook_bootstrap eq_hook
   656 
   657 
   658 end;