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