src/HOL/Tools/Datatype/datatype_codegen.ML
author haftmann
Wed May 05 18:25:34 2010 +0200 (2010-05-05 ago)
changeset 36692 54b64d4ad524
parent 36610 bafd82950e24
child 37425 b5492f611129
permissions -rw-r--r--
farewell to old-style mem infixes -- type inference in situations with mem_int and mem_string should provide enough information to resolve the type of (op =)
haftmann@33968
     1
(*  Title:      HOL/Tools/Datatype/datatype_codegen.ML
wenzelm@29265
     2
    Author:     Stefan Berghofer and Florian Haftmann, TU Muenchen
berghofe@12445
     3
haftmann@25534
     4
Code generator facilities for inductive datatypes.
berghofe@12445
     5
*)
berghofe@12445
     6
berghofe@12445
     7
signature DATATYPE_CODEGEN =
berghofe@12445
     8
sig
wenzelm@18708
     9
  val setup: theory -> theory
berghofe@12445
    10
end;
berghofe@12445
    11
haftmann@33968
    12
structure Datatype_Codegen : DATATYPE_CODEGEN =
berghofe@12445
    13
struct
berghofe@12445
    14
haftmann@36298
    15
(** generic code generator **)
haftmann@36298
    16
haftmann@36298
    17
(* liberal addition of code data for datatypes *)
haftmann@36298
    18
haftmann@36298
    19
fun mk_constr_consts thy vs dtco cos =
haftmann@36298
    20
  let
haftmann@36298
    21
    val cs = map (fn (c, tys) => (c, tys ---> Type (dtco, map TFree vs))) cos;
haftmann@36298
    22
    val cs' = map (fn c_ty as (_, ty) => (AxClass.unoverload_const thy c_ty, ty)) cs;
haftmann@36298
    23
  in if is_some (try (Code.constrset_of_consts thy) cs')
haftmann@36298
    24
    then SOME cs
haftmann@36298
    25
    else NONE
haftmann@36298
    26
  end;
haftmann@36298
    27
haftmann@36298
    28
haftmann@36298
    29
(* case certificates *)
haftmann@36298
    30
haftmann@36298
    31
fun mk_case_cert thy tyco =
haftmann@36298
    32
  let
haftmann@36298
    33
    val raw_thms =
haftmann@36298
    34
      (#case_rewrites o Datatype_Data.the_info thy) tyco;
haftmann@36298
    35
    val thms as hd_thm :: _ = raw_thms
haftmann@36298
    36
      |> Conjunction.intr_balanced
haftmann@36298
    37
      |> Thm.unvarify_global
haftmann@36298
    38
      |> Conjunction.elim_balanced (length raw_thms)
haftmann@36298
    39
      |> map Simpdata.mk_meta_eq
haftmann@36298
    40
      |> map Drule.zero_var_indexes
haftmann@36298
    41
    val params = fold_aterms (fn (Free (v, _)) => insert (op =) v
haftmann@36298
    42
      | _ => I) (Thm.prop_of hd_thm) [];
haftmann@36298
    43
    val rhs = hd_thm
haftmann@36298
    44
      |> Thm.prop_of
haftmann@36298
    45
      |> Logic.dest_equals
haftmann@36298
    46
      |> fst
haftmann@36298
    47
      |> Term.strip_comb
haftmann@36298
    48
      |> apsnd (fst o split_last)
haftmann@36298
    49
      |> list_comb;
haftmann@36298
    50
    val lhs = Free (Name.variant params "case", Term.fastype_of rhs);
haftmann@36298
    51
    val asm = (Thm.cterm_of thy o Logic.mk_equals) (lhs, rhs);
haftmann@36298
    52
  in
haftmann@36298
    53
    thms
haftmann@36298
    54
    |> Conjunction.intr_balanced
haftmann@36298
    55
    |> MetaSimplifier.rewrite_rule [(Thm.symmetric o Thm.assume) asm]
haftmann@36298
    56
    |> Thm.implies_intr asm
haftmann@36298
    57
    |> Thm.generalize ([], params) 0
haftmann@36298
    58
    |> AxClass.unoverload thy
haftmann@36298
    59
    |> Thm.varifyT_global
haftmann@36298
    60
  end;
haftmann@36298
    61
haftmann@36298
    62
haftmann@36298
    63
(* equality *)
haftmann@36298
    64
haftmann@36298
    65
fun mk_eq_eqns thy dtco =
haftmann@36298
    66
  let
haftmann@36298
    67
    val (vs, cos) = Datatype_Data.the_spec thy dtco;
haftmann@36298
    68
    val { descr, index, inject = inject_thms, distinct = distinct_thms, ... } =
haftmann@36298
    69
      Datatype_Data.the_info thy dtco;
haftmann@36298
    70
    val ty = Type (dtco, map TFree vs);
haftmann@36298
    71
    fun mk_eq (t1, t2) = Const (@{const_name eq_class.eq}, ty --> ty --> HOLogic.boolT)
haftmann@36298
    72
      $ t1 $ t2;
haftmann@36298
    73
    fun true_eq t12 = HOLogic.mk_eq (mk_eq t12, HOLogic.true_const);
haftmann@36298
    74
    fun false_eq t12 = HOLogic.mk_eq (mk_eq t12, HOLogic.false_const);
haftmann@36298
    75
    val triv_injects = map_filter
haftmann@36298
    76
     (fn (c, []) => SOME (HOLogic.mk_Trueprop (true_eq (Const (c, ty), Const (c, ty))))
haftmann@36298
    77
       | _ => NONE) cos;
haftmann@36298
    78
    fun prep_inject (trueprop $ (equiv $ (_ $ t1 $ t2) $ rhs)) =
haftmann@36298
    79
      trueprop $ (equiv $ mk_eq (t1, t2) $ rhs);
haftmann@36298
    80
    val injects = map prep_inject (nth (Datatype_Prop.make_injs [descr] vs) index);
haftmann@36298
    81
    fun prep_distinct (trueprop $ (not $ (_ $ t1 $ t2))) =
haftmann@36298
    82
      [trueprop $ false_eq (t1, t2), trueprop $ false_eq (t2, t1)];
haftmann@36298
    83
    val distincts = maps prep_distinct (snd (nth (Datatype_Prop.make_distincts [descr] vs) index));
haftmann@36298
    84
    val refl = HOLogic.mk_Trueprop (true_eq (Free ("x", ty), Free ("x", ty)));
haftmann@36298
    85
    val simpset = Simplifier.global_context thy (HOL_basic_ss addsimps 
haftmann@36298
    86
      (map Simpdata.mk_eq (@{thm eq} :: @{thm eq_True} :: inject_thms @ distinct_thms)));
haftmann@36298
    87
    fun prove prop = Skip_Proof.prove_global thy [] [] prop (K (ALLGOALS (simp_tac simpset)))
haftmann@36298
    88
      |> Simpdata.mk_eq;
haftmann@36298
    89
  in (map prove (triv_injects @ injects @ distincts), prove refl) end;
haftmann@36298
    90
haftmann@36298
    91
fun add_equality vs dtcos thy =
haftmann@36298
    92
  let
haftmann@36298
    93
    fun add_def dtco lthy =
haftmann@36298
    94
      let
haftmann@36298
    95
        val ty = Type (dtco, map TFree vs);
haftmann@36298
    96
        fun mk_side const_name = Const (const_name, ty --> ty --> HOLogic.boolT)
haftmann@36298
    97
          $ Free ("x", ty) $ Free ("y", ty);
haftmann@36298
    98
        val def = HOLogic.mk_Trueprop (HOLogic.mk_eq
haftmann@36298
    99
          (mk_side @{const_name eq_class.eq}, mk_side @{const_name "op ="}));
haftmann@36298
   100
        val def' = Syntax.check_term lthy def;
haftmann@36298
   101
        val ((_, (_, thm)), lthy') = Specification.definition
haftmann@36298
   102
          (NONE, (Attrib.empty_binding, def')) lthy;
wenzelm@36610
   103
        val ctxt_thy = ProofContext.init_global (ProofContext.theory_of lthy);
haftmann@36298
   104
        val thm' = singleton (ProofContext.export lthy' ctxt_thy) thm;
haftmann@36298
   105
      in (thm', lthy') end;
haftmann@36298
   106
    fun tac thms = Class.intro_classes_tac []
haftmann@36298
   107
      THEN ALLGOALS (ProofContext.fact_tac thms);
haftmann@36298
   108
    fun add_eq_thms dtco =
haftmann@36298
   109
      Theory.checkpoint
haftmann@36298
   110
      #> `(fn thy => mk_eq_eqns thy dtco)
haftmann@36298
   111
      #-> (fn (thms, thm) =>
haftmann@36298
   112
        Code.add_nbe_eqn thm
haftmann@36298
   113
        #> fold_rev Code.add_eqn thms);
haftmann@36298
   114
  in
haftmann@36298
   115
    thy
haftmann@36298
   116
    |> Theory_Target.instantiation (dtcos, vs, [HOLogic.class_eq])
haftmann@36298
   117
    |> fold_map add_def dtcos
haftmann@36298
   118
    |-> (fn def_thms => Class.prove_instantiation_exit_result (map o Morphism.thm)
haftmann@36298
   119
         (fn _ => fn def_thms => tac def_thms) def_thms)
haftmann@36298
   120
    |-> (fn def_thms => fold Code.del_eqn def_thms)
haftmann@36298
   121
    |> fold add_eq_thms dtcos
haftmann@36298
   122
  end;
haftmann@36298
   123
haftmann@36298
   124
haftmann@36298
   125
(* register a datatype etc. *)
haftmann@36298
   126
haftmann@36298
   127
fun add_all_code config dtcos thy =
haftmann@36298
   128
  let
haftmann@36298
   129
    val (vs :: _, coss) = (split_list o map (Datatype_Data.the_spec thy)) dtcos;
haftmann@36298
   130
    val any_css = map2 (mk_constr_consts thy vs) dtcos coss;
haftmann@36298
   131
    val css = if exists is_none any_css then []
haftmann@36298
   132
      else map_filter I any_css;
haftmann@36298
   133
    val case_rewrites = maps (#case_rewrites o Datatype_Data.the_info thy) dtcos;
haftmann@36298
   134
    val certs = map (mk_case_cert thy) dtcos;
haftmann@36298
   135
  in
haftmann@36298
   136
    if null css then thy
haftmann@36298
   137
    else thy
haftmann@36298
   138
      |> tap (fn _ => Datatype_Aux.message config "Registering datatype for code generator ...")
haftmann@36298
   139
      |> fold Code.add_datatype css
haftmann@36298
   140
      |> fold_rev Code.add_default_eqn case_rewrites
haftmann@36298
   141
      |> fold Code.add_case certs
haftmann@36298
   142
      |> add_equality vs dtcos
haftmann@36298
   143
   end;
haftmann@36298
   144
haftmann@36298
   145
haftmann@31625
   146
(** SML code generator **)
haftmann@31625
   147
haftmann@31625
   148
open Codegen;
haftmann@31625
   149
haftmann@31625
   150
(* datatype definition *)
haftmann@31625
   151
haftmann@33968
   152
fun add_dt_defs thy defs dep module descr sorts gr =
berghofe@12445
   153
  let
haftmann@33968
   154
    val descr' = filter (can (map Datatype_Aux.dest_DtTFree o #2 o snd)) descr;
wenzelm@33317
   155
    val rtnames = map (#1 o snd) (filter (fn (_, (_, _, cs)) =>
haftmann@33968
   156
      exists (exists Datatype_Aux.is_rec_type o snd) cs) descr');
berghofe@12445
   157
berghofe@17144
   158
    val (_, (tname, _, _)) :: _ = descr';
berghofe@17144
   159
    val node_id = tname ^ " (type)";
haftmann@27398
   160
    val module' = if_library (thyname_of_type thy tname) module;
berghofe@12445
   161
haftmann@28537
   162
    fun mk_dtdef prfx [] gr = ([], gr)
haftmann@28537
   163
      | mk_dtdef prfx ((_, (tname, dts, cs))::xs) gr =
berghofe@12445
   164
          let
haftmann@33968
   165
            val tvs = map Datatype_Aux.dest_DtTFree dts;
haftmann@33968
   166
            val cs' = map (apsnd (map (Datatype_Aux.typ_of_dtyp descr sorts))) cs;
haftmann@28537
   167
            val ((_, type_id), gr') = mk_type_id module' tname gr;
haftmann@28537
   168
            val (ps, gr'') = gr' |>
haftmann@28537
   169
              fold_map (fn (cname, cargs) =>
haftmann@28537
   170
                fold_map (invoke_tycodegen thy defs node_id module' false)
haftmann@28537
   171
                  cargs ##>>
haftmann@28537
   172
                mk_const_id module' cname) cs';
haftmann@28537
   173
            val (rest, gr''') = mk_dtdef "and " xs gr''
berghofe@12445
   174
          in
haftmann@28537
   175
            (Pretty.block (str prfx ::
berghofe@12445
   176
               (if null tvs then [] else
berghofe@26975
   177
                  [mk_tuple (map str tvs), str " "]) @
berghofe@26975
   178
               [str (type_id ^ " ="), Pretty.brk 1] @
wenzelm@32952
   179
               flat (separate [Pretty.brk 1, str "| "]
berghofe@17144
   180
                 (map (fn (ps', (_, cname)) => [Pretty.block
berghofe@26975
   181
                   (str cname ::
berghofe@12445
   182
                    (if null ps' then [] else
wenzelm@32952
   183
                     flat ([str " of", Pretty.brk 1] ::
berghofe@26975
   184
                       separate [str " *", Pretty.brk 1]
haftmann@28537
   185
                         (map single ps'))))]) ps))) :: rest, gr''')
berghofe@13754
   186
          end;
berghofe@13754
   187
berghofe@25889
   188
    fun mk_constr_term cname Ts T ps =
wenzelm@32952
   189
      flat (separate [str " $", Pretty.brk 1]
berghofe@26975
   190
        ([str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
berghofe@26975
   191
          mk_type false (Ts ---> T), str ")"] :: ps));
berghofe@25889
   192
berghofe@17144
   193
    fun mk_term_of_def gr prfx [] = []
berghofe@17144
   194
      | mk_term_of_def gr prfx ((_, (tname, dts, cs)) :: xs) =
berghofe@13754
   195
          let
haftmann@33968
   196
            val cs' = map (apsnd (map (Datatype_Aux.typ_of_dtyp descr sorts))) cs;
haftmann@33968
   197
            val dts' = map (Datatype_Aux.typ_of_dtyp descr sorts) dts;
berghofe@13754
   198
            val T = Type (tname, dts');
berghofe@17144
   199
            val rest = mk_term_of_def gr "and " xs;
haftmann@31458
   200
            val (eqs, _) = fold_map (fn (cname, Ts) => fn prfx =>
berghofe@13754
   201
              let val args = map (fn i =>
berghofe@26975
   202
                str ("x" ^ string_of_int i)) (1 upto length Ts)
haftmann@31458
   203
              in (Pretty.blk (4,
berghofe@26975
   204
                [str prfx, mk_term_of gr module' false T, Pretty.brk 1,
haftmann@28537
   205
                 if null Ts then str (snd (get_const_id gr cname))
berghofe@16645
   206
                 else parens (Pretty.block
haftmann@28537
   207
                   [str (snd (get_const_id gr cname)),
berghofe@13754
   208
                    Pretty.brk 1, mk_tuple args]),
berghofe@26975
   209
                 str " =", Pretty.brk 1] @
berghofe@25889
   210
                 mk_constr_term cname Ts T
haftmann@31458
   211
                   (map2 (fn x => fn U => [Pretty.block [mk_term_of gr module' false U,
haftmann@31458
   212
                      Pretty.brk 1, x]]) args Ts)), "  | ")
haftmann@31458
   213
              end) cs' prfx
berghofe@14104
   214
          in eqs @ rest end;
berghofe@14104
   215
berghofe@17144
   216
    fun mk_gen_of_def gr prfx [] = []
berghofe@17144
   217
      | mk_gen_of_def gr prfx ((i, (tname, dts, cs)) :: xs) =
berghofe@14104
   218
          let
haftmann@33968
   219
            val tvs = map Datatype_Aux.dest_DtTFree dts;
haftmann@33968
   220
            val Us = map (Datatype_Aux.typ_of_dtyp descr sorts) dts;
berghofe@25889
   221
            val T = Type (tname, Us);
berghofe@14104
   222
            val (cs1, cs2) =
haftmann@33968
   223
              List.partition (exists Datatype_Aux.is_rec_type o snd) cs;
haftmann@33968
   224
            val SOME (cname, _) = Datatype_Aux.find_shortest_path descr i;
berghofe@14104
   225
berghofe@14104
   226
            fun mk_delay p = Pretty.block
berghofe@26975
   227
              [str "fn () =>", Pretty.brk 1, p];
berghofe@14104
   228
berghofe@26975
   229
            fun mk_force p = Pretty.block [p, Pretty.brk 1, str "()"];
berghofe@25889
   230
berghofe@15397
   231
            fun mk_constr s b (cname, dts) =
berghofe@14104
   232
              let
berghofe@17144
   233
                val gs = map (fn dt => mk_app false (mk_gen gr module' false rtnames s
haftmann@33968
   234
                    (Datatype_Aux.typ_of_dtyp descr sorts dt))
haftmann@33968
   235
                  [str (if b andalso Datatype_Aux.is_rec_type dt then "0"
berghofe@15397
   236
                     else "j")]) dts;
haftmann@33968
   237
                val Ts = map (Datatype_Aux.typ_of_dtyp descr sorts) dts;
berghofe@26975
   238
                val xs = map str
haftmann@33968
   239
                  (Datatype_Prop.indexify_names (replicate (length dts) "x"));
berghofe@26975
   240
                val ts = map str
haftmann@33968
   241
                  (Datatype_Prop.indexify_names (replicate (length dts) "t"));
haftmann@28537
   242
                val (_, id) = get_const_id gr cname
berghofe@25889
   243
              in
berghofe@25889
   244
                mk_let
berghofe@25889
   245
                  (map2 (fn p => fn q => mk_tuple [p, q]) xs ts ~~ gs)
berghofe@25889
   246
                  (mk_tuple
berghofe@25889
   247
                    [case xs of
berghofe@25889
   248
                       _ :: _ :: _ => Pretty.block
berghofe@26975
   249
                         [str id, Pretty.brk 1, mk_tuple xs]
berghofe@26975
   250
                     | _ => mk_app false (str id) xs,
berghofe@25889
   251
                     mk_delay (Pretty.block (mk_constr_term cname Ts T
berghofe@25889
   252
                       (map (single o mk_force) ts)))])
berghofe@14104
   253
              end;
berghofe@14104
   254
berghofe@15397
   255
            fun mk_choice [c] = mk_constr "(i-1)" false c
berghofe@26975
   256
              | mk_choice cs = Pretty.block [str "one_of",
berghofe@26975
   257
                  Pretty.brk 1, Pretty.blk (1, str "[" ::
wenzelm@32952
   258
                  flat (separate [str ",", Pretty.fbrk]
berghofe@15397
   259
                    (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
berghofe@26975
   260
                  [str "]"]), Pretty.brk 1, str "()"];
berghofe@14104
   261
berghofe@25889
   262
            val gs = maps (fn s =>
berghofe@25889
   263
              let val s' = strip_tname s
berghofe@26975
   264
              in [str (s' ^ "G"), str (s' ^ "T")] end) tvs;
haftmann@28537
   265
            val gen_name = "gen_" ^ snd (get_type_id gr tname)
berghofe@14104
   266
berghofe@14104
   267
          in
berghofe@14104
   268
            Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@26975
   269
                (str (prfx ^ gen_name ^
berghofe@14104
   270
                   (if null cs1 then "" else "'")) :: gs @
berghofe@26975
   271
                 (if null cs1 then [] else [str "i"]) @
berghofe@26975
   272
                 [str "j"]) @
berghofe@26975
   273
              [str " =", Pretty.brk 1] @
berghofe@14104
   274
              (if not (null cs1) andalso not (null cs2)
berghofe@26975
   275
               then [str "frequency", Pretty.brk 1,
berghofe@26975
   276
                 Pretty.blk (1, [str "[",
berghofe@26975
   277
                   mk_tuple [str "i", mk_delay (mk_choice cs1)],
berghofe@26975
   278
                   str ",", Pretty.fbrk,
berghofe@26975
   279
                   mk_tuple [str "1", mk_delay (mk_choice cs2)],
berghofe@26975
   280
                   str "]"]), Pretty.brk 1, str "()"]
berghofe@14104
   281
               else if null cs2 then
berghofe@26975
   282
                 [Pretty.block [str "(case", Pretty.brk 1,
berghofe@26975
   283
                   str "i", Pretty.brk 1, str "of",
berghofe@26975
   284
                   Pretty.brk 1, str "0 =>", Pretty.brk 1,
wenzelm@33035
   285
                   mk_constr "0" true (cname, the (AList.lookup (op =) cs cname)),
berghofe@26975
   286
                   Pretty.brk 1, str "| _ =>", Pretty.brk 1,
berghofe@26975
   287
                   mk_choice cs1, str ")"]]
berghofe@14104
   288
               else [mk_choice cs2])) ::
berghofe@14104
   289
            (if null cs1 then []
berghofe@14104
   290
             else [Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@26975
   291
                 (str ("and " ^ gen_name) :: gs @ [str "i"]) @
berghofe@26975
   292
               [str " =", Pretty.brk 1] @
berghofe@26975
   293
               separate (Pretty.brk 1) (str (gen_name ^ "'") :: gs @
berghofe@26975
   294
                 [str "i", str "i"]))]) @
berghofe@17144
   295
            mk_gen_of_def gr "and " xs
berghofe@14104
   296
          end
berghofe@13754
   297
berghofe@12445
   298
  in
haftmann@28537
   299
    (module', (add_edge_acyclic (node_id, dep) gr
berghofe@12445
   300
        handle Graph.CYCLES _ => gr) handle Graph.UNDEF _ =>
berghofe@12445
   301
         let
berghofe@17144
   302
           val gr1 = add_edge (node_id, dep)
berghofe@17144
   303
             (new_node (node_id, (NONE, "", "")) gr);
haftmann@28537
   304
           val (dtdef, gr2) = mk_dtdef "datatype " descr' gr1 ;
berghofe@12445
   305
         in
berghofe@17144
   306
           map_node node_id (K (NONE, module',
berghofe@26975
   307
             string_of (Pretty.blk (0, separate Pretty.fbrk dtdef @
berghofe@26975
   308
               [str ";"])) ^ "\n\n" ^
haftmann@36692
   309
             (if member (op =) (!mode) "term_of" then
berghofe@26975
   310
                string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@26975
   311
                  (mk_term_of_def gr2 "fun " descr') @ [str ";"])) ^ "\n\n"
berghofe@14104
   312
              else "") ^
haftmann@36692
   313
             (if member (op =) (!mode) "test" then
berghofe@26975
   314
                string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@26975
   315
                  (mk_gen_of_def gr2 "fun " descr') @ [str ";"])) ^ "\n\n"
berghofe@13754
   316
              else ""))) gr2
haftmann@28537
   317
         end)
berghofe@12445
   318
  end;
berghofe@12445
   319
berghofe@12445
   320
haftmann@31625
   321
(* case expressions *)
berghofe@12445
   322
haftmann@28537
   323
fun pretty_case thy defs dep module brack constrs (c as Const (_, T)) ts gr =
berghofe@12445
   324
  let val i = length constrs
berghofe@12445
   325
  in if length ts <= i then
haftmann@28537
   326
       invoke_codegen thy defs dep module brack (eta_expand c ts (i+1)) gr
berghofe@12445
   327
    else
berghofe@12445
   328
      let
haftmann@33957
   329
        val ts1 = take i ts;
haftmann@33957
   330
        val t :: ts2 = drop i ts;
wenzelm@30190
   331
        val names = List.foldr OldTerm.add_term_names
wenzelm@30190
   332
          (map (fst o fst o dest_Var) (List.foldr OldTerm.add_term_vars [] ts1)) ts1;
haftmann@33957
   333
        val (Ts, dT) = split_last (take (i+1) (fst (strip_type T)));
berghofe@12445
   334
haftmann@28537
   335
        fun pcase [] [] [] gr = ([], gr)
haftmann@28537
   336
          | pcase ((cname, cargs)::cs) (t::ts) (U::Us) gr =
berghofe@12445
   337
              let
berghofe@12445
   338
                val j = length cargs;
wenzelm@20071
   339
                val xs = Name.variant_list names (replicate j "x");
haftmann@33957
   340
                val Us' = take j (fst (strip_type U));
haftmann@33957
   341
                val frees = map2 (curry Free) xs Us';
haftmann@28537
   342
                val (cp, gr0) = invoke_codegen thy defs dep module false
haftmann@28537
   343
                  (list_comb (Const (cname, Us' ---> dT), frees)) gr;
berghofe@12445
   344
                val t' = Envir.beta_norm (list_comb (t, frees));
haftmann@28537
   345
                val (p, gr1) = invoke_codegen thy defs dep module false t' gr0;
haftmann@28537
   346
                val (ps, gr2) = pcase cs ts Us gr1;
berghofe@12445
   347
              in
berghofe@26975
   348
                ([Pretty.block [cp, str " =>", Pretty.brk 1, p]] :: ps, gr2)
berghofe@12445
   349
              end;
berghofe@12445
   350
haftmann@28537
   351
        val (ps1, gr1) = pcase constrs ts1 Ts gr ;
wenzelm@32952
   352
        val ps = flat (separate [Pretty.brk 1, str "| "] ps1);
haftmann@28537
   353
        val (p, gr2) = invoke_codegen thy defs dep module false t gr1;
haftmann@28537
   354
        val (ps2, gr3) = fold_map (invoke_codegen thy defs dep module true) ts2 gr2;
haftmann@28537
   355
      in ((if not (null ts2) andalso brack then parens else I)
berghofe@12445
   356
        (Pretty.block (separate (Pretty.brk 1)
berghofe@26975
   357
          (Pretty.block ([str "(case ", p, str " of",
haftmann@28537
   358
             Pretty.brk 1] @ ps @ [str ")"]) :: ps2))), gr3)
berghofe@12445
   359
      end
berghofe@12445
   360
  end;
berghofe@12445
   361
berghofe@12445
   362
haftmann@31625
   363
(* constructors *)
berghofe@12445
   364
haftmann@28537
   365
fun pretty_constr thy defs dep module brack args (c as Const (s, T)) ts gr =
berghofe@12445
   366
  let val i = length args
berghofe@12445
   367
  in if i > 1 andalso length ts < i then
haftmann@28537
   368
      invoke_codegen thy defs dep module brack (eta_expand c ts i) gr
berghofe@12445
   369
     else
berghofe@12445
   370
       let
haftmann@28537
   371
         val id = mk_qual_id module (get_const_id gr s);
haftmann@28537
   372
         val (ps, gr') = fold_map
haftmann@28537
   373
           (invoke_codegen thy defs dep module (i = 1)) ts gr;
berghofe@12445
   374
       in (case args of
haftmann@28537
   375
          _ :: _ :: _ => (if brack then parens else I)
haftmann@28537
   376
            (Pretty.block [str id, Pretty.brk 1, mk_tuple ps])
haftmann@28537
   377
        | _ => (mk_app brack (str id) ps), gr')
berghofe@12445
   378
       end
berghofe@12445
   379
  end;
berghofe@12445
   380
berghofe@12445
   381
haftmann@31625
   382
(* code generators for terms and types *)
berghofe@12445
   383
haftmann@28537
   384
fun datatype_codegen thy defs dep module brack t gr = (case strip_comb t of
berghofe@12445
   385
   (c as Const (s, T), ts) =>
haftmann@33964
   386
     (case Datatype_Data.info_of_case thy s of
berghofe@22778
   387
        SOME {index, descr, ...} =>
haftmann@22921
   388
          if is_some (get_assoc_code thy (s, T)) then NONE else
haftmann@28537
   389
          SOME (pretty_case thy defs dep module brack
haftmann@28537
   390
            (#3 (the (AList.lookup op = descr index))) c ts gr )
haftmann@33964
   391
      | NONE => case (Datatype_Data.info_of_constr thy (s, T), strip_type T) of
berghofe@28639
   392
        (SOME {index, descr, ...}, (_, U as Type (tyname, _))) =>
haftmann@22921
   393
          if is_some (get_assoc_code thy (s, T)) then NONE else
berghofe@28639
   394
          let
berghofe@28639
   395
            val SOME (tyname', _, constrs) = AList.lookup op = descr index;
berghofe@28639
   396
            val SOME args = AList.lookup op = constrs s
berghofe@22778
   397
          in
berghofe@28639
   398
            if tyname <> tyname' then NONE
berghofe@28639
   399
            else SOME (pretty_constr thy defs
haftmann@28537
   400
              dep module brack args c ts (snd (invoke_tycodegen thy defs dep module false U gr)))
berghofe@22778
   401
          end
berghofe@22778
   402
      | _ => NONE)
berghofe@22778
   403
 | _ => NONE);
berghofe@12445
   404
haftmann@28537
   405
fun datatype_tycodegen thy defs dep module brack (Type (s, Ts)) gr =
haftmann@33964
   406
      (case Datatype_Data.get_info thy s of
skalberg@15531
   407
         NONE => NONE
berghofe@25889
   408
       | SOME {descr, sorts, ...} =>
haftmann@22921
   409
           if is_some (get_assoc_type thy s) then NONE else
berghofe@16645
   410
           let
haftmann@28537
   411
             val (ps, gr') = fold_map
haftmann@28537
   412
               (invoke_tycodegen thy defs dep module false) Ts gr;
haftmann@28537
   413
             val (module', gr'') = add_dt_defs thy defs dep module descr sorts gr' ;
haftmann@28537
   414
             val (tyid, gr''') = mk_type_id module' s gr''
haftmann@28537
   415
           in SOME (Pretty.block ((if null Ts then [] else
berghofe@26975
   416
               [mk_tuple ps, str " "]) @
haftmann@28537
   417
               [str (mk_qual_id module tyid)]), gr''')
berghofe@12445
   418
           end)
berghofe@16645
   419
  | datatype_tycodegen _ _ _ _ _ _ _ = NONE;
berghofe@12445
   420
haftmann@18247
   421
haftmann@20426
   422
(** theory setup **)
haftmann@20426
   423
haftmann@19008
   424
val setup = 
haftmann@36298
   425
  Datatype_Data.interpretation add_all_code
haftmann@36298
   426
  #> add_codegen "datatype" datatype_codegen
haftmann@36298
   427
  #> add_tycodegen "datatype" datatype_tycodegen;
haftmann@20597
   428
berghofe@12445
   429
end;