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