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