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