src/HOL/Tools/Datatype/datatype_codegen.ML
author wenzelm
Tue Apr 19 23:57:28 2011 +0200 (2011-04-19)
changeset 42411 ff997038e8eb
parent 42361 23f352990944
child 43324 2b47822868e4
permissions -rw-r--r--
eliminated Codegen.mode in favour of explicit argument;
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@38538
    19
fun mk_constr_consts thy vs tyco cos =
haftmann@36298
    20
  let
haftmann@38538
    21
    val cs = map (fn (c, tys) => (c, tys ---> Type (tyco, 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
wenzelm@41228
    55
    |> Raw_Simplifier.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@38538
    65
fun mk_eq_eqns thy tyco =
haftmann@36298
    66
  let
haftmann@38538
    67
    val (vs, cos) = Datatype_Data.the_spec thy tyco;
haftmann@36298
    68
    val { descr, index, inject = inject_thms, distinct = distinct_thms, ... } =
haftmann@38538
    69
      Datatype_Data.the_info thy tyco;
haftmann@38538
    70
    val ty = Type (tyco, map TFree vs);
haftmann@38857
    71
    fun mk_eq (t1, t2) = Const (@{const_name HOL.equal}, 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@38857
    86
      (map Simpdata.mk_eq (@{thm equal} :: @{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@38538
    91
fun add_equality vs tycos thy =
haftmann@36298
    92
  let
haftmann@38538
    93
    fun add_def tyco lthy =
haftmann@36298
    94
      let
haftmann@38538
    95
        val ty = Type (tyco, 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@38864
    99
          (mk_side @{const_name HOL.equal}, mk_side @{const_name HOL.eq}));
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@42361
   103
        val ctxt_thy = Proof_Context.init_global (Proof_Context.theory_of lthy);
wenzelm@42361
   104
        val thm' = singleton (Proof_Context.export lthy' ctxt_thy) thm;
haftmann@36298
   105
      in (thm', lthy') end;
haftmann@36298
   106
    fun tac thms = Class.intro_classes_tac []
wenzelm@42361
   107
      THEN ALLGOALS (Proof_Context.fact_tac thms);
haftmann@38538
   108
    fun prefix tyco = Binding.qualify true (Long_Name.base_name tyco) o Binding.qualify true "eq" o Binding.name;
haftmann@38538
   109
    fun add_eq_thms tyco =
haftmann@36298
   110
      Theory.checkpoint
haftmann@38538
   111
      #> `(fn thy => mk_eq_eqns thy tyco)
wenzelm@39557
   112
      #-> (fn (thms, thm) => Global_Theory.note_thmss Thm.lemmaK
haftmann@38538
   113
          [((prefix tyco "refl", [Code.add_nbe_default_eqn_attribute]), [([thm], [])]),
haftmann@38538
   114
            ((prefix tyco "simps", [Code.add_default_eqn_attribute]), [(rev thms, [])])])
haftmann@37425
   115
      #> snd
haftmann@36298
   116
  in
haftmann@36298
   117
    thy
haftmann@38857
   118
    |> Class.instantiation (tycos, vs, [HOLogic.class_equal])
haftmann@38538
   119
    |> fold_map add_def tycos
haftmann@36298
   120
    |-> (fn def_thms => Class.prove_instantiation_exit_result (map o Morphism.thm)
haftmann@36298
   121
         (fn _ => fn def_thms => tac def_thms) def_thms)
haftmann@36298
   122
    |-> (fn def_thms => fold Code.del_eqn def_thms)
haftmann@38538
   123
    |> fold add_eq_thms tycos
haftmann@36298
   124
  end;
haftmann@36298
   125
haftmann@36298
   126
haftmann@36298
   127
(* register a datatype etc. *)
haftmann@36298
   128
haftmann@38538
   129
fun add_all_code config tycos thy =
haftmann@36298
   130
  let
haftmann@38538
   131
    val (vs :: _, coss) = (split_list o map (Datatype_Data.the_spec thy)) tycos;
haftmann@38538
   132
    val any_css = map2 (mk_constr_consts thy vs) tycos coss;
haftmann@36298
   133
    val css = if exists is_none any_css then []
haftmann@36298
   134
      else map_filter I any_css;
haftmann@38538
   135
    val case_rewrites = maps (#case_rewrites o Datatype_Data.the_info thy) tycos;
haftmann@38538
   136
    val certs = map (mk_case_cert thy) tycos;
haftmann@38538
   137
    val tycos_eq = filter_out
haftmann@38857
   138
      (fn tyco => can (Sorts.mg_domain (Sign.classes_of thy) tyco) [HOLogic.class_equal]) tycos;
haftmann@36298
   139
  in
haftmann@36298
   140
    if null css then thy
haftmann@36298
   141
    else thy
haftmann@36298
   142
      |> tap (fn _ => Datatype_Aux.message config "Registering datatype for code generator ...")
haftmann@36298
   143
      |> fold Code.add_datatype css
haftmann@36298
   144
      |> fold_rev Code.add_default_eqn case_rewrites
haftmann@36298
   145
      |> fold Code.add_case certs
haftmann@38538
   146
      |> not (null tycos_eq) ? add_equality vs tycos_eq
haftmann@36298
   147
   end;
haftmann@36298
   148
haftmann@36298
   149
haftmann@31625
   150
(** SML code generator **)
haftmann@31625
   151
haftmann@31625
   152
(* datatype definition *)
haftmann@31625
   153
wenzelm@42411
   154
fun add_dt_defs thy mode defs dep module descr sorts gr =
berghofe@12445
   155
  let
haftmann@33968
   156
    val descr' = filter (can (map Datatype_Aux.dest_DtTFree o #2 o snd)) descr;
wenzelm@33317
   157
    val rtnames = map (#1 o snd) (filter (fn (_, (_, _, cs)) =>
haftmann@33968
   158
      exists (exists Datatype_Aux.is_rec_type o snd) cs) descr');
berghofe@12445
   159
berghofe@17144
   160
    val (_, (tname, _, _)) :: _ = descr';
berghofe@17144
   161
    val node_id = tname ^ " (type)";
wenzelm@42411
   162
    val module' = Codegen.if_library mode (Codegen.thyname_of_type thy tname) module;
berghofe@12445
   163
haftmann@28537
   164
    fun mk_dtdef prfx [] gr = ([], gr)
haftmann@28537
   165
      | mk_dtdef prfx ((_, (tname, dts, cs))::xs) gr =
berghofe@12445
   166
          let
haftmann@33968
   167
            val tvs = map Datatype_Aux.dest_DtTFree dts;
haftmann@33968
   168
            val cs' = map (apsnd (map (Datatype_Aux.typ_of_dtyp descr sorts))) cs;
wenzelm@41424
   169
            val ((_, type_id), gr') = Codegen.mk_type_id module' tname gr;
haftmann@28537
   170
            val (ps, gr'') = gr' |>
haftmann@28537
   171
              fold_map (fn (cname, cargs) =>
wenzelm@42411
   172
                fold_map (Codegen.invoke_tycodegen thy mode defs node_id module' false)
haftmann@28537
   173
                  cargs ##>>
wenzelm@41424
   174
                Codegen.mk_const_id module' cname) cs';
haftmann@28537
   175
            val (rest, gr''') = mk_dtdef "and " xs gr''
berghofe@12445
   176
          in
wenzelm@41424
   177
            (Pretty.block (Codegen.str prfx ::
berghofe@12445
   178
               (if null tvs then [] else
wenzelm@41424
   179
                  [Codegen.mk_tuple (map Codegen.str tvs), Codegen.str " "]) @
wenzelm@41424
   180
               [Codegen.str (type_id ^ " ="), Pretty.brk 1] @
wenzelm@41424
   181
               flat (separate [Pretty.brk 1, Codegen.str "| "]
berghofe@17144
   182
                 (map (fn (ps', (_, cname)) => [Pretty.block
wenzelm@41424
   183
                   (Codegen.str cname ::
berghofe@12445
   184
                    (if null ps' then [] else
wenzelm@41424
   185
                     flat ([Codegen.str " of", Pretty.brk 1] ::
wenzelm@41424
   186
                       separate [Codegen.str " *", Pretty.brk 1]
haftmann@28537
   187
                         (map single ps'))))]) ps))) :: rest, gr''')
berghofe@13754
   188
          end;
berghofe@13754
   189
berghofe@25889
   190
    fun mk_constr_term cname Ts T ps =
wenzelm@41424
   191
      flat (separate [Codegen.str " $", Pretty.brk 1]
wenzelm@41424
   192
        ([Codegen.str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
wenzelm@41424
   193
          Codegen.mk_type false (Ts ---> T), Codegen.str ")"] :: ps));
berghofe@25889
   194
berghofe@17144
   195
    fun mk_term_of_def gr prfx [] = []
berghofe@17144
   196
      | mk_term_of_def gr prfx ((_, (tname, dts, cs)) :: xs) =
berghofe@13754
   197
          let
haftmann@33968
   198
            val cs' = map (apsnd (map (Datatype_Aux.typ_of_dtyp descr sorts))) cs;
haftmann@33968
   199
            val dts' = map (Datatype_Aux.typ_of_dtyp descr sorts) dts;
berghofe@13754
   200
            val T = Type (tname, dts');
berghofe@17144
   201
            val rest = mk_term_of_def gr "and " xs;
haftmann@31458
   202
            val (eqs, _) = fold_map (fn (cname, Ts) => fn prfx =>
berghofe@13754
   203
              let val args = map (fn i =>
wenzelm@41424
   204
                Codegen.str ("x" ^ string_of_int i)) (1 upto length Ts)
haftmann@31458
   205
              in (Pretty.blk (4,
wenzelm@41424
   206
                [Codegen.str prfx, Codegen.mk_term_of gr module' false T, Pretty.brk 1,
wenzelm@41424
   207
                 if null Ts then Codegen.str (snd (Codegen.get_const_id gr cname))
wenzelm@41424
   208
                 else Codegen.parens (Pretty.block
wenzelm@41424
   209
                   [Codegen.str (snd (Codegen.get_const_id gr cname)),
wenzelm@41424
   210
                    Pretty.brk 1, Codegen.mk_tuple args]),
wenzelm@41424
   211
                 Codegen.str " =", Pretty.brk 1] @
berghofe@25889
   212
                 mk_constr_term cname Ts T
wenzelm@41424
   213
                   (map2 (fn x => fn U => [Pretty.block [Codegen.mk_term_of gr module' false U,
haftmann@31458
   214
                      Pretty.brk 1, x]]) args Ts)), "  | ")
haftmann@31458
   215
              end) cs' prfx
berghofe@14104
   216
          in eqs @ rest end;
berghofe@14104
   217
berghofe@17144
   218
    fun mk_gen_of_def gr prfx [] = []
berghofe@17144
   219
      | mk_gen_of_def gr prfx ((i, (tname, dts, cs)) :: xs) =
berghofe@14104
   220
          let
haftmann@33968
   221
            val tvs = map Datatype_Aux.dest_DtTFree dts;
haftmann@33968
   222
            val Us = map (Datatype_Aux.typ_of_dtyp descr sorts) dts;
berghofe@25889
   223
            val T = Type (tname, Us);
berghofe@14104
   224
            val (cs1, cs2) =
haftmann@33968
   225
              List.partition (exists Datatype_Aux.is_rec_type o snd) cs;
haftmann@33968
   226
            val SOME (cname, _) = Datatype_Aux.find_shortest_path descr i;
berghofe@14104
   227
berghofe@14104
   228
            fun mk_delay p = Pretty.block
wenzelm@41424
   229
              [Codegen.str "fn () =>", Pretty.brk 1, p];
berghofe@14104
   230
wenzelm@41424
   231
            fun mk_force p = Pretty.block [p, Pretty.brk 1, Codegen.str "()"];
berghofe@25889
   232
berghofe@15397
   233
            fun mk_constr s b (cname, dts) =
berghofe@14104
   234
              let
wenzelm@41424
   235
                val gs = map (fn dt => Codegen.mk_app false
wenzelm@41424
   236
                    (Codegen.mk_gen gr module' false rtnames s
wenzelm@41424
   237
                      (Datatype_Aux.typ_of_dtyp descr sorts dt))
wenzelm@41424
   238
                  [Codegen.str (if b andalso Datatype_Aux.is_rec_type dt then "0"
berghofe@15397
   239
                     else "j")]) dts;
haftmann@33968
   240
                val Ts = map (Datatype_Aux.typ_of_dtyp descr sorts) dts;
wenzelm@41424
   241
                val xs = map Codegen.str
haftmann@33968
   242
                  (Datatype_Prop.indexify_names (replicate (length dts) "x"));
wenzelm@41424
   243
                val ts = map Codegen.str
haftmann@33968
   244
                  (Datatype_Prop.indexify_names (replicate (length dts) "t"));
wenzelm@41424
   245
                val (_, id) = Codegen.get_const_id gr cname;
berghofe@25889
   246
              in
wenzelm@41424
   247
                Codegen.mk_let
wenzelm@41424
   248
                  (map2 (fn p => fn q => Codegen.mk_tuple [p, q]) xs ts ~~ gs)
wenzelm@41424
   249
                  (Codegen.mk_tuple
berghofe@25889
   250
                    [case xs of
berghofe@25889
   251
                       _ :: _ :: _ => Pretty.block
wenzelm@41424
   252
                         [Codegen.str id, Pretty.brk 1, Codegen.mk_tuple xs]
wenzelm@41424
   253
                     | _ => Codegen.mk_app false (Codegen.str id) xs,
berghofe@25889
   254
                     mk_delay (Pretty.block (mk_constr_term cname Ts T
berghofe@25889
   255
                       (map (single o mk_force) ts)))])
berghofe@14104
   256
              end;
berghofe@14104
   257
berghofe@15397
   258
            fun mk_choice [c] = mk_constr "(i-1)" false c
wenzelm@41424
   259
              | mk_choice cs = Pretty.block [Codegen.str "one_of",
wenzelm@41424
   260
                  Pretty.brk 1, Pretty.blk (1, Codegen.str "[" ::
wenzelm@41424
   261
                  flat (separate [Codegen.str ",", Pretty.fbrk]
berghofe@15397
   262
                    (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
wenzelm@41424
   263
                  [Codegen.str "]"]), Pretty.brk 1, Codegen.str "()"];
berghofe@14104
   264
berghofe@25889
   265
            val gs = maps (fn s =>
wenzelm@41424
   266
              let val s' = Codegen.strip_tname s
wenzelm@41424
   267
              in [Codegen.str (s' ^ "G"), Codegen.str (s' ^ "T")] end) tvs;
wenzelm@41424
   268
            val gen_name = "gen_" ^ snd (Codegen.get_type_id gr tname)
berghofe@14104
   269
berghofe@14104
   270
          in
berghofe@14104
   271
            Pretty.blk (4, separate (Pretty.brk 1) 
wenzelm@41424
   272
                (Codegen.str (prfx ^ gen_name ^
berghofe@14104
   273
                   (if null cs1 then "" else "'")) :: gs @
wenzelm@41424
   274
                 (if null cs1 then [] else [Codegen.str "i"]) @
wenzelm@41424
   275
                 [Codegen.str "j"]) @
wenzelm@41424
   276
              [Codegen.str " =", Pretty.brk 1] @
berghofe@14104
   277
              (if not (null cs1) andalso not (null cs2)
wenzelm@41424
   278
               then [Codegen.str "frequency", Pretty.brk 1,
wenzelm@41424
   279
                 Pretty.blk (1, [Codegen.str "[",
wenzelm@41424
   280
                   Codegen.mk_tuple [Codegen.str "i", mk_delay (mk_choice cs1)],
wenzelm@41424
   281
                   Codegen.str ",", Pretty.fbrk,
wenzelm@41424
   282
                   Codegen.mk_tuple [Codegen.str "1", mk_delay (mk_choice cs2)],
wenzelm@41424
   283
                   Codegen.str "]"]), Pretty.brk 1, Codegen.str "()"]
berghofe@14104
   284
               else if null cs2 then
wenzelm@41424
   285
                 [Pretty.block [Codegen.str "(case", Pretty.brk 1,
wenzelm@41424
   286
                   Codegen.str "i", Pretty.brk 1, Codegen.str "of",
wenzelm@41424
   287
                   Pretty.brk 1, Codegen.str "0 =>", Pretty.brk 1,
wenzelm@33035
   288
                   mk_constr "0" true (cname, the (AList.lookup (op =) cs cname)),
wenzelm@41424
   289
                   Pretty.brk 1, Codegen.str "| _ =>", Pretty.brk 1,
wenzelm@41424
   290
                   mk_choice cs1, Codegen.str ")"]]
berghofe@14104
   291
               else [mk_choice cs2])) ::
berghofe@14104
   292
            (if null cs1 then []
berghofe@14104
   293
             else [Pretty.blk (4, separate (Pretty.brk 1) 
wenzelm@41424
   294
                 (Codegen.str ("and " ^ gen_name) :: gs @ [Codegen.str "i"]) @
wenzelm@41424
   295
               [Codegen.str " =", Pretty.brk 1] @
wenzelm@41424
   296
               separate (Pretty.brk 1) (Codegen.str (gen_name ^ "'") :: gs @
wenzelm@41424
   297
                 [Codegen.str "i", Codegen.str "i"]))]) @
berghofe@17144
   298
            mk_gen_of_def gr "and " xs
berghofe@14104
   299
          end
berghofe@13754
   300
berghofe@12445
   301
  in
wenzelm@41424
   302
    (module', (Codegen.add_edge_acyclic (node_id, dep) gr
berghofe@12445
   303
        handle Graph.CYCLES _ => gr) handle Graph.UNDEF _ =>
berghofe@12445
   304
         let
wenzelm@41424
   305
           val gr1 = Codegen.add_edge (node_id, dep)
wenzelm@41424
   306
             (Codegen.new_node (node_id, (NONE, "", "")) gr);
haftmann@28537
   307
           val (dtdef, gr2) = mk_dtdef "datatype " descr' gr1 ;
berghofe@12445
   308
         in
wenzelm@41424
   309
           Codegen.map_node node_id (K (NONE, module',
wenzelm@41424
   310
             Codegen.string_of (Pretty.blk (0, separate Pretty.fbrk dtdef @
wenzelm@41424
   311
               [Codegen.str ";"])) ^ "\n\n" ^
wenzelm@42411
   312
             (if member (op =) mode "term_of" then
wenzelm@41424
   313
                Codegen.string_of (Pretty.blk (0, separate Pretty.fbrk
wenzelm@41424
   314
                  (mk_term_of_def gr2 "fun " descr') @ [Codegen.str ";"])) ^ "\n\n"
berghofe@14104
   315
              else "") ^
wenzelm@42411
   316
             (if member (op =) mode "test" then
wenzelm@41424
   317
                Codegen.string_of (Pretty.blk (0, separate Pretty.fbrk
wenzelm@41424
   318
                  (mk_gen_of_def gr2 "fun " descr') @ [Codegen.str ";"])) ^ "\n\n"
berghofe@13754
   319
              else ""))) gr2
haftmann@28537
   320
         end)
berghofe@12445
   321
  end;
berghofe@12445
   322
berghofe@12445
   323
haftmann@31625
   324
(* case expressions *)
berghofe@12445
   325
wenzelm@42411
   326
fun pretty_case thy mode defs dep module brack constrs (c as Const (_, T)) ts gr =
berghofe@12445
   327
  let val i = length constrs
berghofe@12445
   328
  in if length ts <= i then
wenzelm@42411
   329
       Codegen.invoke_codegen thy mode defs dep module brack (Codegen.eta_expand c ts (i+1)) gr
berghofe@12445
   330
    else
berghofe@12445
   331
      let
haftmann@33957
   332
        val ts1 = take i ts;
haftmann@33957
   333
        val t :: ts2 = drop i ts;
wenzelm@30190
   334
        val names = List.foldr OldTerm.add_term_names
wenzelm@30190
   335
          (map (fst o fst o dest_Var) (List.foldr OldTerm.add_term_vars [] ts1)) ts1;
wenzelm@40844
   336
        val (Ts, dT) = split_last (take (i+1) (binder_types T));
berghofe@12445
   337
haftmann@28537
   338
        fun pcase [] [] [] gr = ([], gr)
haftmann@28537
   339
          | pcase ((cname, cargs)::cs) (t::ts) (U::Us) gr =
berghofe@12445
   340
              let
berghofe@12445
   341
                val j = length cargs;
wenzelm@20071
   342
                val xs = Name.variant_list names (replicate j "x");
wenzelm@40844
   343
                val Us' = take j (binder_types U);
haftmann@33957
   344
                val frees = map2 (curry Free) xs Us';
wenzelm@42411
   345
                val (cp, gr0) = Codegen.invoke_codegen thy mode defs dep module false
haftmann@28537
   346
                  (list_comb (Const (cname, Us' ---> dT), frees)) gr;
berghofe@12445
   347
                val t' = Envir.beta_norm (list_comb (t, frees));
wenzelm@42411
   348
                val (p, gr1) = Codegen.invoke_codegen thy mode defs dep module false t' gr0;
haftmann@28537
   349
                val (ps, gr2) = pcase cs ts Us gr1;
berghofe@12445
   350
              in
wenzelm@41424
   351
                ([Pretty.block [cp, Codegen.str " =>", Pretty.brk 1, p]] :: ps, gr2)
berghofe@12445
   352
              end;
berghofe@12445
   353
haftmann@28537
   354
        val (ps1, gr1) = pcase constrs ts1 Ts gr ;
wenzelm@41424
   355
        val ps = flat (separate [Pretty.brk 1, Codegen.str "| "] ps1);
wenzelm@42411
   356
        val (p, gr2) = Codegen.invoke_codegen thy mode defs dep module false t gr1;
wenzelm@42411
   357
        val (ps2, gr3) = fold_map (Codegen.invoke_codegen thy mode defs dep module true) ts2 gr2;
wenzelm@41424
   358
      in ((if not (null ts2) andalso brack then Codegen.parens else I)
berghofe@12445
   359
        (Pretty.block (separate (Pretty.brk 1)
wenzelm@41424
   360
          (Pretty.block ([Codegen.str "(case ", p, Codegen.str " of",
wenzelm@41424
   361
             Pretty.brk 1] @ ps @ [Codegen.str ")"]) :: ps2))), gr3)
berghofe@12445
   362
      end
berghofe@12445
   363
  end;
berghofe@12445
   364
berghofe@12445
   365
haftmann@31625
   366
(* constructors *)
berghofe@12445
   367
wenzelm@42411
   368
fun pretty_constr thy mode defs dep module brack args (c as Const (s, T)) ts gr =
berghofe@12445
   369
  let val i = length args
berghofe@12445
   370
  in if i > 1 andalso length ts < i then
wenzelm@42411
   371
      Codegen.invoke_codegen thy mode defs dep module brack (Codegen.eta_expand c ts i) gr
berghofe@12445
   372
     else
berghofe@12445
   373
       let
wenzelm@41424
   374
         val id = Codegen.mk_qual_id module (Codegen.get_const_id gr s);
haftmann@28537
   375
         val (ps, gr') = fold_map
wenzelm@42411
   376
           (Codegen.invoke_codegen thy mode defs dep module (i = 1)) ts gr;
wenzelm@41424
   377
       in
wenzelm@41424
   378
        (case args of
wenzelm@41424
   379
          _ :: _ :: _ => (if brack then Codegen.parens else I)
wenzelm@41424
   380
            (Pretty.block [Codegen.str id, Pretty.brk 1, Codegen.mk_tuple ps])
wenzelm@41424
   381
        | _ => (Codegen.mk_app brack (Codegen.str id) ps), gr')
berghofe@12445
   382
       end
berghofe@12445
   383
  end;
berghofe@12445
   384
berghofe@12445
   385
haftmann@31625
   386
(* code generators for terms and types *)
berghofe@12445
   387
wenzelm@42411
   388
fun datatype_codegen thy mode defs dep module brack t gr =
wenzelm@40844
   389
  (case strip_comb t of
wenzelm@40844
   390
    (c as Const (s, T), ts) =>
wenzelm@40844
   391
      (case Datatype_Data.info_of_case thy s of
berghofe@22778
   392
        SOME {index, descr, ...} =>
wenzelm@41424
   393
          if is_some (Codegen.get_assoc_code thy (s, T)) then NONE
wenzelm@40844
   394
          else
wenzelm@42411
   395
            SOME (pretty_case thy mode defs dep module brack
wenzelm@40844
   396
              (#3 (the (AList.lookup op = descr index))) c ts gr)
wenzelm@40844
   397
      | NONE =>
wenzelm@40844
   398
          (case (Datatype_Data.info_of_constr thy (s, T), body_type T) of
wenzelm@40844
   399
            (SOME {index, descr, ...}, U as Type (tyname, _)) =>
wenzelm@41424
   400
              if is_some (Codegen.get_assoc_code thy (s, T)) then NONE
wenzelm@40844
   401
              else
wenzelm@40844
   402
                let
wenzelm@40844
   403
                  val SOME (tyname', _, constrs) = AList.lookup op = descr index;
wenzelm@40844
   404
                  val SOME args = AList.lookup op = constrs s;
wenzelm@40844
   405
                in
wenzelm@40844
   406
                  if tyname <> tyname' then NONE
wenzelm@40844
   407
                  else
wenzelm@40844
   408
                    SOME
wenzelm@42411
   409
                      (pretty_constr thy mode defs
wenzelm@40844
   410
                        dep module brack args c ts
wenzelm@42411
   411
                        (snd (Codegen.invoke_tycodegen thy mode defs dep module false U gr)))
wenzelm@40844
   412
                end
wenzelm@40844
   413
          | _ => NONE))
wenzelm@40844
   414
  | _ => NONE);
berghofe@12445
   415
wenzelm@42411
   416
fun datatype_tycodegen thy mode defs dep module brack (Type (s, Ts)) gr =
haftmann@33964
   417
      (case Datatype_Data.get_info thy s of
skalberg@15531
   418
         NONE => NONE
berghofe@25889
   419
       | SOME {descr, sorts, ...} =>
wenzelm@41424
   420
           if is_some (Codegen.get_assoc_type thy s) then NONE else
berghofe@16645
   421
           let
haftmann@28537
   422
             val (ps, gr') = fold_map
wenzelm@42411
   423
               (Codegen.invoke_tycodegen thy mode defs dep module false) Ts gr;
wenzelm@42411
   424
             val (module', gr'') = add_dt_defs thy mode defs dep module descr sorts gr' ;
wenzelm@41424
   425
             val (tyid, gr''') = Codegen.mk_type_id module' s gr''
haftmann@28537
   426
           in SOME (Pretty.block ((if null Ts then [] else
wenzelm@41424
   427
               [Codegen.mk_tuple ps, Codegen.str " "]) @
wenzelm@41424
   428
               [Codegen.str (Codegen.mk_qual_id module tyid)]), gr''')
berghofe@12445
   429
           end)
wenzelm@42411
   430
  | datatype_tycodegen _ _ _ _ _ _ _ _ = NONE;
berghofe@12445
   431
haftmann@18247
   432
haftmann@20426
   433
(** theory setup **)
haftmann@20426
   434
haftmann@19008
   435
val setup = 
haftmann@36298
   436
  Datatype_Data.interpretation add_all_code
wenzelm@41424
   437
  #> Codegen.add_codegen "datatype" datatype_codegen
wenzelm@41424
   438
  #> Codegen.add_tycodegen "datatype" datatype_tycodegen;
haftmann@20597
   439
berghofe@12445
   440
end;