src/Tools/Code/code_scala.ML
author haftmann
Thu Jan 14 17:47:39 2010 +0100 (2010-01-14)
changeset 34900 9b12b0824bfe
parent 34888 460ec1a99aa2
child 34944 970e1466028d
permissions -rw-r--r--
tuned for products vs. tupled functions
haftmann@34294
     1
(*  Author:     Florian Haftmann, TU Muenchen
haftmann@34294
     2
haftmann@34294
     3
Serializer for Scala.
haftmann@34294
     4
*)
haftmann@34294
     5
haftmann@34294
     6
signature CODE_SCALA =
haftmann@34294
     7
sig
haftmann@34294
     8
  val setup: theory -> theory
haftmann@34294
     9
end;
haftmann@34294
    10
haftmann@34294
    11
structure Code_Scala : CODE_SCALA =
haftmann@34294
    12
struct
haftmann@34294
    13
haftmann@34294
    14
val target = "Scala";
haftmann@34294
    15
haftmann@34294
    16
open Basic_Code_Thingol;
haftmann@34294
    17
open Code_Printer;
haftmann@34294
    18
haftmann@34294
    19
infixr 5 @@;
haftmann@34294
    20
infixr 5 @|;
haftmann@34294
    21
haftmann@34294
    22
haftmann@34294
    23
(** Scala serializer **)
haftmann@34294
    24
haftmann@34294
    25
fun print_scala_stmt labelled_name syntax_tyco syntax_const reserved args_num is_singleton deresolve =
haftmann@34294
    26
  let
haftmann@34294
    27
    val deresolve_base = Long_Name.base_name o deresolve;
haftmann@34294
    28
    fun print_typ tyvars fxy (tycoexpr as tyco `%% tys) = (case syntax_tyco tyco
haftmann@34294
    29
         of NONE => applify "[" "]" fxy
haftmann@34294
    30
              ((str o deresolve) tyco) (map (print_typ tyvars NOBR) tys)
haftmann@34294
    31
          | SOME (i, print) => print (print_typ tyvars) fxy tys)
haftmann@34294
    32
      | print_typ tyvars fxy (ITyVar v) = (str o lookup_var tyvars) v;
haftmann@34294
    33
    fun print_typed tyvars p ty =
haftmann@34294
    34
      Pretty.block [p, str ":", Pretty.brk 1, print_typ tyvars NOBR ty]
haftmann@34294
    35
    fun print_var vars NONE = str "_"
haftmann@34294
    36
      | print_var vars (SOME v) = (str o lookup_var vars) v
haftmann@34294
    37
    fun print_term tyvars is_pat thm vars fxy (IConst c) =
haftmann@34294
    38
          print_app tyvars is_pat thm vars fxy (c, [])
haftmann@34294
    39
      | print_term tyvars is_pat thm vars fxy (t as (t1 `$ t2)) =
haftmann@34294
    40
          (case Code_Thingol.unfold_const_app t
haftmann@34294
    41
           of SOME app => print_app tyvars is_pat thm vars fxy app
haftmann@34294
    42
            | _ => applify "(" ")" fxy
haftmann@34294
    43
                (print_term tyvars is_pat thm vars BR t1)
haftmann@34294
    44
                [print_term tyvars is_pat thm vars NOBR t2])
haftmann@34294
    45
      | print_term tyvars is_pat thm vars fxy (IVar v) =
haftmann@34294
    46
          print_var vars v
haftmann@34294
    47
      | print_term tyvars is_pat thm vars fxy ((v, ty) `|=> t) =
haftmann@34294
    48
          let
haftmann@34294
    49
            val vars' = intro_vars (the_list v) vars;
haftmann@34294
    50
          in
haftmann@34294
    51
            concat [
haftmann@34294
    52
              Pretty.block [str "(", print_typed tyvars (print_var vars' v) ty, str ")"],
haftmann@34294
    53
              str "=>",
haftmann@34294
    54
              print_term tyvars false thm vars' NOBR t
haftmann@34294
    55
            ]
haftmann@34294
    56
          end 
haftmann@34294
    57
      | print_term tyvars is_pat thm vars fxy (ICase (cases as (_, t0))) =
haftmann@34294
    58
          (case Code_Thingol.unfold_const_app t0
haftmann@34294
    59
           of SOME (c_ts as ((c, _), _)) => if is_none (syntax_const c)
haftmann@34294
    60
                then print_case tyvars thm vars fxy cases
haftmann@34294
    61
                else print_app tyvars is_pat thm vars fxy c_ts
haftmann@34294
    62
            | NONE => print_case tyvars thm vars fxy cases)
haftmann@34308
    63
    and print_app tyvars is_pat thm vars fxy (app as ((c, ((tys, _), tys_args)), ts)) =
haftmann@34294
    64
      let
haftmann@34294
    65
        val k = length ts;
haftmann@34294
    66
        val l = case syntax_const c of NONE => args_num c | SOME (l, _) => l;
haftmann@34294
    67
        val tys' = if is_pat orelse
haftmann@34294
    68
          (is_none (syntax_const c) andalso is_singleton c) then [] else tys;
haftmann@34294
    69
        val (no_syntax, print') = case syntax_const c
haftmann@34294
    70
         of NONE => (true, fn ts => applify "(" ")" fxy
haftmann@34294
    71
              (applify "[" "]" NOBR ((str o deresolve) c) (map (print_typ tyvars NOBR) tys'))
haftmann@34294
    72
                (map (print_term tyvars is_pat thm vars NOBR) ts))
haftmann@34294
    73
          | SOME (_, print) => (false, fn ts =>
haftmann@34900
    74
              print (print_term tyvars is_pat thm) thm vars fxy (ts ~~ take l tys_args));
haftmann@34294
    75
      in if k = l then print' ts
haftmann@34294
    76
      else if k < l then
haftmann@34294
    77
        print_term tyvars is_pat thm vars fxy (Code_Thingol.eta_expand l app)
haftmann@34294
    78
      else let
haftmann@34294
    79
        val (ts1, ts23) = chop l ts;
haftmann@34294
    80
      in
haftmann@34294
    81
        Pretty.block (print' ts1 :: map (fn t => Pretty.block
haftmann@34294
    82
          [str ".apply(", print_term tyvars is_pat thm vars NOBR t, str ")"]) ts23)
haftmann@34294
    83
      end end
haftmann@34294
    84
    and print_bind tyvars thm fxy p = gen_print_bind (print_term tyvars true) thm fxy p
haftmann@34294
    85
    and print_case tyvars thm vars fxy (cases as ((_, [_]), _)) =
haftmann@34294
    86
          let
haftmann@34294
    87
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@34294
    88
            fun print_match ((pat, ty), t) vars =
haftmann@34294
    89
              vars
haftmann@34294
    90
              |> print_bind tyvars thm BR pat
haftmann@34294
    91
              |>> (fn p => semicolon [Pretty.block [str "val", Pretty.brk 1, p,
haftmann@34294
    92
                str ":", Pretty.brk 1, print_typ tyvars NOBR ty],
haftmann@34294
    93
                  str "=", print_term tyvars false thm vars NOBR t])
haftmann@34294
    94
            val (ps, vars') = fold_map print_match binds vars;
haftmann@34294
    95
          in
haftmann@34294
    96
            brackify_block fxy
haftmann@34294
    97
              (str "{")
haftmann@34294
    98
              (ps @| print_term tyvars false thm vars' NOBR body)
haftmann@34294
    99
              (str "}")
haftmann@34294
   100
          end
haftmann@34294
   101
      | print_case tyvars thm vars fxy (((t, ty), clauses as _ :: _), _) =
haftmann@34294
   102
          let
haftmann@34294
   103
            fun print_select (pat, body) =
haftmann@34294
   104
              let
haftmann@34294
   105
                val (p, vars') = print_bind tyvars thm NOBR pat vars;
haftmann@34294
   106
              in concat [str "case", p, str "=>", print_term tyvars false thm vars' NOBR body] end;
haftmann@34294
   107
          in brackify_block fxy
haftmann@34294
   108
            (concat [print_term tyvars false thm vars NOBR t, str "match", str "{"])
haftmann@34294
   109
            (map print_select clauses)
haftmann@34294
   110
            (str "}") 
haftmann@34294
   111
          end
haftmann@34294
   112
      | print_case tyvars thm vars fxy ((_, []), _) =
haftmann@34294
   113
          (brackify fxy o Pretty.breaks o map str) ["error(\"empty case\")"];
haftmann@34294
   114
    fun implicit_arguments tyvars vs vars =
haftmann@34294
   115
      let
haftmann@34294
   116
        val implicit_typ_ps = maps (fn (v, sort) => map (fn class => Pretty.block
haftmann@34294
   117
          [(str o deresolve) class, str "[", (str o lookup_var tyvars) v, str "]"]) sort) vs;
haftmann@34294
   118
        val implicit_names = Name.invents (snd vars) "a" (length implicit_typ_ps);
haftmann@34294
   119
        val vars' = intro_vars implicit_names vars;
haftmann@34294
   120
        val implicit_ps = map2 (fn v => fn p => concat [str (v ^ ":"), p])
haftmann@34294
   121
          implicit_names implicit_typ_ps;
haftmann@34294
   122
      in ((implicit_names, implicit_ps), vars') end;
haftmann@34294
   123
    fun print_defhead tyvars vars p vs params tys implicits ty =
haftmann@34294
   124
      concat [str "def", print_typed tyvars (applify "(implicit " ")" NOBR
haftmann@34294
   125
        (applify "(" ")" NOBR
haftmann@34294
   126
          (applify "[" "]" NOBR p (map (str o lookup_var tyvars o fst) vs))
haftmann@34294
   127
            (map2 (fn param => fn ty => print_typed tyvars
haftmann@34294
   128
                ((str o lookup_var vars) param) ty)
haftmann@34294
   129
              params tys)) implicits) ty, str "="]
haftmann@34294
   130
    fun print_stmt (name, Code_Thingol.Fun (_, ((vs, ty), raw_eqs))) = (case filter (snd o snd) raw_eqs
haftmann@34294
   131
         of [] =>
haftmann@34294
   132
              let
haftmann@34294
   133
                val (tys, ty') = Code_Thingol.unfold_fun ty;
haftmann@34294
   134
                val params = Name.invents (snd reserved) "a" (length tys);
haftmann@34294
   135
                val tyvars = intro_vars (map fst vs) reserved;
haftmann@34294
   136
                val vars = intro_vars params reserved;
haftmann@34294
   137
              in
haftmann@34294
   138
                concat [print_defhead tyvars vars ((str o deresolve) name) vs params tys [] ty',
haftmann@34294
   139
                  str ("error(\"" ^ name ^ "\")")]
haftmann@34294
   140
              end
haftmann@34294
   141
          | eqs =>
haftmann@34294
   142
              let
haftmann@34294
   143
                val tycos = fold (fn ((ts, t), (thm, _)) =>
haftmann@34294
   144
                  fold Code_Thingol.add_tyconames (t :: ts)) eqs [];
haftmann@34294
   145
                val tyvars = reserved
haftmann@34294
   146
                  |> intro_base_names
haftmann@34294
   147
                       (is_none o syntax_tyco) deresolve tycos
haftmann@34294
   148
                  |> intro_vars (map fst vs);
haftmann@34294
   149
                val simple = case eqs
haftmann@34294
   150
                 of [((ts, _), _)] => forall Code_Thingol.is_IVar ts
haftmann@34294
   151
                  | _ => false;
haftmann@34294
   152
                val consts = fold Code_Thingol.add_constnames
haftmann@34294
   153
                  (map (snd o fst) eqs) [];
haftmann@34294
   154
                val vars1 = reserved
haftmann@34294
   155
                  |> intro_base_names
haftmann@34294
   156
                       (is_none o syntax_const) deresolve consts
haftmann@34294
   157
                val ((_, implicit_ps), vars2) = implicit_arguments tyvars vs vars1;
haftmann@34294
   158
                val params = if simple then (map (fn IVar (SOME x) => x) o fst o fst o hd) eqs
haftmann@34294
   159
                  else aux_params vars2 (map (fst o fst) eqs);
haftmann@34294
   160
                val vars3 = intro_vars params vars2;
haftmann@34294
   161
                val (tys, ty1) = Code_Thingol.unfold_fun ty;
haftmann@34294
   162
                val (tys1, tys2) = chop (length params) tys;
haftmann@34294
   163
                val ty2 = Library.foldr
haftmann@34294
   164
                  (fn (ty1, ty2) => Code_Thingol.fun_tyco `%% [ty1, ty2]) (tys2, ty1);
haftmann@34294
   165
                fun print_tuple [p] = p
haftmann@34294
   166
                  | print_tuple ps = enum "," "(" ")" ps;
haftmann@34294
   167
                fun print_rhs vars' ((_, t), (thm, _)) = print_term tyvars false thm vars' NOBR t;
haftmann@34294
   168
                fun print_clause (eq as ((ts, _), (thm, _))) =
haftmann@34294
   169
                  let
haftmann@34294
   170
                    val vars' = intro_vars ((fold o Code_Thingol.fold_varnames) (insert (op =)) ts []) vars2;
haftmann@34294
   171
                  in
haftmann@34294
   172
                    concat [str "case", print_tuple (map (print_term tyvars true thm vars' NOBR) ts),
haftmann@34294
   173
                      str "=>", print_rhs vars' eq]
haftmann@34294
   174
                  end;
haftmann@34294
   175
                val head = print_defhead tyvars vars3 ((str o deresolve) name) vs params tys1 implicit_ps ty2;
haftmann@34294
   176
              in if simple then
haftmann@34294
   177
                concat [head, print_rhs vars3 (hd eqs)]
haftmann@34294
   178
              else
haftmann@34294
   179
                Pretty.block_enclose
haftmann@34294
   180
                  (concat [head, print_tuple (map (str o lookup_var vars3) params),
haftmann@34294
   181
                    str "match", str "{"], str "}")
haftmann@34294
   182
                  (map print_clause eqs)
haftmann@34294
   183
              end)
haftmann@34294
   184
      | print_stmt (name, Code_Thingol.Datatype (_, (vs, cos))) =
haftmann@34294
   185
          let
haftmann@34294
   186
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@34294
   187
            fun print_co (co, []) =
haftmann@34294
   188
                  concat [str "final", str "case", str "object", (str o deresolve_base) co,
haftmann@34294
   189
                    str "extends", applify "[" "]" NOBR ((str o deresolve_base) name)
haftmann@34294
   190
                      (replicate (length vs) (str "Nothing"))]
haftmann@34294
   191
              | print_co (co, tys) =
haftmann@34294
   192
                  let
haftmann@34294
   193
                    val fields = Name.names (snd reserved) "a" tys;
haftmann@34294
   194
                    val vars = intro_vars (map fst fields) reserved;
haftmann@34294
   195
                    fun add_typargs p = applify "[" "]" NOBR p
haftmann@34294
   196
                      (map (str o lookup_var tyvars o fst) vs);
haftmann@34294
   197
                  in
haftmann@34294
   198
                    concat [
haftmann@34294
   199
                      applify "(" ")" NOBR
haftmann@34294
   200
                        (add_typargs ((concat o map str) ["final", "case", "class", deresolve_base co]))
haftmann@34294
   201
                        (map (uncurry (print_typed tyvars) o apfst str) fields),
haftmann@34294
   202
                      str "extends",
haftmann@34294
   203
                      add_typargs ((str o deresolve_base) name)
haftmann@34294
   204
                    ]
haftmann@34294
   205
                  end
haftmann@34294
   206
          in
haftmann@34294
   207
            Pretty.chunks (
haftmann@34294
   208
              applify "[" "]" NOBR ((concat o map str) ["sealed", "class", deresolve_base name])
haftmann@34294
   209
                (map (str o prefix "+" o lookup_var tyvars o fst) vs)
haftmann@34294
   210
              :: map print_co cos
haftmann@34294
   211
            )
haftmann@34294
   212
          end
haftmann@34294
   213
      | print_stmt (name, Code_Thingol.Class (_, (v, (superclasses, classparams)))) =
haftmann@34294
   214
          let
haftmann@34294
   215
            val tyvars = intro_vars [v] reserved;
haftmann@34294
   216
            val vs = [(v, [name])];
haftmann@34294
   217
            fun add_typarg p = applify "[" "]" NOBR p [(str o lookup_var tyvars) v];
haftmann@34294
   218
            fun print_superclasses [] = NONE
haftmann@34294
   219
              | print_superclasses classes = SOME (concat (str "extends"
haftmann@34294
   220
                  :: separate (str "with") (map (add_typarg o str o deresolve o fst) classes)));
haftmann@34294
   221
            fun print_tupled_typ ([], ty) =
haftmann@34294
   222
                  print_typ tyvars NOBR ty
haftmann@34294
   223
              | print_tupled_typ ([ty1], ty2) =
haftmann@34294
   224
                  concat [print_typ tyvars BR ty1, str "=>", print_typ tyvars NOBR ty2]
haftmann@34294
   225
              | print_tupled_typ (tys, ty) =
haftmann@34294
   226
                  concat [enum "," "(" ")" (map (print_typ tyvars NOBR) tys),
haftmann@34294
   227
                    str "=>", print_typ tyvars NOBR ty];
haftmann@34294
   228
            fun print_classparam_val (classparam, ty) =
haftmann@34294
   229
              concat [str "val", (str o suffix "$:" o deresolve_base) classparam,
haftmann@34294
   230
                (print_tupled_typ o Code_Thingol.unfold_fun) ty]
haftmann@34294
   231
            fun print_classparam_def (classparam, ty) =
haftmann@34294
   232
              let
haftmann@34294
   233
                val (tys, ty) = Code_Thingol.unfold_fun ty;
haftmann@34294
   234
                val params = Name.invents (snd reserved) "a" (length tys);
haftmann@34294
   235
                val vars = intro_vars params reserved;
haftmann@34294
   236
                val (([implicit], [p_implicit]), vars') = implicit_arguments tyvars vs vars;
haftmann@34294
   237
                val head = print_defhead tyvars vars' ((str o deresolve) classparam) vs params tys [p_implicit] ty;
haftmann@34294
   238
              in
haftmann@34294
   239
                concat [head, applify "(" ")" NOBR
haftmann@34294
   240
                  (Pretty.block [str implicit, str ".", (str o suffix "$" o deresolve_base) classparam])
haftmann@34294
   241
                  (map (str o lookup_var vars') params)]
haftmann@34294
   242
              end;
haftmann@34294
   243
          in
haftmann@34294
   244
            Pretty.chunks (
haftmann@34294
   245
              (Pretty.block_enclose
haftmann@34294
   246
                (concat ([str "trait", add_typarg ((str o deresolve_base) name)]
haftmann@34294
   247
                  @ the_list (print_superclasses superclasses) @ [str "{"]), str "}")
haftmann@34294
   248
                (map print_classparam_val classparams))
haftmann@34294
   249
              :: map print_classparam_def classparams
haftmann@34294
   250
            )
haftmann@34294
   251
          end
haftmann@34294
   252
      | print_stmt (name, Code_Thingol.Classinst ((class, (tyco, vs)),
haftmann@34294
   253
            (super_instances, classparam_insts))) =
haftmann@34294
   254
          let
haftmann@34294
   255
            val tyvars = intro_vars (map fst vs) reserved;
haftmann@34294
   256
            val insttyp = tyco `%% map (ITyVar o fst) vs;
haftmann@34294
   257
            val p_inst_typ = print_typ tyvars NOBR insttyp;
haftmann@34294
   258
            fun add_typ_params p = applify "[" "]" NOBR p (map (str o lookup_var tyvars o fst) vs);
haftmann@34294
   259
            fun add_inst_typ p = Pretty.block [p, str "[", p_inst_typ, str "]"];
haftmann@34294
   260
            val ((implicit_names, implicit_ps), vars) = implicit_arguments tyvars vs reserved;
haftmann@34294
   261
            fun print_classparam_inst ((classparam, const as (_, (_, tys))), (thm, _)) =
haftmann@34294
   262
              let
haftmann@34294
   263
                val auxs = Name.invents (snd reserved) "a" (length tys);
haftmann@34294
   264
                val vars = intro_vars auxs reserved;
haftmann@34294
   265
                val args = if null auxs then [] else
haftmann@34294
   266
                  [concat [enum "," "(" ")" (map2 (fn aux => fn ty => print_typed tyvars ((str o lookup_var vars) aux) ty)
haftmann@34294
   267
                    auxs tys), str "=>"]];
haftmann@34294
   268
              in 
haftmann@34294
   269
                concat ([str "val", (str o suffix "$" o deresolve_base) classparam,
haftmann@34294
   270
                  str "="] @ args @ [print_app tyvars false thm vars NOBR (const, map (IVar o SOME) auxs)])
haftmann@34294
   271
              end;
haftmann@34294
   272
          in
haftmann@34294
   273
            Pretty.chunks [
haftmann@34294
   274
              Pretty.block_enclose
haftmann@34294
   275
                (concat ([str "trait",
haftmann@34294
   276
                    add_typ_params ((str o deresolve_base) name),
haftmann@34294
   277
                    str "extends",
haftmann@34294
   278
                    Pretty.block [(str o deresolve) class, str "[", p_inst_typ, str "]"]]
haftmann@34294
   279
                    @ map (fn (_, (_, (superinst, _))) => add_typ_params (str ("with " ^ deresolve superinst)))
haftmann@34294
   280
                      super_instances @| str "{"), str "}")
haftmann@34294
   281
                (map (fn p => Pretty.block [str "implicit val arg$", p]) implicit_ps
haftmann@34294
   282
                  @ map print_classparam_inst classparam_insts),
haftmann@34294
   283
              concat [str "implicit", str (if null vs then "val" else "def"),
haftmann@34294
   284
                applify "(implicit " ")" NOBR (applify "[" "]" NOBR
haftmann@34294
   285
                  ((str o deresolve_base) name) (map (str o lookup_var tyvars o fst) vs))
haftmann@34294
   286
                    implicit_ps,
haftmann@34294
   287
                  str "=", str "new", applify "[" "]" NOBR ((str o deresolve_base) name)
haftmann@34294
   288
                      (map (str o lookup_var tyvars o fst) vs),
haftmann@34294
   289
                    Pretty.enum ";" "{ " " }" (map (str o (fn v => "val arg$" ^ v ^ " = " ^ v) o lookup_var vars)
haftmann@34294
   290
                      implicit_names)]
haftmann@34294
   291
            ]
haftmann@34294
   292
          end;
haftmann@34294
   293
  in print_stmt end;
haftmann@34294
   294
haftmann@34294
   295
fun scala_program_of_program labelled_name module_name reserved raw_module_alias program =
haftmann@34294
   296
  let
haftmann@34294
   297
    val the_module_name = the_default "Program" module_name;
haftmann@34294
   298
    val module_alias = K (SOME the_module_name);
haftmann@34294
   299
    val reserved = Name.make_context reserved;
haftmann@34294
   300
    fun prepare_stmt (name, stmt) (nsps, stmts) =
haftmann@34294
   301
      let
haftmann@34294
   302
        val (_, base) = Code_Printer.dest_name name;
haftmann@34294
   303
        val mk_name_stmt = yield_singleton Name.variants;
haftmann@34294
   304
        fun add_class ((nsp_class, nsp_object), nsp_common) =
haftmann@34294
   305
          let
haftmann@34294
   306
            val (base', nsp_class') = mk_name_stmt base nsp_class
haftmann@34294
   307
          in (base', ((nsp_class', nsp_object), Name.declare base' nsp_common)) end;
haftmann@34294
   308
        fun add_object ((nsp_class, nsp_object), nsp_common) =
haftmann@34294
   309
          let
haftmann@34294
   310
            val (base', nsp_object') = mk_name_stmt base nsp_object
haftmann@34294
   311
          in (base', ((nsp_class, nsp_object'), Name.declare base' nsp_common)) end;
haftmann@34294
   312
        fun add_common upper ((nsp_class, nsp_object), nsp_common) =
haftmann@34294
   313
          let
haftmann@34294
   314
            val (base', nsp_common') =
haftmann@34294
   315
              mk_name_stmt (if upper then first_upper base else base) nsp_common
haftmann@34294
   316
          in (base', ((Name.declare base' nsp_class, Name.declare base' nsp_object), nsp_common')) end;
haftmann@34294
   317
        val add_name = case stmt
haftmann@34294
   318
         of Code_Thingol.Fun _ => add_object
haftmann@34294
   319
          | Code_Thingol.Datatype _ => add_class
haftmann@34294
   320
          | Code_Thingol.Datatypecons _ => add_common true
haftmann@34294
   321
          | Code_Thingol.Class _ => add_class
haftmann@34294
   322
          | Code_Thingol.Classrel _ => add_object
haftmann@34294
   323
          | Code_Thingol.Classparam _ => add_object
haftmann@34294
   324
          | Code_Thingol.Classinst _ => add_common false;
haftmann@34294
   325
        fun add_stmt base' = case stmt
haftmann@34294
   326
         of Code_Thingol.Datatypecons _ => cons (name, (base', NONE))
haftmann@34294
   327
          | Code_Thingol.Classrel _ => cons (name, (base', NONE))
haftmann@34294
   328
          | Code_Thingol.Classparam _ => cons (name, (base', NONE))
haftmann@34294
   329
          | _ => cons (name, (base', SOME stmt));
haftmann@34294
   330
      in
haftmann@34294
   331
        nsps
haftmann@34294
   332
        |> add_name
haftmann@34294
   333
        |-> (fn base' => rpair (add_stmt base' stmts))
haftmann@34294
   334
      end;
haftmann@34294
   335
    val (_, sca_program) = fold prepare_stmt (AList.make (fn name => Graph.get_node program name)
haftmann@34294
   336
      (Graph.strong_conn program |> flat)) (((reserved, reserved), reserved), []);
haftmann@34294
   337
    fun deresolver name = (fst o the o AList.lookup (op =) sca_program) name
haftmann@34294
   338
      handle Option => error ("Unknown statement name: " ^ labelled_name name);
haftmann@34294
   339
  in (deresolver, (the_module_name, sca_program)) end;
haftmann@34294
   340
haftmann@34294
   341
fun serialize_scala raw_module_name labelled_name
haftmann@34294
   342
    raw_reserved includes raw_module_alias
haftmann@34294
   343
    _ syntax_tyco syntax_const (code_of_pretty, code_writeln) program cs destination =
haftmann@34294
   344
  let
haftmann@34294
   345
    val stmt_names = Code_Target.stmt_names_of_destination destination;
haftmann@34294
   346
    val module_name = if null stmt_names then raw_module_name else SOME "Code";
haftmann@34294
   347
    val reserved = fold (insert (op =) o fst) includes raw_reserved;
haftmann@34294
   348
    val (deresolver, (the_module_name, sca_program)) = scala_program_of_program labelled_name
haftmann@34294
   349
      module_name reserved raw_module_alias program;
haftmann@34294
   350
    val reserved = make_vars reserved;
haftmann@34294
   351
    fun args_num c = case Graph.get_node program c
haftmann@34294
   352
     of Code_Thingol.Fun (_, ((_, ty), [])) => (length o fst o Code_Thingol.unfold_fun) ty
haftmann@34294
   353
      | Code_Thingol.Fun (_, (_, ((ts, _), _) :: _)) => length ts
haftmann@34294
   354
      | Code_Thingol.Datatypecons (_, tyco) =>
haftmann@34294
   355
          let val Code_Thingol.Datatype (_, (_, dtcos)) = Graph.get_node program tyco
haftmann@34294
   356
          in (length o the o AList.lookup (op =) dtcos) c end
haftmann@34294
   357
      | Code_Thingol.Classparam (_, class) =>
haftmann@34294
   358
          let val Code_Thingol.Class (_, (_, (_, classparams))) = Graph.get_node program class
haftmann@34294
   359
          in (length o fst o Code_Thingol.unfold_fun o the o AList.lookup (op =) classparams) c end;
haftmann@34294
   360
    fun is_singleton c = case Graph.get_node program c
haftmann@34294
   361
     of Code_Thingol.Datatypecons (_, tyco) =>
haftmann@34294
   362
          let val Code_Thingol.Datatype (_, (_, dtcos)) = Graph.get_node program tyco
haftmann@34294
   363
          in (null o the o AList.lookup (op =) dtcos) c end
haftmann@34294
   364
      | _ => false;
haftmann@34294
   365
    val print_stmt = print_scala_stmt labelled_name syntax_tyco syntax_const
haftmann@34294
   366
      reserved args_num is_singleton deresolver;
haftmann@34294
   367
    fun print_module name content =
haftmann@34294
   368
      (name, Pretty.chunks [
haftmann@34294
   369
        str ("object " ^ name ^ " {"),
haftmann@34294
   370
        str "",
haftmann@34294
   371
        content,
haftmann@34294
   372
        str "",
haftmann@34294
   373
        str "}"
haftmann@34294
   374
      ]);
haftmann@34294
   375
    fun serialize_module the_module_name sca_program =
haftmann@34294
   376
      let
haftmann@34294
   377
        val content = Pretty.chunks2 (map_filter
haftmann@34294
   378
          (fn (name, (_, SOME stmt)) => SOME (print_stmt (name, stmt))
haftmann@34294
   379
            | (_, (_, NONE)) => NONE) sca_program);
haftmann@34294
   380
      in print_module the_module_name content end;
haftmann@34294
   381
    fun check_destination destination =
haftmann@34294
   382
      (File.check destination; destination);
haftmann@34294
   383
    fun write_module destination (modlname, content) =
haftmann@34294
   384
      let
haftmann@34294
   385
        val filename = case modlname
haftmann@34294
   386
         of "" => Path.explode "Main.scala"
haftmann@34294
   387
          | _ => (Path.ext "scala" o Path.explode o implode o separate "/"
haftmann@34294
   388
                o Long_Name.explode) modlname;
haftmann@34294
   389
        val pathname = Path.append destination filename;
haftmann@34294
   390
        val _ = File.mkdir (Path.dir pathname);
haftmann@34294
   391
      in File.write pathname (code_of_pretty content) end
haftmann@34294
   392
  in
haftmann@34294
   393
    Code_Target.mk_serialization target NONE
haftmann@34294
   394
      (fn NONE => K () o map (code_writeln o snd) | SOME file => K () o map
haftmann@34294
   395
        (write_module (check_destination file)))
haftmann@34294
   396
      (rpair [] o cat_lines o map (code_of_pretty o snd))
haftmann@34294
   397
      (map (uncurry print_module) includes
haftmann@34294
   398
        @| serialize_module the_module_name sca_program)
haftmann@34294
   399
      destination
haftmann@34294
   400
  end;
haftmann@34294
   401
haftmann@34294
   402
val literals = let
haftmann@34294
   403
  fun char_scala c =
haftmann@34294
   404
    let
haftmann@34294
   405
      val s = ML_Syntax.print_char c;
haftmann@34294
   406
    in if s = "'" then "\\'" else s end;
haftmann@34900
   407
  fun bigint_scala k = "(" ^ (if k <= 2147483647
haftmann@34900
   408
    then string_of_int k else quote (string_of_int k)) ^ ")"
haftmann@34294
   409
in Literals {
haftmann@34294
   410
  literal_char = Library.enclose "'" "'" o char_scala,
haftmann@34294
   411
  literal_string = quote o translate_string char_scala,
haftmann@34900
   412
  literal_numeral = fn unbounded => fn k => if k >= 0 then
haftmann@34900
   413
      if unbounded then bigint_scala k
haftmann@34900
   414
      else Library.enclose "(" ")" (string_of_int k)
haftmann@34900
   415
    else
haftmann@34900
   416
      if unbounded then "(- " ^ bigint_scala (~ k) ^ ")"
haftmann@34900
   417
      else Library.enclose "(" ")" (signed_string_of_int k),
haftmann@34888
   418
  literal_list = fn [] => str "Nil" | ps => Pretty.block [str "List", enum "," "(" ")" ps],
haftmann@34294
   419
  infix_cons = (6, "::")
haftmann@34294
   420
} end;
haftmann@34294
   421
haftmann@34294
   422
haftmann@34294
   423
(** Isar setup **)
haftmann@34294
   424
haftmann@34294
   425
fun isar_seri_scala module_name =
haftmann@34294
   426
  Code_Target.parse_args (Scan.succeed ())
haftmann@34294
   427
  #> (fn () => serialize_scala module_name);
haftmann@34294
   428
haftmann@34294
   429
val setup =
haftmann@34294
   430
  Code_Target.add_target (target, (isar_seri_scala, literals))
haftmann@34294
   431
  #> Code_Target.add_syntax_tyco target "fun" (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@34294
   432
      brackify_infix (1, R) fxy [
haftmann@34900
   433
        print_typ BR ty1 (*product type vs. tupled arguments!*),
haftmann@34294
   434
        str "=>",
haftmann@34294
   435
        print_typ (INFX (1, R)) ty2
haftmann@34294
   436
      ]))
haftmann@34294
   437
  #> fold (Code_Target.add_reserved target) [
haftmann@34294
   438
      "abstract", "case", "catch", "class", "def", "do", "else", "extends", "false",
haftmann@34294
   439
      "final", "finally", "for", "forSome", "if", "implicit", "import", "lazy",
haftmann@34294
   440
      "match", "new", "null", "object", "override", "package", "private", "protected",
haftmann@34294
   441
      "requires", "return", "sealed", "super", "this", "throw", "trait", "try",
haftmann@34294
   442
      "true", "type", "val", "var", "while", "with"
haftmann@34294
   443
    ]
haftmann@34294
   444
  #> fold (Code_Target.add_reserved target) [
haftmann@34888
   445
      "error", "apply", "List", "Nil"
haftmann@34294
   446
    ];
haftmann@34294
   447
haftmann@34294
   448
end; (*struct*)