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