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