src/HOL/Tools/datatype_codegen.ML
author haftmann
Tue Aug 29 14:31:13 2006 +0200 (2006-08-29)
changeset 20426 9ffea7a8b31c
parent 20389 8b6ecb22ef35
child 20435 d2a30fed7596
permissions -rw-r--r--
added typecopy_package
berghofe@12446
     1
(*  Title:      HOL/datatype_codegen.ML
berghofe@12445
     2
    ID:         $Id$
haftmann@20105
     3
    Author:     Stefan Berghofer & Florian Haftmann, TU Muenchen
berghofe@12445
     4
haftmann@20426
     5
Code generator for inductive datatypes and type copies ("code types").
berghofe@12445
     6
*)
berghofe@12445
     7
berghofe@12445
     8
signature DATATYPE_CODEGEN =
berghofe@12445
     9
sig
haftmann@20426
    10
  val get_eq: theory -> string -> thm list
haftmann@19346
    11
  val get_datatype_spec_thms: theory -> string
haftmann@19346
    12
    -> (((string * sort) list * (string * typ list) list) * tactic) option
haftmann@20389
    13
  val datatype_tac: theory -> string -> tactic
haftmann@20105
    14
  val dest_case_expr: theory -> term
haftmann@20177
    15
    -> ((string * typ) list * ((term * typ) * (term * term) list)) option
haftmann@19886
    16
  val add_datatype_case_const: string -> theory -> theory
haftmann@19886
    17
  val add_datatype_case_defs: string -> theory -> theory
haftmann@20426
    18
haftmann@20426
    19
  type hook = (string * (bool * ((string * sort) list * (string * typ list) list))) list
haftmann@20426
    20
    -> theory -> theory
haftmann@20426
    21
  val codetypes_dependency: theory -> (string * bool) list list
haftmann@20426
    22
  val add_codetypes_hook_bootstrap: hook -> theory -> theory
haftmann@20426
    23
  val the_codetypes_mut_specs: theory -> (string * bool) list
haftmann@20426
    24
    -> ((string * sort) list * (string * (bool * (string * typ list) list)) list)
haftmann@20426
    25
  val get_codetypes_arities: theory -> (string * bool) list -> sort
haftmann@20190
    26
    -> (string * (((string * sort list) * sort) * term list)) list option
haftmann@20426
    27
  val prove_codetypes_arities: (thm list -> tactic) -> (string * bool) list -> sort
haftmann@20389
    28
    -> (theory -> ((string * sort list) * sort) list -> (string * term list) list
haftmann@20177
    29
    -> ((bstring * attribute list) * term) list) -> theory -> theory
haftmann@20426
    30
wenzelm@18708
    31
  val setup: theory -> theory
berghofe@12445
    32
end;
berghofe@12445
    33
berghofe@12445
    34
structure DatatypeCodegen : DATATYPE_CODEGEN =
berghofe@12445
    35
struct
berghofe@12445
    36
berghofe@12445
    37
open Codegen;
berghofe@12445
    38
berghofe@12445
    39
fun mk_tuple [p] = p
berghofe@12445
    40
  | mk_tuple ps = Pretty.block (Pretty.str "(" ::
skalberg@15570
    41
      List.concat (separate [Pretty.str ",", Pretty.brk 1] (map single ps)) @
berghofe@12445
    42
        [Pretty.str ")"]);
berghofe@12445
    43
berghofe@12445
    44
(**** datatype definition ****)
berghofe@12445
    45
berghofe@14104
    46
(* find shortest path to constructor with no recursive arguments *)
berghofe@14104
    47
berghofe@14104
    48
fun find_nonempty (descr: DatatypeAux.descr) is i =
berghofe@14104
    49
  let
haftmann@17521
    50
    val (_, _, constrs) = valOf (AList.lookup (op =) descr i);
skalberg@15531
    51
    fun arg_nonempty (_, DatatypeAux.DtRec i) = if i mem is then NONE
skalberg@15570
    52
          else Option.map (curry op + 1 o snd) (find_nonempty descr (i::is) i)
skalberg@15531
    53
      | arg_nonempty _ = SOME 0;
skalberg@15570
    54
    fun max xs = Library.foldl
skalberg@15531
    55
      (fn (NONE, _) => NONE
skalberg@15531
    56
        | (SOME i, SOME j) => SOME (Int.max (i, j))
skalberg@15531
    57
        | (_, NONE) => NONE) (SOME 0, xs);
berghofe@14104
    58
    val xs = sort (int_ord o pairself snd)
skalberg@15570
    59
      (List.mapPartial (fn (s, dts) => Option.map (pair s)
berghofe@14104
    60
        (max (map (arg_nonempty o DatatypeAux.strip_dtyp) dts))) constrs)
skalberg@15531
    61
  in case xs of [] => NONE | x :: _ => SOME x end;
berghofe@14104
    62
berghofe@17144
    63
fun add_dt_defs thy defs dep module gr (descr: DatatypeAux.descr) =
berghofe@12445
    64
  let
berghofe@12445
    65
    val sg = sign_of thy;
berghofe@12445
    66
    val tab = DatatypePackage.get_datatypes thy;
berghofe@12445
    67
skalberg@15570
    68
    val descr' = List.filter (can (map DatatypeAux.dest_DtTFree o #2 o snd)) descr;
skalberg@15570
    69
    val rtnames = map (#1 o snd) (List.filter (fn (_, (_, _, cs)) =>
berghofe@14104
    70
      exists (exists DatatypeAux.is_rec_type o snd) cs) descr');
berghofe@12445
    71
berghofe@17144
    72
    val (_, (tname, _, _)) :: _ = descr';
berghofe@17144
    73
    val node_id = tname ^ " (type)";
berghofe@17144
    74
    val module' = if_library (thyname_of_type tname thy) module;
berghofe@12445
    75
berghofe@12445
    76
    fun mk_dtdef gr prfx [] = (gr, [])
berghofe@12445
    77
      | mk_dtdef gr prfx ((_, (tname, dts, cs))::xs) =
berghofe@12445
    78
          let
berghofe@12445
    79
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@12445
    80
            val sorts = map (rpair []) tvs;
berghofe@12445
    81
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
berghofe@17144
    82
            val (gr', (_, type_id)) = mk_type_id module' tname gr;
berghofe@17144
    83
            val (gr'', ps) =
berghofe@17144
    84
              foldl_map (fn (gr, (cname, cargs)) =>
berghofe@17144
    85
                foldl_map (invoke_tycodegen thy defs node_id module' false)
berghofe@17144
    86
                  (gr, cargs) |>>>
berghofe@17144
    87
                mk_const_id module' cname) (gr', cs');
berghofe@17144
    88
            val (gr''', rest) = mk_dtdef gr'' "and " xs
berghofe@12445
    89
          in
berghofe@17144
    90
            (gr''',
berghofe@12445
    91
             Pretty.block (Pretty.str prfx ::
berghofe@12445
    92
               (if null tvs then [] else
berghofe@12445
    93
                  [mk_tuple (map Pretty.str tvs), Pretty.str " "]) @
berghofe@17144
    94
               [Pretty.str (type_id ^ " ="), Pretty.brk 1] @
skalberg@15570
    95
               List.concat (separate [Pretty.brk 1, Pretty.str "| "]
berghofe@17144
    96
                 (map (fn (ps', (_, cname)) => [Pretty.block
berghofe@17144
    97
                   (Pretty.str cname ::
berghofe@12445
    98
                    (if null ps' then [] else
skalberg@15570
    99
                     List.concat ([Pretty.str " of", Pretty.brk 1] ::
berghofe@12445
   100
                       separate [Pretty.str " *", Pretty.brk 1]
berghofe@12445
   101
                         (map single ps'))))]) ps))) :: rest)
berghofe@13754
   102
          end;
berghofe@13754
   103
berghofe@17144
   104
    fun mk_term_of_def gr prfx [] = []
berghofe@17144
   105
      | mk_term_of_def gr prfx ((_, (tname, dts, cs)) :: xs) =
berghofe@13754
   106
          let
berghofe@13754
   107
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@13754
   108
            val sorts = map (rpair []) tvs;
berghofe@13754
   109
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
berghofe@13754
   110
            val dts' = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
berghofe@13754
   111
            val T = Type (tname, dts');
berghofe@17144
   112
            val rest = mk_term_of_def gr "and " xs;
berghofe@13754
   113
            val (_, eqs) = foldl_map (fn (prfx, (cname, Ts)) =>
berghofe@13754
   114
              let val args = map (fn i =>
berghofe@13754
   115
                Pretty.str ("x" ^ string_of_int i)) (1 upto length Ts)
berghofe@13754
   116
              in ("  | ", Pretty.blk (4,
berghofe@17144
   117
                [Pretty.str prfx, mk_term_of gr module' false T, Pretty.brk 1,
berghofe@17144
   118
                 if null Ts then Pretty.str (snd (get_const_id cname gr))
berghofe@16645
   119
                 else parens (Pretty.block
berghofe@17144
   120
                   [Pretty.str (snd (get_const_id cname gr)),
berghofe@13754
   121
                    Pretty.brk 1, mk_tuple args]),
berghofe@13754
   122
                 Pretty.str " =", Pretty.brk 1] @
skalberg@15570
   123
                 List.concat (separate [Pretty.str " $", Pretty.brk 1]
berghofe@13754
   124
                   ([Pretty.str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
berghofe@13754
   125
                     mk_type false (Ts ---> T), Pretty.str ")"] ::
berghofe@17144
   126
                    map (fn (x, U) => [Pretty.block [mk_term_of gr module' false U,
berghofe@13754
   127
                      Pretty.brk 1, x]]) (args ~~ Ts)))))
berghofe@13754
   128
              end) (prfx, cs')
berghofe@14104
   129
          in eqs @ rest end;
berghofe@14104
   130
berghofe@17144
   131
    fun mk_gen_of_def gr prfx [] = []
berghofe@17144
   132
      | mk_gen_of_def gr prfx ((i, (tname, dts, cs)) :: xs) =
berghofe@14104
   133
          let
berghofe@14104
   134
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@14104
   135
            val sorts = map (rpair []) tvs;
berghofe@14104
   136
            val (cs1, cs2) =
skalberg@15570
   137
              List.partition (exists DatatypeAux.is_rec_type o snd) cs;
skalberg@15531
   138
            val SOME (cname, _) = find_nonempty descr [i] i;
berghofe@14104
   139
berghofe@14104
   140
            fun mk_delay p = Pretty.block
berghofe@14104
   141
              [Pretty.str "fn () =>", Pretty.brk 1, p];
berghofe@14104
   142
berghofe@15397
   143
            fun mk_constr s b (cname, dts) =
berghofe@14104
   144
              let
berghofe@17144
   145
                val gs = map (fn dt => mk_app false (mk_gen gr module' false rtnames s
berghofe@15397
   146
                    (DatatypeAux.typ_of_dtyp descr sorts dt))
berghofe@15397
   147
                  [Pretty.str (if b andalso DatatypeAux.is_rec_type dt then "0"
berghofe@15397
   148
                     else "j")]) dts;
berghofe@17144
   149
                val (_, id) = get_const_id cname gr
berghofe@14104
   150
              in case gs of
berghofe@14104
   151
                  _ :: _ :: _ => Pretty.block
berghofe@14104
   152
                    [Pretty.str id, Pretty.brk 1, mk_tuple gs]
berghofe@14104
   153
                | _ => mk_app false (Pretty.str id) (map parens gs)
berghofe@14104
   154
              end;
berghofe@14104
   155
berghofe@15397
   156
            fun mk_choice [c] = mk_constr "(i-1)" false c
berghofe@14104
   157
              | mk_choice cs = Pretty.block [Pretty.str "one_of",
berghofe@14104
   158
                  Pretty.brk 1, Pretty.blk (1, Pretty.str "[" ::
skalberg@15570
   159
                  List.concat (separate [Pretty.str ",", Pretty.fbrk]
berghofe@15397
   160
                    (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
berghofe@14104
   161
                  [Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"];
berghofe@14104
   162
berghofe@14104
   163
            val gs = map (Pretty.str o suffix "G" o strip_tname) tvs;
berghofe@17144
   164
            val gen_name = "gen_" ^ snd (get_type_id tname gr)
berghofe@14104
   165
berghofe@14104
   166
          in
berghofe@14104
   167
            Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@14104
   168
                (Pretty.str (prfx ^ gen_name ^
berghofe@14104
   169
                   (if null cs1 then "" else "'")) :: gs @
berghofe@14104
   170
                 (if null cs1 then [] else [Pretty.str "i"]) @
berghofe@14104
   171
                 [Pretty.str "j"]) @
berghofe@14104
   172
              [Pretty.str " =", Pretty.brk 1] @
berghofe@14104
   173
              (if not (null cs1) andalso not (null cs2)
berghofe@14104
   174
               then [Pretty.str "frequency", Pretty.brk 1,
berghofe@14104
   175
                 Pretty.blk (1, [Pretty.str "[",
berghofe@14104
   176
                   mk_tuple [Pretty.str "i", mk_delay (mk_choice cs1)],
berghofe@14104
   177
                   Pretty.str ",", Pretty.fbrk,
berghofe@14104
   178
                   mk_tuple [Pretty.str "1", mk_delay (mk_choice cs2)],
berghofe@14104
   179
                   Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"]
berghofe@14104
   180
               else if null cs2 then
berghofe@14104
   181
                 [Pretty.block [Pretty.str "(case", Pretty.brk 1,
berghofe@14104
   182
                   Pretty.str "i", Pretty.brk 1, Pretty.str "of",
berghofe@14104
   183
                   Pretty.brk 1, Pretty.str "0 =>", Pretty.brk 1,
haftmann@17521
   184
                   mk_constr "0" true (cname, valOf (AList.lookup (op =) cs cname)),
berghofe@14104
   185
                   Pretty.brk 1, Pretty.str "| _ =>", Pretty.brk 1,
berghofe@14104
   186
                   mk_choice cs1, Pretty.str ")"]]
berghofe@14104
   187
               else [mk_choice cs2])) ::
berghofe@14104
   188
            (if null cs1 then []
berghofe@14104
   189
             else [Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@14104
   190
                 (Pretty.str ("and " ^ gen_name) :: gs @ [Pretty.str "i"]) @
berghofe@14104
   191
               [Pretty.str " =", Pretty.brk 1] @
berghofe@14104
   192
               separate (Pretty.brk 1) (Pretty.str (gen_name ^ "'") :: gs @
berghofe@14104
   193
                 [Pretty.str "i", Pretty.str "i"]))]) @
berghofe@17144
   194
            mk_gen_of_def gr "and " xs
berghofe@14104
   195
          end
berghofe@13754
   196
berghofe@12445
   197
  in
berghofe@17144
   198
    (add_edge_acyclic (node_id, dep) gr
berghofe@12445
   199
        handle Graph.CYCLES _ => gr) handle Graph.UNDEF _ =>
berghofe@12445
   200
         let
berghofe@17144
   201
           val gr1 = add_edge (node_id, dep)
berghofe@17144
   202
             (new_node (node_id, (NONE, "", "")) gr);
berghofe@12445
   203
           val (gr2, dtdef) = mk_dtdef gr1 "datatype " descr';
berghofe@12445
   204
         in
berghofe@17144
   205
           map_node node_id (K (NONE, module',
berghofe@12445
   206
             Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk dtdef @
berghofe@13754
   207
               [Pretty.str ";"])) ^ "\n\n" ^
berghofe@13754
   208
             (if "term_of" mem !mode then
berghofe@13754
   209
                Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@17144
   210
                  (mk_term_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
berghofe@14104
   211
              else "") ^
berghofe@14104
   212
             (if "test" mem !mode then
berghofe@14104
   213
                Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@17144
   214
                  (mk_gen_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
berghofe@13754
   215
              else ""))) gr2
berghofe@17144
   216
         end
berghofe@12445
   217
  end;
berghofe@12445
   218
berghofe@12445
   219
berghofe@12445
   220
(**** case expressions ****)
berghofe@12445
   221
berghofe@17144
   222
fun pretty_case thy defs gr dep module brack constrs (c as Const (_, T)) ts =
berghofe@12445
   223
  let val i = length constrs
berghofe@12445
   224
  in if length ts <= i then
berghofe@17144
   225
       invoke_codegen thy defs dep module brack (gr, eta_expand c ts (i+1))
berghofe@12445
   226
    else
berghofe@12445
   227
      let
skalberg@15570
   228
        val ts1 = Library.take (i, ts);
skalberg@15570
   229
        val t :: ts2 = Library.drop (i, ts);
skalberg@15574
   230
        val names = foldr add_term_names
skalberg@15574
   231
          (map (fst o fst o dest_Var) (foldr add_term_vars [] ts1)) ts1;
skalberg@15570
   232
        val (Ts, dT) = split_last (Library.take (i+1, fst (strip_type T)));
berghofe@12445
   233
berghofe@12445
   234
        fun pcase gr [] [] [] = ([], gr)
berghofe@12445
   235
          | pcase gr ((cname, cargs)::cs) (t::ts) (U::Us) =
berghofe@12445
   236
              let
berghofe@12445
   237
                val j = length cargs;
wenzelm@20071
   238
                val xs = Name.variant_list names (replicate j "x");
skalberg@15570
   239
                val Us' = Library.take (j, fst (strip_type U));
berghofe@12445
   240
                val frees = map Free (xs ~~ Us');
berghofe@17144
   241
                val (gr0, cp) = invoke_codegen thy defs dep module false
berghofe@12445
   242
                  (gr, list_comb (Const (cname, Us' ---> dT), frees));
berghofe@12445
   243
                val t' = Envir.beta_norm (list_comb (t, frees));
berghofe@17144
   244
                val (gr1, p) = invoke_codegen thy defs dep module false (gr0, t');
berghofe@12445
   245
                val (ps, gr2) = pcase gr1 cs ts Us;
berghofe@12445
   246
              in
berghofe@12445
   247
                ([Pretty.block [cp, Pretty.str " =>", Pretty.brk 1, p]] :: ps, gr2)
berghofe@12445
   248
              end;
berghofe@12445
   249
berghofe@12445
   250
        val (ps1, gr1) = pcase gr constrs ts1 Ts;
skalberg@15570
   251
        val ps = List.concat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
berghofe@17144
   252
        val (gr2, p) = invoke_codegen thy defs dep module false (gr1, t);
berghofe@17144
   253
        val (gr3, ps2) = foldl_map (invoke_codegen thy defs dep module true) (gr2, ts2)
berghofe@12445
   254
      in (gr3, (if not (null ts2) andalso brack then parens else I)
berghofe@12445
   255
        (Pretty.block (separate (Pretty.brk 1)
berghofe@12445
   256
          (Pretty.block ([Pretty.str "(case ", p, Pretty.str " of",
berghofe@12445
   257
             Pretty.brk 1] @ ps @ [Pretty.str ")"]) :: ps2))))
berghofe@12445
   258
      end
berghofe@12445
   259
  end;
berghofe@12445
   260
berghofe@12445
   261
berghofe@12445
   262
(**** constructors ****)
berghofe@12445
   263
berghofe@17144
   264
fun pretty_constr thy defs gr dep module brack args (c as Const (s, T)) ts =
berghofe@12445
   265
  let val i = length args
berghofe@12445
   266
  in if i > 1 andalso length ts < i then
berghofe@17144
   267
      invoke_codegen thy defs dep module brack (gr, eta_expand c ts i)
berghofe@12445
   268
     else
berghofe@12445
   269
       let
berghofe@17144
   270
         val id = mk_qual_id module (get_const_id s gr);
berghofe@16645
   271
         val (gr', ps) = foldl_map
berghofe@17144
   272
           (invoke_codegen thy defs dep module (i = 1)) (gr, ts);
berghofe@12445
   273
       in (case args of
berghofe@12445
   274
          _ :: _ :: _ => (gr', (if brack then parens else I)
berghofe@12445
   275
            (Pretty.block [Pretty.str id, Pretty.brk 1, mk_tuple ps]))
berghofe@12445
   276
        | _ => (gr', mk_app brack (Pretty.str id) ps))
berghofe@12445
   277
       end
berghofe@12445
   278
  end;
berghofe@12445
   279
berghofe@12445
   280
berghofe@12445
   281
(**** code generators for terms and types ****)
berghofe@12445
   282
berghofe@17144
   283
fun datatype_codegen thy defs gr dep module brack t = (case strip_comb t of
berghofe@12445
   284
   (c as Const (s, T), ts) =>
haftmann@18247
   285
       (case Library.find_first (fn (_, {index, descr, case_name, ...}) =>
berghofe@12445
   286
         s = case_name orelse
haftmann@17521
   287
           AList.defined (op =) ((#3 o the o AList.lookup (op =) descr) index) s)
berghofe@12445
   288
             (Symtab.dest (DatatypePackage.get_datatypes thy)) of
skalberg@15531
   289
          NONE => NONE
skalberg@15531
   290
        | SOME (tname, {index, descr, ...}) =>
haftmann@18247
   291
           if is_some (get_assoc_code thy s T) then NONE else
haftmann@17521
   292
           let val SOME (_, _, constrs) = AList.lookup (op =) descr index
haftmann@17521
   293
           in (case (AList.lookup (op =) constrs s, strip_type T) of
berghofe@17144
   294
               (NONE, _) => SOME (pretty_case thy defs gr dep module brack
haftmann@18247
   295
                 ((#3 o the o AList.lookup (op =) descr) index) c ts)
berghofe@16645
   296
             | (SOME args, (_, Type _)) => SOME (pretty_constr thy defs
berghofe@17144
   297
                 (fst (invoke_tycodegen thy defs dep module false
berghofe@16645
   298
                    (gr, snd (strip_type T))))
berghofe@17144
   299
                 dep module brack args c ts)
skalberg@15531
   300
             | _ => NONE)
berghofe@12445
   301
           end)
skalberg@15531
   302
 |  _ => NONE);
berghofe@12445
   303
berghofe@17144
   304
fun datatype_tycodegen thy defs gr dep module brack (Type (s, Ts)) =
wenzelm@17412
   305
      (case Symtab.lookup (DatatypePackage.get_datatypes thy) s of
skalberg@15531
   306
         NONE => NONE
skalberg@15531
   307
       | SOME {descr, ...} =>
skalberg@15570
   308
           if isSome (get_assoc_type thy s) then NONE else
berghofe@16645
   309
           let
berghofe@16645
   310
             val (gr', ps) = foldl_map
berghofe@17144
   311
               (invoke_tycodegen thy defs dep module false) (gr, Ts);
berghofe@17144
   312
             val gr'' = add_dt_defs thy defs dep module gr' descr
berghofe@16645
   313
           in SOME (gr'',
berghofe@12445
   314
             Pretty.block ((if null Ts then [] else
berghofe@12445
   315
               [mk_tuple ps, Pretty.str " "]) @
berghofe@17144
   316
               [Pretty.str (mk_qual_id module (get_type_id s gr''))]))
berghofe@12445
   317
           end)
berghofe@16645
   318
  | datatype_tycodegen _ _ _ _ _ _ _ = NONE;
berghofe@12445
   319
haftmann@18247
   320
haftmann@20426
   321
(** datatypes for code 2nd generation **)
haftmann@20177
   322
haftmann@20105
   323
fun dtyp_of_case_const thy c =
haftmann@20105
   324
  get_first (fn (dtco, { case_name, ... }) => if case_name = c then SOME dtco else NONE)
haftmann@20105
   325
    ((Symtab.dest o DatatypePackage.get_datatypes) thy);
haftmann@20105
   326
haftmann@20105
   327
fun dest_case_app cs ts tys =
haftmann@20105
   328
  let
haftmann@20192
   329
    val abs = Name.names Name.context "a" (Library.drop (length ts, tys));
haftmann@20105
   330
    val (ts', t) = split_last (ts @ map Free abs);
haftmann@20105
   331
    val (tys', sty) = split_last tys;
haftmann@20105
   332
    fun freenames_of t = fold_aterms
haftmann@20105
   333
      (fn Free (v, _) => insert (op =) v | _ => I) t [];
haftmann@20105
   334
    fun dest_case ((c, tys_decl), ty) t =
haftmann@20105
   335
      let
haftmann@20105
   336
        val (vs, t') = Term.strip_abs_eta (length tys_decl) t;
haftmann@20105
   337
        val c' = list_comb (Const (c, map snd vs ---> sty), map Free vs);
haftmann@20105
   338
      in (c', t') end;
haftmann@20105
   339
  in (abs, ((t, sty), map2 dest_case (cs ~~ tys') ts')) end;
haftmann@20105
   340
haftmann@20105
   341
fun dest_case_expr thy t =
haftmann@20105
   342
  case strip_comb t
haftmann@20105
   343
   of (Const (c, ty), ts) =>
haftmann@20105
   344
        (case dtyp_of_case_const thy c
haftmann@20105
   345
         of SOME dtco =>
haftmann@20105
   346
              let val (vs, cs) = (the o DatatypePackage.get_datatype_spec thy) dtco;
haftmann@20105
   347
              in SOME (dest_case_app cs ts (Library.take (length cs + 1, (fst o strip_type) ty))) end
haftmann@20105
   348
          | _ => NONE)
haftmann@20105
   349
    | _ => NONE;
haftmann@20105
   350
haftmann@20426
   351
fun mk_distinct cos =
haftmann@20426
   352
  let
haftmann@20426
   353
    fun sym_product [] = []
haftmann@20426
   354
      | sym_product (x::xs) = map (pair x) xs @ sym_product xs;
haftmann@20426
   355
    fun mk_co_args (co, tys) ctxt =
haftmann@20426
   356
      let
haftmann@20426
   357
        val names = Name.invents ctxt "a" (length tys);
haftmann@20426
   358
        val ctxt' = fold Name.declare names ctxt;
haftmann@20426
   359
        val vs = map2 (curry Free) names tys;
haftmann@20426
   360
      in (vs, ctxt) end;
haftmann@20426
   361
    fun mk_dist ((co1, tys1), (co2, tys2)) =
haftmann@20426
   362
      let
haftmann@20426
   363
        val ((xs1, xs2), _) = Name.context
haftmann@20426
   364
          |> mk_co_args (co1, tys1)
haftmann@20426
   365
          ||>> mk_co_args (co2, tys2);
haftmann@20426
   366
        val prem = HOLogic.mk_eq
haftmann@20426
   367
          (list_comb (co1, xs1), list_comb (co2, xs2));
haftmann@20426
   368
        val t = HOLogic.mk_not prem;
haftmann@20426
   369
      in HOLogic.mk_Trueprop t end;
haftmann@20426
   370
  in map mk_dist (sym_product cos) end;
haftmann@20426
   371
haftmann@20426
   372
local
haftmann@20426
   373
  val not_false_true = iffD2 OF [nth (thms "HOL.simp_thms") 7, TrueI];
haftmann@20426
   374
in fun get_eq thy dtco =
haftmann@20426
   375
  let
haftmann@20426
   376
    val SOME (vs, cs) = DatatypePackage.get_datatype_spec thy dtco;
haftmann@20426
   377
    fun mk_triv_inject co =
haftmann@20426
   378
      let
haftmann@20426
   379
        val ct' = Thm.cterm_of thy
haftmann@20426
   380
          (Const (co, Type (dtco, map (fn (v, sort) => TVar ((v, 0), sort)) vs)))
haftmann@20426
   381
        val cty' = Thm.ctyp_of_term ct';
haftmann@20426
   382
        val refl = Thm.prop_of HOL.refl;
haftmann@20426
   383
        val SOME (ct, cty) = fold_aterms (fn Var (v, ty) =>
haftmann@20426
   384
          (K o SOME) (Thm.cterm_of thy (Var (v, Thm.typ_of cty')), Thm.ctyp_of thy ty) | _ => I)
haftmann@20426
   385
          refl NONE;
haftmann@20426
   386
      in eqTrueI OF [Thm.instantiate ([(cty, cty')], [(ct, ct')]) HOL.refl] end;
haftmann@20426
   387
    val inject1 = map_filter (fn (co, []) => SOME (mk_triv_inject co) | _ => NONE) cs
haftmann@20426
   388
    val inject2 = (#inject o DatatypePackage.the_datatype thy) dtco;
haftmann@20426
   389
    val ctxt = Context.init_proof thy;
haftmann@20426
   390
    val simpset = Simplifier.context ctxt
haftmann@20426
   391
      (MetaSimplifier.empty_ss addsimprocs [distinct_simproc]);
haftmann@20426
   392
    val cos = map (fn (co, tys) =>
haftmann@20426
   393
        (Const (co, tys ---> Type (dtco, map TFree vs)), tys)) cs;
haftmann@20426
   394
    val tac = ALLGOALS (simp_tac simpset)
haftmann@20426
   395
      THEN ALLGOALS (ProofContext.fact_tac [not_false_true, TrueI]);
haftmann@20426
   396
    val distinct =
haftmann@20426
   397
      mk_distinct cos
haftmann@20426
   398
      |> map (fn t => Goal.prove_global thy [] [] t (K tac))
haftmann@20426
   399
  in inject1 @ inject2 @ distinct end;
haftmann@20426
   400
end (*local*);
haftmann@20426
   401
haftmann@19346
   402
fun datatype_tac thy dtco =
haftmann@19346
   403
  let
haftmann@19346
   404
    val ctxt = Context.init_proof thy;
haftmann@19346
   405
    val inject = (#inject o DatatypePackage.the_datatype thy) dtco;
haftmann@19346
   406
    val simpset = Simplifier.context ctxt
haftmann@19346
   407
      (MetaSimplifier.empty_ss addsimprocs [distinct_simproc]);
haftmann@19346
   408
  in
haftmann@19458
   409
    (TRY o ALLGOALS o match_tac) [HOL.eq_reflection]
haftmann@19346
   410
    THEN (
haftmann@19458
   411
      (ALLGOALS o match_tac) (eqTrueI :: inject)
haftmann@19346
   412
      ORELSE (ALLGOALS o simp_tac) simpset
haftmann@19346
   413
    )
haftmann@19458
   414
    THEN (ALLGOALS o match_tac) [HOL.refl, Drule.reflexive_thm]
haftmann@19346
   415
  end;
haftmann@19346
   416
haftmann@19346
   417
fun get_datatype_spec_thms thy dtco =
haftmann@19346
   418
  case DatatypePackage.get_datatype_spec thy dtco
haftmann@19346
   419
   of SOME vs_cos =>
haftmann@19346
   420
        SOME (vs_cos, datatype_tac thy dtco)
haftmann@19346
   421
    | NONE => NONE;
haftmann@19346
   422
haftmann@19599
   423
fun add_datatype_case_const dtco thy =
haftmann@19599
   424
  let
haftmann@20105
   425
    val {case_name, index, descr, ...} = DatatypePackage.the_datatype thy dtco;
haftmann@19599
   426
  in
haftmann@20105
   427
    CodegenPackage.add_appconst_i (case_name, CodegenPackage.appgen_case dest_case_expr) thy
haftmann@19599
   428
  end;
haftmann@19346
   429
haftmann@19818
   430
fun add_datatype_case_defs dtco thy =
haftmann@19818
   431
  let
haftmann@19818
   432
    val {case_rewrites, ...} = DatatypePackage.the_datatype thy dtco
haftmann@19818
   433
  in
haftmann@19818
   434
    fold CodegenTheorems.add_fun case_rewrites thy
haftmann@19818
   435
  end;
haftmann@19818
   436
haftmann@20426
   437
haftmann@20426
   438
(** codetypes for code 2nd generation **)
haftmann@20426
   439
haftmann@20426
   440
type hook = (string * (bool * ((string * sort) list * (string * typ list) list))) list
haftmann@20426
   441
  -> theory -> theory;
haftmann@20426
   442
haftmann@20426
   443
fun codetypes_dependency thy =
haftmann@20426
   444
  let
haftmann@20426
   445
    val names =
haftmann@20426
   446
      map (rpair true) (Symtab.keys (DatatypePackage.get_datatypes thy))
haftmann@20426
   447
        @ map (rpair false) (TypecopyPackage.get_typecopies thy);
haftmann@20426
   448
    fun add_node (name, is_dt) =
haftmann@20426
   449
      let
haftmann@20426
   450
        fun add_tycos (Type (tyco, tys)) = insert (op =) tyco #> fold add_tycos tys
haftmann@20426
   451
          | add_tycos _ = I;
haftmann@20426
   452
        val tys = if is_dt then
haftmann@20426
   453
            (maps snd o snd o the o DatatypePackage.get_datatype_spec thy) name
haftmann@20426
   454
          else
haftmann@20426
   455
            [(#typ o the o TypecopyPackage.get_typecopy_info thy) name]
haftmann@20426
   456
        val deps = (filter (AList.defined (op =) names) o maps (fn ty =>
haftmann@20426
   457
          add_tycos ty [])) tys;
haftmann@20426
   458
      in
haftmann@20426
   459
        Graph.default_node (name, ())
haftmann@20426
   460
        #> fold (fn name' =>
haftmann@20426
   461
             Graph.default_node (name', ())
haftmann@20426
   462
             #> Graph.add_edge (name', name)
haftmann@20426
   463
           ) deps
haftmann@20426
   464
      end
haftmann@20426
   465
  in
haftmann@20426
   466
    Graph.empty
haftmann@20426
   467
    |> fold add_node names
haftmann@20426
   468
    |> Graph.strong_conn
haftmann@20426
   469
    |> map (AList.make (the o AList.lookup (op =) names))
haftmann@20426
   470
  end;
haftmann@20426
   471
haftmann@20426
   472
fun mk_typecopy_spec ({ vs, constr, typ, ... } : TypecopyPackage.info) =
haftmann@20426
   473
  (vs, [(constr, [typ])]);
haftmann@20426
   474
haftmann@20426
   475
fun get_spec thy (dtco, true) =
haftmann@20426
   476
      (the o DatatypePackage.get_datatype_spec thy) dtco
haftmann@20426
   477
  | get_spec thy (tyco, false) =
haftmann@20426
   478
      (mk_typecopy_spec o the o TypecopyPackage.get_typecopy_info thy) tyco;
haftmann@20426
   479
haftmann@20426
   480
fun add_spec thy (tyco, is_dt) =
haftmann@20426
   481
  (tyco, (is_dt, get_spec thy (tyco, is_dt)));
haftmann@20426
   482
haftmann@20426
   483
fun add_codetypes_hook_bootstrap hook thy =
haftmann@20426
   484
  let
haftmann@20426
   485
    fun datatype_hook dtcos thy =
haftmann@20426
   486
      hook (map (add_spec thy) (map (rpair true) dtcos)) thy;
haftmann@20426
   487
    fun typecopy_hook ((tyco, info )) thy =
haftmann@20426
   488
      hook ([(tyco, (false, mk_typecopy_spec info))]) thy;
haftmann@20426
   489
  in
haftmann@20426
   490
    thy
haftmann@20426
   491
    |> fold hook ((map o map) (add_spec thy) (codetypes_dependency thy))
haftmann@20426
   492
    |> DatatypeHooks.add datatype_hook
haftmann@20426
   493
    |> TypecopyPackage.add_hook typecopy_hook
haftmann@20426
   494
  end;
haftmann@20426
   495
haftmann@20426
   496
fun the_codetypes_mut_specs thy ([(tyco, is_dt)]) =
haftmann@20426
   497
      let
haftmann@20426
   498
        val (vs, cs) = get_spec thy (tyco, is_dt)
haftmann@20426
   499
      in (vs, [(tyco, (is_dt, cs))]) end
haftmann@20426
   500
  | the_codetypes_mut_specs thy (tycos' as (tyco, true) :: _) =
haftmann@20426
   501
      let
haftmann@20426
   502
        val tycos = map fst tycos';
haftmann@20426
   503
        val tycos'' = (map (#1 o snd) o #descr o DatatypePackage.the_datatype thy) tyco;
haftmann@20426
   504
        val _ = if gen_subset (op =) (tycos, tycos'') then () else
haftmann@20426
   505
          error ("datatype constructors are not mutually recursive: " ^ (commas o map quote) tycos);
haftmann@20426
   506
        val (vs::_, css) = split_list (map (the o DatatypePackage.get_datatype_spec thy) tycos);
haftmann@20426
   507
      in (vs, map2 (fn (tyco, is_dt) => fn cs => (tyco, (is_dt, cs))) tycos' css) end;
haftmann@20426
   508
haftmann@20426
   509
fun get_codetypes_arities thy tycos sort =
haftmann@20426
   510
  let
haftmann@20426
   511
    val algebra = Sign.classes_of thy;
haftmann@20426
   512
    val (vs_proto, css_proto) = the_codetypes_mut_specs thy tycos;
haftmann@20426
   513
    val vs = map (fn (v, vsort) => (v, Sorts.inter_sort algebra (vsort, sort))) vs_proto;
haftmann@20426
   514
    fun inst_type tyco (c, tys) =
haftmann@20426
   515
      let
haftmann@20426
   516
        val tys' = (map o map_atyps)
haftmann@20426
   517
          (fn TFree (v, _) => TFree (v, the (AList.lookup (op =) vs v))) tys
haftmann@20426
   518
      in (c, tys') end;
haftmann@20426
   519
    val css = map (fn (tyco, (_, cs)) => (tyco, (map (inst_type tyco) cs))) css_proto;
haftmann@20426
   520
    fun mk_arity tyco =
haftmann@20426
   521
      ((tyco, map snd vs), sort);
haftmann@20426
   522
    fun typ_of_sort ty =
haftmann@20426
   523
      let
haftmann@20426
   524
        val arities = map (fn (tyco, _) => ((tyco, map snd vs), sort)) css;
haftmann@20426
   525
      in ClassPackage.assume_arities_of_sort thy arities (ty, sort) end;
haftmann@20426
   526
    fun mk_cons tyco (c, tys) =
haftmann@20426
   527
      let
haftmann@20426
   528
        val ts = Name.names Name.context "a" tys;
haftmann@20426
   529
        val ty = tys ---> Type (tyco, map TFree vs);
haftmann@20426
   530
      in list_comb (Const (c, ty), map Free ts) end;
haftmann@20426
   531
  in if forall (fn (_, cs) => forall (fn (_, tys) => forall typ_of_sort tys) cs) css
haftmann@20426
   532
    then SOME (
haftmann@20426
   533
      map (fn (tyco, cs) => (tyco, (mk_arity tyco, map (mk_cons tyco) cs))) css
haftmann@20426
   534
    ) else NONE
haftmann@20426
   535
  end;
haftmann@20426
   536
haftmann@20426
   537
fun prove_codetypes_arities tac tycos sort f thy =
haftmann@20426
   538
  case get_codetypes_arities thy tycos sort
haftmann@20426
   539
   of NONE => thy
haftmann@20426
   540
    | SOME insts => let
haftmann@20426
   541
        fun proven ((tyco, asorts), sort) =
haftmann@20426
   542
          Sorts.of_sort (Sign.classes_of thy)
haftmann@20426
   543
            (Type (tyco, map TFree (Name.names Name.context "'a" asorts)), sort);
haftmann@20426
   544
        val (arities, css) = (split_list o map_filter
haftmann@20426
   545
          (fn (tyco, (arity, cs)) => if proven arity
haftmann@20426
   546
            then NONE else SOME (arity, (tyco, cs)))) insts;
haftmann@20426
   547
      in
haftmann@20426
   548
        thy
haftmann@20426
   549
        |> K ((not o null) arities) ? ClassPackage.prove_instance_arity tac
haftmann@20426
   550
             arities ("", []) (f thy arities css)
haftmann@20426
   551
      end;
haftmann@20426
   552
haftmann@20426
   553
haftmann@20426
   554
haftmann@20426
   555
(** theory setup **)
haftmann@20426
   556
haftmann@19008
   557
val setup = 
wenzelm@18708
   558
  add_codegen "datatype" datatype_codegen #>
wenzelm@18708
   559
  add_tycodegen "datatype" datatype_tycodegen #>
haftmann@19346
   560
  CodegenTheorems.add_datatype_extr
haftmann@19346
   561
    get_datatype_spec_thms #>
haftmann@20177
   562
  DatatypeHooks.add (fold add_datatype_case_const) #>
haftmann@20177
   563
  DatatypeHooks.add (fold add_datatype_case_defs)
berghofe@12445
   564
berghofe@12445
   565
end;