src/HOL/Tools/datatype_codegen.ML
author haftmann
Thu Oct 04 19:54:46 2007 +0200 (2007-10-04)
changeset 24845 abcd15369ffa
parent 24711 e8bba7723858
child 24976 821628d16552
permissions -rw-r--r--
tuned datatype_codegen setup
haftmann@24589
     1
(*  Title:      HOL/Tools/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@23811
    14
  val get_case_cert: theory -> string -> thm
haftmann@20426
    15
haftmann@20426
    16
  type hook = (string * (bool * ((string * sort) list * (string * typ list) list))) list
haftmann@20426
    17
    -> theory -> theory
haftmann@20597
    18
  val codetype_hook: hook
haftmann@20597
    19
  val eq_hook: hook
haftmann@24626
    20
  val add_codetypes_hook: hook -> theory -> theory
haftmann@20426
    21
  val the_codetypes_mut_specs: theory -> (string * bool) list
haftmann@20426
    22
    -> ((string * sort) list * (string * (bool * (string * typ list) list)) list)
haftmann@20426
    23
  val get_codetypes_arities: theory -> (string * bool) list -> sort
haftmann@24626
    24
    -> (string * (arity * term list)) list
haftmann@21924
    25
  val prove_codetypes_arities: tactic -> (string * bool) list -> sort
wenzelm@22331
    26
    -> (arity list -> (string * term list) list -> theory
haftmann@22423
    27
      -> ((bstring * Attrib.src list) * term) list * theory)
haftmann@24423
    28
    -> (arity list -> (string * term list) list -> thm list -> theory -> theory)
haftmann@20835
    29
    -> 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
skalberg@15570
    65
    val descr' = List.filter (can (map DatatypeAux.dest_DtTFree o #2 o snd)) descr;
skalberg@15570
    66
    val rtnames = map (#1 o snd) (List.filter (fn (_, (_, _, cs)) =>
berghofe@14104
    67
      exists (exists DatatypeAux.is_rec_type o snd) cs) descr');
berghofe@12445
    68
berghofe@17144
    69
    val (_, (tname, _, _)) :: _ = descr';
berghofe@17144
    70
    val node_id = tname ^ " (type)";
berghofe@17144
    71
    val module' = if_library (thyname_of_type tname thy) module;
berghofe@12445
    72
berghofe@12445
    73
    fun mk_dtdef gr prfx [] = (gr, [])
berghofe@12445
    74
      | mk_dtdef gr prfx ((_, (tname, dts, cs))::xs) =
berghofe@12445
    75
          let
berghofe@12445
    76
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@12445
    77
            val sorts = map (rpair []) tvs;
berghofe@12445
    78
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
berghofe@17144
    79
            val (gr', (_, type_id)) = mk_type_id module' tname gr;
berghofe@17144
    80
            val (gr'', ps) =
berghofe@17144
    81
              foldl_map (fn (gr, (cname, cargs)) =>
berghofe@17144
    82
                foldl_map (invoke_tycodegen thy defs node_id module' false)
berghofe@17144
    83
                  (gr, cargs) |>>>
berghofe@17144
    84
                mk_const_id module' cname) (gr', cs');
berghofe@17144
    85
            val (gr''', rest) = mk_dtdef gr'' "and " xs
berghofe@12445
    86
          in
berghofe@17144
    87
            (gr''',
berghofe@12445
    88
             Pretty.block (Pretty.str prfx ::
berghofe@12445
    89
               (if null tvs then [] else
berghofe@12445
    90
                  [mk_tuple (map Pretty.str tvs), Pretty.str " "]) @
berghofe@17144
    91
               [Pretty.str (type_id ^ " ="), Pretty.brk 1] @
skalberg@15570
    92
               List.concat (separate [Pretty.brk 1, Pretty.str "| "]
berghofe@17144
    93
                 (map (fn (ps', (_, cname)) => [Pretty.block
berghofe@17144
    94
                   (Pretty.str cname ::
berghofe@12445
    95
                    (if null ps' then [] else
skalberg@15570
    96
                     List.concat ([Pretty.str " of", Pretty.brk 1] ::
berghofe@12445
    97
                       separate [Pretty.str " *", Pretty.brk 1]
berghofe@12445
    98
                         (map single ps'))))]) ps))) :: rest)
berghofe@13754
    99
          end;
berghofe@13754
   100
berghofe@17144
   101
    fun mk_term_of_def gr prfx [] = []
berghofe@17144
   102
      | mk_term_of_def gr prfx ((_, (tname, dts, cs)) :: xs) =
berghofe@13754
   103
          let
berghofe@13754
   104
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@13754
   105
            val sorts = map (rpair []) tvs;
berghofe@13754
   106
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
berghofe@13754
   107
            val dts' = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
berghofe@13754
   108
            val T = Type (tname, dts');
berghofe@17144
   109
            val rest = mk_term_of_def gr "and " xs;
berghofe@13754
   110
            val (_, eqs) = foldl_map (fn (prfx, (cname, Ts)) =>
berghofe@13754
   111
              let val args = map (fn i =>
berghofe@13754
   112
                Pretty.str ("x" ^ string_of_int i)) (1 upto length Ts)
berghofe@13754
   113
              in ("  | ", Pretty.blk (4,
berghofe@17144
   114
                [Pretty.str prfx, mk_term_of gr module' false T, Pretty.brk 1,
berghofe@17144
   115
                 if null Ts then Pretty.str (snd (get_const_id cname gr))
berghofe@16645
   116
                 else parens (Pretty.block
berghofe@17144
   117
                   [Pretty.str (snd (get_const_id cname gr)),
berghofe@13754
   118
                    Pretty.brk 1, mk_tuple args]),
berghofe@13754
   119
                 Pretty.str " =", Pretty.brk 1] @
skalberg@15570
   120
                 List.concat (separate [Pretty.str " $", Pretty.brk 1]
berghofe@13754
   121
                   ([Pretty.str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
berghofe@13754
   122
                     mk_type false (Ts ---> T), Pretty.str ")"] ::
berghofe@17144
   123
                    map (fn (x, U) => [Pretty.block [mk_term_of gr module' false U,
berghofe@13754
   124
                      Pretty.brk 1, x]]) (args ~~ Ts)))))
berghofe@13754
   125
              end) (prfx, cs')
berghofe@14104
   126
          in eqs @ rest end;
berghofe@14104
   127
berghofe@17144
   128
    fun mk_gen_of_def gr prfx [] = []
berghofe@17144
   129
      | mk_gen_of_def gr prfx ((i, (tname, dts, cs)) :: xs) =
berghofe@14104
   130
          let
berghofe@14104
   131
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@14104
   132
            val sorts = map (rpair []) tvs;
berghofe@14104
   133
            val (cs1, cs2) =
skalberg@15570
   134
              List.partition (exists DatatypeAux.is_rec_type o snd) cs;
skalberg@15531
   135
            val SOME (cname, _) = find_nonempty descr [i] i;
berghofe@14104
   136
berghofe@14104
   137
            fun mk_delay p = Pretty.block
berghofe@14104
   138
              [Pretty.str "fn () =>", Pretty.brk 1, p];
berghofe@14104
   139
berghofe@15397
   140
            fun mk_constr s b (cname, dts) =
berghofe@14104
   141
              let
berghofe@17144
   142
                val gs = map (fn dt => mk_app false (mk_gen gr module' false rtnames s
berghofe@15397
   143
                    (DatatypeAux.typ_of_dtyp descr sorts dt))
berghofe@15397
   144
                  [Pretty.str (if b andalso DatatypeAux.is_rec_type dt then "0"
berghofe@15397
   145
                     else "j")]) dts;
berghofe@17144
   146
                val (_, id) = get_const_id cname gr
berghofe@14104
   147
              in case gs of
berghofe@14104
   148
                  _ :: _ :: _ => Pretty.block
berghofe@14104
   149
                    [Pretty.str id, Pretty.brk 1, mk_tuple gs]
berghofe@14104
   150
                | _ => mk_app false (Pretty.str id) (map parens gs)
berghofe@14104
   151
              end;
berghofe@14104
   152
berghofe@15397
   153
            fun mk_choice [c] = mk_constr "(i-1)" false c
berghofe@14104
   154
              | mk_choice cs = Pretty.block [Pretty.str "one_of",
berghofe@14104
   155
                  Pretty.brk 1, Pretty.blk (1, Pretty.str "[" ::
skalberg@15570
   156
                  List.concat (separate [Pretty.str ",", Pretty.fbrk]
berghofe@15397
   157
                    (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
berghofe@14104
   158
                  [Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"];
berghofe@14104
   159
berghofe@14104
   160
            val gs = map (Pretty.str o suffix "G" o strip_tname) tvs;
berghofe@17144
   161
            val gen_name = "gen_" ^ snd (get_type_id tname gr)
berghofe@14104
   162
berghofe@14104
   163
          in
berghofe@14104
   164
            Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@14104
   165
                (Pretty.str (prfx ^ gen_name ^
berghofe@14104
   166
                   (if null cs1 then "" else "'")) :: gs @
berghofe@14104
   167
                 (if null cs1 then [] else [Pretty.str "i"]) @
berghofe@14104
   168
                 [Pretty.str "j"]) @
berghofe@14104
   169
              [Pretty.str " =", Pretty.brk 1] @
berghofe@14104
   170
              (if not (null cs1) andalso not (null cs2)
berghofe@14104
   171
               then [Pretty.str "frequency", Pretty.brk 1,
berghofe@14104
   172
                 Pretty.blk (1, [Pretty.str "[",
berghofe@14104
   173
                   mk_tuple [Pretty.str "i", mk_delay (mk_choice cs1)],
berghofe@14104
   174
                   Pretty.str ",", Pretty.fbrk,
berghofe@14104
   175
                   mk_tuple [Pretty.str "1", mk_delay (mk_choice cs2)],
berghofe@14104
   176
                   Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"]
berghofe@14104
   177
               else if null cs2 then
berghofe@14104
   178
                 [Pretty.block [Pretty.str "(case", Pretty.brk 1,
berghofe@14104
   179
                   Pretty.str "i", Pretty.brk 1, Pretty.str "of",
berghofe@14104
   180
                   Pretty.brk 1, Pretty.str "0 =>", Pretty.brk 1,
haftmann@17521
   181
                   mk_constr "0" true (cname, valOf (AList.lookup (op =) cs cname)),
berghofe@14104
   182
                   Pretty.brk 1, Pretty.str "| _ =>", Pretty.brk 1,
berghofe@14104
   183
                   mk_choice cs1, Pretty.str ")"]]
berghofe@14104
   184
               else [mk_choice cs2])) ::
berghofe@14104
   185
            (if null cs1 then []
berghofe@14104
   186
             else [Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@14104
   187
                 (Pretty.str ("and " ^ gen_name) :: gs @ [Pretty.str "i"]) @
berghofe@14104
   188
               [Pretty.str " =", Pretty.brk 1] @
berghofe@14104
   189
               separate (Pretty.brk 1) (Pretty.str (gen_name ^ "'") :: gs @
berghofe@14104
   190
                 [Pretty.str "i", Pretty.str "i"]))]) @
berghofe@17144
   191
            mk_gen_of_def gr "and " xs
berghofe@14104
   192
          end
berghofe@13754
   193
berghofe@12445
   194
  in
berghofe@20681
   195
    ((add_edge_acyclic (node_id, dep) gr
berghofe@12445
   196
        handle Graph.CYCLES _ => gr) handle Graph.UNDEF _ =>
berghofe@12445
   197
         let
berghofe@17144
   198
           val gr1 = add_edge (node_id, dep)
berghofe@17144
   199
             (new_node (node_id, (NONE, "", "")) gr);
berghofe@12445
   200
           val (gr2, dtdef) = mk_dtdef gr1 "datatype " descr';
berghofe@12445
   201
         in
berghofe@17144
   202
           map_node node_id (K (NONE, module',
berghofe@12445
   203
             Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk dtdef @
berghofe@13754
   204
               [Pretty.str ";"])) ^ "\n\n" ^
berghofe@13754
   205
             (if "term_of" mem !mode then
berghofe@13754
   206
                Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@17144
   207
                  (mk_term_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
berghofe@14104
   208
              else "") ^
berghofe@14104
   209
             (if "test" mem !mode then
berghofe@14104
   210
                Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@17144
   211
                  (mk_gen_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
berghofe@13754
   212
              else ""))) gr2
berghofe@20681
   213
         end,
berghofe@20681
   214
     module')
berghofe@12445
   215
  end;
berghofe@12445
   216
berghofe@12445
   217
berghofe@12445
   218
(**** case expressions ****)
berghofe@12445
   219
berghofe@17144
   220
fun pretty_case thy defs gr dep module brack constrs (c as Const (_, T)) ts =
berghofe@12445
   221
  let val i = length constrs
berghofe@12445
   222
  in if length ts <= i then
berghofe@17144
   223
       invoke_codegen thy defs dep module brack (gr, eta_expand c ts (i+1))
berghofe@12445
   224
    else
berghofe@12445
   225
      let
skalberg@15570
   226
        val ts1 = Library.take (i, ts);
skalberg@15570
   227
        val t :: ts2 = Library.drop (i, ts);
skalberg@15574
   228
        val names = foldr add_term_names
skalberg@15574
   229
          (map (fst o fst o dest_Var) (foldr add_term_vars [] ts1)) ts1;
skalberg@15570
   230
        val (Ts, dT) = split_last (Library.take (i+1, fst (strip_type T)));
berghofe@12445
   231
berghofe@12445
   232
        fun pcase gr [] [] [] = ([], gr)
berghofe@12445
   233
          | pcase gr ((cname, cargs)::cs) (t::ts) (U::Us) =
berghofe@12445
   234
              let
berghofe@12445
   235
                val j = length cargs;
wenzelm@20071
   236
                val xs = Name.variant_list names (replicate j "x");
skalberg@15570
   237
                val Us' = Library.take (j, fst (strip_type U));
berghofe@12445
   238
                val frees = map Free (xs ~~ Us');
berghofe@17144
   239
                val (gr0, cp) = invoke_codegen thy defs dep module false
berghofe@12445
   240
                  (gr, list_comb (Const (cname, Us' ---> dT), frees));
berghofe@12445
   241
                val t' = Envir.beta_norm (list_comb (t, frees));
berghofe@17144
   242
                val (gr1, p) = invoke_codegen thy defs dep module false (gr0, t');
berghofe@12445
   243
                val (ps, gr2) = pcase gr1 cs ts Us;
berghofe@12445
   244
              in
berghofe@12445
   245
                ([Pretty.block [cp, Pretty.str " =>", Pretty.brk 1, p]] :: ps, gr2)
berghofe@12445
   246
              end;
berghofe@12445
   247
berghofe@12445
   248
        val (ps1, gr1) = pcase gr constrs ts1 Ts;
skalberg@15570
   249
        val ps = List.concat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
berghofe@17144
   250
        val (gr2, p) = invoke_codegen thy defs dep module false (gr1, t);
berghofe@17144
   251
        val (gr3, ps2) = foldl_map (invoke_codegen thy defs dep module true) (gr2, ts2)
berghofe@12445
   252
      in (gr3, (if not (null ts2) andalso brack then parens else I)
berghofe@12445
   253
        (Pretty.block (separate (Pretty.brk 1)
berghofe@12445
   254
          (Pretty.block ([Pretty.str "(case ", p, Pretty.str " of",
berghofe@12445
   255
             Pretty.brk 1] @ ps @ [Pretty.str ")"]) :: ps2))))
berghofe@12445
   256
      end
berghofe@12445
   257
  end;
berghofe@12445
   258
berghofe@12445
   259
berghofe@12445
   260
(**** constructors ****)
berghofe@12445
   261
berghofe@17144
   262
fun pretty_constr thy defs gr dep module brack args (c as Const (s, T)) ts =
berghofe@12445
   263
  let val i = length args
berghofe@12445
   264
  in if i > 1 andalso length ts < i then
berghofe@17144
   265
      invoke_codegen thy defs dep module brack (gr, eta_expand c ts i)
berghofe@12445
   266
     else
berghofe@12445
   267
       let
berghofe@17144
   268
         val id = mk_qual_id module (get_const_id s gr);
berghofe@16645
   269
         val (gr', ps) = foldl_map
berghofe@17144
   270
           (invoke_codegen thy defs dep module (i = 1)) (gr, ts);
berghofe@12445
   271
       in (case args of
berghofe@12445
   272
          _ :: _ :: _ => (gr', (if brack then parens else I)
berghofe@12445
   273
            (Pretty.block [Pretty.str id, Pretty.brk 1, mk_tuple ps]))
berghofe@12445
   274
        | _ => (gr', mk_app brack (Pretty.str id) ps))
berghofe@12445
   275
       end
berghofe@12445
   276
  end;
berghofe@12445
   277
berghofe@12445
   278
berghofe@12445
   279
(**** code generators for terms and types ****)
berghofe@12445
   280
berghofe@17144
   281
fun datatype_codegen thy defs gr dep module brack t = (case strip_comb t of
berghofe@12445
   282
   (c as Const (s, T), ts) =>
berghofe@22778
   283
     (case DatatypePackage.datatype_of_case thy s of
berghofe@22778
   284
        SOME {index, descr, ...} =>
haftmann@22921
   285
          if is_some (get_assoc_code thy (s, T)) then NONE else
berghofe@22778
   286
          SOME (pretty_case thy defs gr dep module brack
berghofe@22778
   287
            (#3 (the (AList.lookup op = descr index))) c ts)
berghofe@22778
   288
      | NONE => case (DatatypePackage.datatype_of_constr thy s, strip_type T) of
berghofe@22778
   289
        (SOME {index, descr, ...}, (_, U as Type _)) =>
haftmann@22921
   290
          if is_some (get_assoc_code thy (s, T)) then NONE else
berghofe@22778
   291
          let val SOME args = AList.lookup op =
berghofe@22778
   292
            (#3 (the (AList.lookup op = descr index))) s
berghofe@22778
   293
          in
berghofe@22778
   294
            SOME (pretty_constr thy defs
berghofe@22778
   295
              (fst (invoke_tycodegen thy defs dep module false (gr, U)))
berghofe@22778
   296
              dep module brack args c ts)
berghofe@22778
   297
          end
berghofe@22778
   298
      | _ => NONE)
berghofe@22778
   299
 | _ => NONE);
berghofe@12445
   300
berghofe@17144
   301
fun datatype_tycodegen thy defs gr dep module brack (Type (s, Ts)) =
berghofe@22778
   302
      (case DatatypePackage.get_datatype thy s of
skalberg@15531
   303
         NONE => NONE
skalberg@15531
   304
       | SOME {descr, ...} =>
haftmann@22921
   305
           if is_some (get_assoc_type thy s) then NONE else
berghofe@16645
   306
           let
berghofe@16645
   307
             val (gr', ps) = foldl_map
berghofe@17144
   308
               (invoke_tycodegen thy defs dep module false) (gr, Ts);
berghofe@20681
   309
             val (gr'', module') = add_dt_defs thy defs dep module gr' descr;
berghofe@20681
   310
             val (gr''', tyid) = mk_type_id module' s gr''
berghofe@20681
   311
           in SOME (gr''',
berghofe@12445
   312
             Pretty.block ((if null Ts then [] else
berghofe@12445
   313
               [mk_tuple ps, Pretty.str " "]) @
berghofe@20681
   314
               [Pretty.str (mk_qual_id module tyid)]))
berghofe@12445
   315
           end)
berghofe@16645
   316
  | datatype_tycodegen _ _ _ _ _ _ _ = NONE;
berghofe@12445
   317
haftmann@18247
   318
haftmann@20426
   319
(** datatypes for code 2nd generation **)
haftmann@20177
   320
haftmann@20105
   321
fun dtyp_of_case_const thy c =
berghofe@22778
   322
  Option.map (fn {descr, index, ...} => #1 (the (AList.lookup op = descr index)))
berghofe@22778
   323
    (DatatypePackage.datatype_of_case thy c);
haftmann@20105
   324
haftmann@20105
   325
fun dest_case_app cs ts tys =
haftmann@20105
   326
  let
haftmann@22052
   327
    val names = (Name.make_context o map fst) (fold Term.add_tfrees ts []);
haftmann@22052
   328
    val abs = Name.names names "a" (Library.drop (length ts, tys));
haftmann@20105
   329
    val (ts', t) = split_last (ts @ map Free abs);
haftmann@20105
   330
    val (tys', sty) = split_last tys;
haftmann@22051
   331
    fun dest_case ((c, tys_decl), ty) t =
haftmann@22051
   332
      let
haftmann@22051
   333
        val (vs, t') = Term.strip_abs_eta (length tys_decl) t;
haftmann@22051
   334
        val c' = list_comb (Const (c, map snd vs ---> sty), map Free vs);
haftmann@22051
   335
      in case t'
haftmann@22480
   336
       of Const ("HOL.undefined", _) => NONE
haftmann@22051
   337
        | _ => SOME (c', t')
haftmann@22051
   338
      end;
haftmann@22047
   339
  in (abs, ((t, sty), map2 dest_case (cs ~~ tys') ts' |> map_filter I)) 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@20835
   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@20835
   373
  val not_sym = thm "HOL.not_sym";
haftmann@20835
   374
  val not_false_true = iffD2 OF [nth (thms "HOL.simp_thms") 7, TrueI];
haftmann@21546
   375
  val refl = thm "refl";
haftmann@21546
   376
  val eqTrueI = thm "eqTrueI";
wenzelm@21516
   377
in
wenzelm@21516
   378
wenzelm@21516
   379
fun get_eq_datatype thy dtco =
haftmann@20835
   380
  let
haftmann@20835
   381
    val SOME (vs, cs) = DatatypePackage.get_datatype_spec thy dtco;
haftmann@20835
   382
    fun mk_triv_inject co =
haftmann@20835
   383
      let
haftmann@20835
   384
        val ct' = Thm.cterm_of thy
haftmann@20835
   385
          (Const (co, Type (dtco, map (fn (v, sort) => TVar ((v, 0), sort)) vs)))
haftmann@20835
   386
        val cty' = Thm.ctyp_of_term ct';
haftmann@20835
   387
        val SOME (ct, cty) = fold_aterms (fn Var (v, ty) =>
haftmann@20835
   388
          (K o SOME) (Thm.cterm_of thy (Var (v, Thm.typ_of cty')), Thm.ctyp_of thy ty) | _ => I)
haftmann@21546
   389
          (Thm.prop_of refl) NONE;
haftmann@21546
   390
      in eqTrueI OF [Thm.instantiate ([(cty, cty')], [(ct, ct')]) refl] end;
haftmann@20835
   391
    val inject1 = map_filter (fn (co, []) => SOME (mk_triv_inject co) | _ => NONE) cs
haftmann@20835
   392
    val inject2 = (#inject o DatatypePackage.the_datatype thy) dtco;
wenzelm@21516
   393
    val ctxt = ProofContext.init thy;
haftmann@20835
   394
    val simpset = Simplifier.context ctxt
haftmann@20835
   395
      (MetaSimplifier.empty_ss addsimprocs [distinct_simproc]);
haftmann@20835
   396
    val cos = map (fn (co, tys) =>
haftmann@20835
   397
        (Const (co, tys ---> Type (dtco, map TFree vs)), tys)) cs;
haftmann@20835
   398
    val tac = ALLGOALS (simp_tac simpset)
haftmann@20835
   399
      THEN ALLGOALS (ProofContext.fact_tac [not_false_true, TrueI]);
haftmann@20835
   400
    val distinct =
haftmann@20835
   401
      mk_distinct cos
haftmann@20835
   402
      |> map (fn t => Goal.prove_global thy [] [] t (K tac))
haftmann@20835
   403
      |> (fn thms => thms @ map (fn thm => not_sym OF [thm]) thms)
haftmann@20835
   404
  in inject1 @ inject2 @ distinct end;
wenzelm@21516
   405
wenzelm@21516
   406
end;
haftmann@19346
   407
haftmann@23811
   408
fun get_case_cert thy tyco =
haftmann@23811
   409
  let
haftmann@23811
   410
    val raw_thms =
haftmann@23811
   411
      (#case_rewrites o DatatypePackage.the_datatype thy) tyco;
haftmann@23811
   412
    val thms as hd_thm :: _ = raw_thms
haftmann@23811
   413
      |> Conjunction.intr_balanced
haftmann@23811
   414
      |> Drule.unvarify
haftmann@23811
   415
      |> Conjunction.elim_balanced (length raw_thms)
haftmann@23811
   416
      |> map Simpdata.mk_meta_eq
haftmann@23811
   417
      |> map Drule.zero_var_indexes
haftmann@23811
   418
    val params = fold_aterms (fn (Free (v, _)) => insert (op =) v
haftmann@23811
   419
      | _ => I) (Thm.prop_of hd_thm) [];
haftmann@23811
   420
    val rhs = hd_thm
haftmann@23811
   421
      |> Thm.prop_of
haftmann@23811
   422
      |> Logic.dest_equals
haftmann@23811
   423
      |> fst
haftmann@23811
   424
      |> Term.strip_comb
haftmann@23811
   425
      |> apsnd (fst o split_last)
haftmann@23811
   426
      |> list_comb;
haftmann@23811
   427
    val lhs = Free (Name.variant params "case", Term.fastype_of rhs);
haftmann@23811
   428
    val asm = (Thm.cterm_of thy o Logic.mk_equals) (lhs, rhs);
haftmann@23811
   429
  in
haftmann@23811
   430
    thms
haftmann@23811
   431
    |> Conjunction.intr_balanced
haftmann@23811
   432
    |> MetaSimplifier.rewrite_rule [(Thm.symmetric o Thm.assume) asm]
haftmann@23811
   433
    |> Thm.implies_intr asm
haftmann@23811
   434
    |> Thm.generalize ([], params) 0
haftmann@24845
   435
    |> Conv.fconv_rule (Class.unoverload thy)
haftmann@23811
   436
    |> Thm.varifyT
haftmann@23811
   437
  end;
haftmann@23811
   438
haftmann@19818
   439
haftmann@20426
   440
haftmann@20426
   441
(** codetypes for code 2nd generation **)
haftmann@20426
   442
haftmann@20835
   443
(* abstraction over datatypes vs. type copies *)
haftmann@20426
   444
haftmann@24626
   445
fun get_spec thy (dtco, true) =
haftmann@24626
   446
      (the o DatatypePackage.get_datatype_spec thy) dtco
haftmann@24626
   447
  | get_spec thy (tyco, false) =
haftmann@24626
   448
      TypecopyPackage.get_spec thy tyco;
haftmann@24626
   449
haftmann@20835
   450
local
haftmann@20835
   451
  fun get_eq_thms thy tyco = case DatatypePackage.get_datatype thy tyco
haftmann@20835
   452
   of SOME _ => get_eq_datatype thy tyco
haftmann@20835
   453
    | NONE => [TypecopyPackage.get_eq thy tyco];
haftmann@21546
   454
  fun constrain_op_eq_thms thy thms =
haftmann@21546
   455
    let
haftmann@21546
   456
      fun add_eq (Const ("op =", ty)) =
haftmann@23712
   457
            fold (insert (eq_fst (op =))) (Term.add_tvarsT ty [])
haftmann@21546
   458
        | add_eq _ =
haftmann@21546
   459
            I
haftmann@21546
   460
      val eqs = fold (fold_aterms add_eq o Thm.prop_of) thms [];
haftmann@21546
   461
      val instT = map (fn (v_i, sort) =>
haftmann@21546
   462
        (Thm.ctyp_of thy (TVar (v_i, sort)),
haftmann@23712
   463
           Thm.ctyp_of thy (TVar (v_i, Sorts.inter_sort (Sign.classes_of thy)
haftmann@23712
   464
             (sort, [HOLogic.class_eq]))))) eqs;
haftmann@21546
   465
    in
haftmann@21546
   466
      thms
haftmann@21546
   467
      |> map (Thm.instantiate (instT, []))
haftmann@21546
   468
    end;
haftmann@20835
   469
in
haftmann@20835
   470
  fun get_eq thy tyco =
haftmann@20835
   471
    get_eq_thms thy tyco
haftmann@20835
   472
    |> maps ((#mk o #mk_rews o snd o MetaSimplifier.rep_ss o Simplifier.simpset_of) thy)
haftmann@21546
   473
    |> constrain_op_eq_thms thy
haftmann@20835
   474
end;
haftmann@20835
   475
haftmann@20835
   476
type hook = (string * (bool * ((string * sort) list * (string * typ list) list))) list
haftmann@20835
   477
  -> theory -> theory;
haftmann@20426
   478
haftmann@24626
   479
fun add_codetypes_hook hook thy =
haftmann@20426
   480
  let
haftmann@20835
   481
    fun add_spec thy (tyco, is_dt) =
haftmann@20835
   482
      (tyco, (is_dt, get_spec thy (tyco, is_dt)));
haftmann@20426
   483
    fun datatype_hook dtcos thy =
haftmann@20426
   484
      hook (map (add_spec thy) (map (rpair true) dtcos)) thy;
haftmann@20835
   485
    fun typecopy_hook ((tyco, _)) thy =
haftmann@20835
   486
      hook ([(tyco, (false, TypecopyPackage.get_spec thy tyco))]) thy;
haftmann@20426
   487
  in
haftmann@20426
   488
    thy
wenzelm@24711
   489
    |> DatatypePackage.interpretation datatype_hook
wenzelm@24711
   490
    |> TypecopyPackage.interpretation typecopy_hook
haftmann@20426
   491
  end;
haftmann@20426
   492
haftmann@20426
   493
fun the_codetypes_mut_specs thy ([(tyco, is_dt)]) =
haftmann@20426
   494
      let
haftmann@20426
   495
        val (vs, cs) = get_spec thy (tyco, is_dt)
haftmann@20426
   496
      in (vs, [(tyco, (is_dt, cs))]) end
haftmann@20426
   497
  | the_codetypes_mut_specs thy (tycos' as (tyco, true) :: _) =
haftmann@20426
   498
      let
haftmann@20426
   499
        val tycos = map fst tycos';
haftmann@20426
   500
        val tycos'' = (map (#1 o snd) o #descr o DatatypePackage.the_datatype thy) tyco;
haftmann@20426
   501
        val _ = if gen_subset (op =) (tycos, tycos'') then () else
haftmann@22175
   502
          error ("type constructors are not mutually recursive: " ^ (commas o map quote) tycos);
haftmann@20426
   503
        val (vs::_, css) = split_list (map (the o DatatypePackage.get_datatype_spec thy) tycos);
haftmann@20426
   504
      in (vs, map2 (fn (tyco, is_dt) => fn cs => (tyco, (is_dt, cs))) tycos' css) end;
haftmann@20426
   505
haftmann@20835
   506
haftmann@20835
   507
(* registering code types in code generator *)
haftmann@20835
   508
haftmann@24423
   509
fun add_datatype_spec (tyco, (vs, cos)) thy =
haftmann@24423
   510
  let
haftmann@24423
   511
    val cs = map (fn (c, tys) => (c, tys ---> Type (tyco, map TFree vs))) cos;
haftmann@24423
   512
  in try (Code.add_datatype cs) thy |> the_default thy end;
haftmann@24423
   513
haftmann@24423
   514
val codetype_hook =
haftmann@24428
   515
  fold (fn (dtco, (_ : bool, spec)) => add_datatype_spec (dtco, spec));
haftmann@20835
   516
haftmann@20835
   517
haftmann@20835
   518
(* instrumentalizing the sort algebra *)
haftmann@20835
   519
haftmann@22423
   520
fun get_codetypes_arities thy tycos sort =
haftmann@22423
   521
  let
haftmann@22423
   522
    val pp = Sign.pp thy;
haftmann@22423
   523
    val algebra = Sign.classes_of thy;
haftmann@22423
   524
    val (vs_proto, css_proto) = the_codetypes_mut_specs thy tycos;
haftmann@22423
   525
    val vs = map (fn (v, vsort) => (v, Sorts.inter_sort algebra (vsort, sort))) vs_proto;
haftmann@22423
   526
    val css = map (fn (tyco, (_, cs)) => (tyco, cs)) css_proto;
haftmann@22423
   527
    val algebra' = algebra
haftmann@22423
   528
      |> fold (fn (tyco, _) =>
haftmann@22423
   529
           Sorts.add_arities pp (tyco, map (fn class => (class, map snd vs)) sort)) css;
haftmann@24219
   530
    fun typ_sort_inst ty = CodeUnit.typ_sort_inst algebra' (Logic.varifyT ty, sort);
haftmann@22423
   531
    val venv = Vartab.empty
haftmann@22423
   532
      |> fold (fn (v, sort) => Vartab.update_new ((v, 0), sort)) vs
haftmann@22423
   533
      |> fold (fn (_, cs) => fold (fn (_, tys) => fold typ_sort_inst tys) cs) css;
haftmann@22423
   534
    fun inst (v, _) = (v, (the o Vartab.lookup venv) (v, 0));
haftmann@22423
   535
    val vs' = map inst vs;
haftmann@22423
   536
    fun mk_arity tyco = (tyco, map snd vs', sort);
haftmann@22423
   537
    fun mk_cons tyco (c, tys) =
haftmann@22423
   538
      let
haftmann@22423
   539
        val tys' = (map o Term.map_type_tfree) (TFree o inst) tys;
haftmann@22423
   540
        val ts = Name.names Name.context "a" tys';
haftmann@22423
   541
        val ty = (tys' ---> Type (tyco, map TFree vs'));
haftmann@22423
   542
      in list_comb (Const (c, ty), map Free ts) end;
haftmann@22423
   543
  in
haftmann@24626
   544
    map (fn (tyco, cs) => (tyco, (mk_arity tyco, map (mk_cons tyco) cs))) css
haftmann@24626
   545
  end;
haftmann@20426
   546
haftmann@20597
   547
fun prove_codetypes_arities tac tycos sort f after_qed thy =
haftmann@24626
   548
  case try (get_codetypes_arities thy tycos) sort
haftmann@20426
   549
   of NONE => thy
haftmann@20426
   550
    | SOME insts => let
wenzelm@22331
   551
        fun proven (tyco, asorts, sort) =
haftmann@20426
   552
          Sorts.of_sort (Sign.classes_of thy)
haftmann@20426
   553
            (Type (tyco, map TFree (Name.names Name.context "'a" asorts)), sort);
haftmann@20426
   554
        val (arities, css) = (split_list o map_filter
haftmann@20426
   555
          (fn (tyco, (arity, cs)) => if proven arity
haftmann@20426
   556
            then NONE else SOME (arity, (tyco, cs)))) insts;
haftmann@20426
   557
      in
haftmann@20426
   558
        thy
wenzelm@21565
   559
        |> not (null arities) ? (
haftmann@20835
   560
            f arities css
haftmann@20835
   561
            #-> (fn defs =>
haftmann@24589
   562
              Class.prove_instance tac arities defs
haftmann@24423
   563
            #-> (fn defs =>
haftmann@24423
   564
              after_qed arities css defs)))
haftmann@20426
   565
      end;
haftmann@20426
   566
haftmann@20835
   567
haftmann@20835
   568
(* operational equality *)
haftmann@20835
   569
haftmann@21046
   570
fun eq_hook specs =
haftmann@20597
   571
  let
haftmann@20835
   572
    fun add_eq_thms (dtco, (_, (vs, cs))) thy =
haftmann@20597
   573
      let
wenzelm@24137
   574
        val thy_ref = Theory.check_thy thy;
haftmann@24423
   575
        val const = Class.inst_const thy ("op =", dtco);
haftmann@20835
   576
        val get_thms = (fn () => get_eq (Theory.deref thy_ref) dtco |> rev);
haftmann@20597
   577
      in
haftmann@24219
   578
        Code.add_funcl (const, Susp.delay get_thms) thy
haftmann@20597
   579
      end;
haftmann@20597
   580
  in
haftmann@24219
   581
    prove_codetypes_arities (Class.intro_classes_tac [])
haftmann@20835
   582
      (map (fn (tyco, (is_dt, _)) => (tyco, is_dt)) specs)
haftmann@24423
   583
      [HOLogic.class_eq] ((K o K o pair) []) ((K o K o K) (fold add_eq_thms specs))
haftmann@20597
   584
  end;
haftmann@20597
   585
haftmann@20426
   586
haftmann@20426
   587
haftmann@20426
   588
(** theory setup **)
haftmann@20426
   589
haftmann@23513
   590
fun add_datatype_case_defs dtco thy =
haftmann@23513
   591
  let
haftmann@23513
   592
    val {case_rewrites, ...} = DatatypePackage.the_datatype thy dtco
haftmann@23513
   593
  in
haftmann@24624
   594
    fold_rev Code.add_default_func case_rewrites thy
haftmann@23513
   595
  end;
haftmann@23513
   596
haftmann@24845
   597
fun add_datatype_case_certs dtco thy =
haftmann@24845
   598
  Code.add_case (get_case_cert thy dtco) thy;
haftmann@24845
   599
haftmann@19008
   600
val setup = 
haftmann@20597
   601
  add_codegen "datatype" datatype_codegen
haftmann@24626
   602
  #> add_tycodegen "datatype" datatype_tycodegen
haftmann@24845
   603
  #> DatatypePackage.interpretation (fold add_datatype_case_certs)
wenzelm@24711
   604
  #> DatatypePackage.interpretation (fold add_datatype_case_defs)
haftmann@24845
   605
  #> add_codetypes_hook codetype_hook
haftmann@24626
   606
  #> add_codetypes_hook eq_hook
haftmann@20597
   607
berghofe@12445
   608
end;