src/Tools/Code/code_scala.ML
author haftmann
Fri Dec 05 19:35:36 2014 +0100 (2014-12-05)
changeset 59104 a14475f044b2
parent 58520 a4d1f8041af0
child 59323 468bd3aedfa1
permissions -rw-r--r--
allow multiple inheritance of targets
haftmann@37745
     1
(*  Title:      Tools/Code/code_scala.ML
haftmann@37745
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@34294
     3
haftmann@34294
     4
Serializer for Scala.
haftmann@34294
     5
*)
haftmann@34294
     6
haftmann@34294
     7
signature CODE_SCALA =
haftmann@34294
     8
sig
haftmann@37745
     9
  val target: string
haftmann@58520
    10
  val case_insensitive: bool Config.T;
haftmann@34294
    11
  val setup: theory -> theory
haftmann@34294
    12
end;
haftmann@34294
    13
haftmann@34294
    14
structure Code_Scala : CODE_SCALA =
haftmann@34294
    15
struct
haftmann@34294
    16
haftmann@34294
    17
val target = "Scala";
haftmann@34294
    18
haftmann@55150
    19
open Basic_Code_Symbol;
haftmann@34294
    20
open Basic_Code_Thingol;
haftmann@34294
    21
open Code_Printer;
haftmann@34294
    22
haftmann@34294
    23
infixr 5 @@;
haftmann@34294
    24
infixr 5 @|;
haftmann@34294
    25
haftmann@58520
    26
(** preliminary: option to circumvent clashes on case-insensitive file systems **)
haftmann@58520
    27
haftmann@58520
    28
val case_insensitive = Attrib.setup_config_bool @{binding "scala_case_insensitive"} (K false);
haftmann@58520
    29
haftmann@34294
    30
haftmann@34294
    31
(** Scala serializer **)
haftmann@34294
    32
haftmann@47609
    33
fun print_scala_stmt tyco_syntax const_syntax reserved
haftmann@50626
    34
    args_num is_constr (deresolve, deresolve_full) =
haftmann@34294
    35
  let
haftmann@55150
    36
    val deresolve_const = deresolve o Constant;
haftmann@55150
    37
    val deresolve_tyco = deresolve o Type_Constructor;
haftmann@55150
    38
    val deresolve_class = deresolve o Type_Class;
haftmann@56812
    39
    fun lookup_tyvar tyvars = lookup_var tyvars o Name.enforce_case true;
haftmann@56812
    40
    fun intro_tyvars vs = intro_vars (map (Name.enforce_case true o fst) vs);
haftmann@55147
    41
    fun print_tyco_expr tyvars fxy (sym, tys) = applify "[" "]"
haftmann@55147
    42
          (print_typ tyvars NOBR) fxy ((str o deresolve) sym) tys
haftmann@38923
    43
    and print_typ tyvars fxy (tyco `%% tys) = (case tyco_syntax tyco
haftmann@55150
    44
         of NONE => print_tyco_expr tyvars fxy (Type_Constructor tyco, tys)
haftmann@47609
    45
          | SOME (_, print) => print (print_typ tyvars) fxy tys)
haftmann@37243
    46
      | print_typ tyvars fxy (ITyVar v) = (str o lookup_tyvar tyvars) v;
haftmann@55150
    47
    fun print_dicttyp tyvars (class, ty) = print_tyco_expr tyvars NOBR (Type_Class class, [ty]);
haftmann@37639
    48
    fun print_tupled_typ tyvars ([], ty) =
haftmann@37639
    49
          print_typ tyvars NOBR ty
haftmann@37639
    50
      | print_tupled_typ tyvars ([ty1], ty2) =
haftmann@37639
    51
          concat [print_typ tyvars BR ty1, str "=>", print_typ tyvars NOBR ty2]
haftmann@37639
    52
      | print_tupled_typ tyvars (tys, ty) =
haftmann@37639
    53
          concat [enum "," "(" ")" (map (print_typ tyvars NOBR) tys),
haftmann@37639
    54
            str "=>", print_typ tyvars NOBR ty];
haftmann@37639
    55
    fun constraint p1 p2 = Pretty.block [p1, str ":", Pretty.brk 1, p2];
haftmann@34294
    56
    fun print_var vars NONE = str "_"
haftmann@34294
    57
      | print_var vars (SOME v) = (str o lookup_var vars) v
haftmann@48072
    58
    fun print_term tyvars is_pat some_thm vars fxy (IConst const) =
haftmann@48072
    59
          print_app tyvars is_pat some_thm vars fxy (const, [])
haftmann@35228
    60
      | print_term tyvars is_pat some_thm vars fxy (t as (t1 `$ t2)) =
haftmann@34294
    61
          (case Code_Thingol.unfold_const_app t
haftmann@35228
    62
           of SOME app => print_app tyvars is_pat some_thm vars fxy app
haftmann@37639
    63
            | _ => applify "(" ")" (print_term tyvars is_pat some_thm vars NOBR) fxy
haftmann@37639
    64
                (print_term tyvars is_pat some_thm vars BR t1) [t2])
haftmann@35228
    65
      | print_term tyvars is_pat some_thm vars fxy (IVar v) =
haftmann@34294
    66
          print_var vars v
haftmann@35228
    67
      | print_term tyvars is_pat some_thm vars fxy ((v, ty) `|=> t) =
haftmann@34294
    68
          let
haftmann@34294
    69
            val vars' = intro_vars (the_list v) vars;
haftmann@34294
    70
          in
haftmann@34294
    71
            concat [
haftmann@37639
    72
              enclose "(" ")" [constraint (print_var vars' v) (print_typ tyvars NOBR ty)],
haftmann@34294
    73
              str "=>",
haftmann@35228
    74
              print_term tyvars false some_thm vars' NOBR t
haftmann@34294
    75
            ]
wenzelm@41939
    76
          end
haftmann@48072
    77
      | print_term tyvars is_pat some_thm vars fxy (ICase case_expr) =
haftmann@48072
    78
          (case Code_Thingol.unfold_const_app (#primitive case_expr)
haftmann@55150
    79
           of SOME (app as ({ sym = Constant const, ... }, _)) =>
haftmann@55147
    80
                if is_none (const_syntax const)
haftmann@48072
    81
                then print_case tyvars some_thm vars fxy case_expr
haftmann@48072
    82
                else print_app tyvars is_pat some_thm vars fxy app
haftmann@48072
    83
            | NONE => print_case tyvars some_thm vars fxy case_expr)
haftmann@37464
    84
    and print_app tyvars is_pat some_thm vars fxy
haftmann@55147
    85
        (app as ({ sym, typargs, dom, ... }, ts)) =
haftmann@34294
    86
      let
haftmann@34294
    87
        val k = length ts;
haftmann@50626
    88
        val typargs' = if is_pat then [] else typargs;
haftmann@55147
    89
        val syntax = case sym of
haftmann@55150
    90
            Constant const => const_syntax const
haftmann@55147
    91
          | _ => NONE;
haftmann@55147
    92
        val (l, print') = case syntax of
haftmann@55147
    93
            NONE => (args_num sym, fn fxy => fn ts => gen_applify (is_constr sym) "(" ")"
haftmann@37639
    94
              (print_term tyvars is_pat some_thm vars NOBR) fxy
haftmann@37639
    95
                (applify "[" "]" (print_typ tyvars NOBR)
haftmann@55147
    96
                  NOBR ((str o deresolve) sym) typargs') ts)
haftmann@55153
    97
          | SOME (k, Plain_printer s) => (k, fn fxy => fn ts => applify "(" ")"
haftmann@37881
    98
              (print_term tyvars is_pat some_thm vars NOBR) fxy
haftmann@37881
    99
                (applify "[" "]" (print_typ tyvars NOBR)
haftmann@48072
   100
                  NOBR (str s) typargs') ts)
haftmann@55153
   101
          | SOME (k, Complex_printer print) =>
haftmann@38059
   102
              (k, fn fxy => fn ts => print (print_term tyvars is_pat some_thm) some_thm vars fxy
haftmann@48072
   103
                (ts ~~ take k dom))
haftmann@38059
   104
      in if k = l then print' fxy ts
haftmann@34294
   105
      else if k < l then
haftmann@35228
   106
        print_term tyvars is_pat some_thm vars fxy (Code_Thingol.eta_expand l app)
haftmann@34294
   107
      else let
haftmann@34294
   108
        val (ts1, ts23) = chop l ts;
haftmann@34294
   109
      in
haftmann@38059
   110
        Pretty.block (print' BR ts1 :: map (fn t => Pretty.block
haftmann@35228
   111
          [str ".apply(", print_term tyvars is_pat some_thm vars NOBR t, str ")"]) ts23)
haftmann@34294
   112
      end end
haftmann@37464
   113
    and print_bind tyvars some_thm fxy p =
haftmann@37464
   114
      gen_print_bind (print_term tyvars true) some_thm fxy p
haftmann@48072
   115
    and print_case tyvars some_thm vars fxy { clauses = [], ... } =
haftmann@48073
   116
          (brackify fxy o Pretty.breaks o map str) ["sys.error(\"empty case\")"]
haftmann@48072
   117
      | print_case tyvars some_thm vars fxy (case_expr as { clauses = [_], ... }) =
haftmann@34294
   118
          let
haftmann@48072
   119
            val (bind :: binds, body) = Code_Thingol.unfold_let (ICase case_expr);
haftmann@41781
   120
            fun print_match_val ((pat, ty), t) vars =
haftmann@41781
   121
              vars
haftmann@41781
   122
              |> print_bind tyvars some_thm BR pat
haftmann@41781
   123
              |>> (fn p => (false, concat [str "val", constraint p (print_typ tyvars NOBR ty),
haftmann@41781
   124
                  str "=", print_term tyvars false some_thm vars NOBR t]));
haftmann@41781
   125
            fun print_match_seq t vars =
haftmann@41781
   126
              ((true, print_term tyvars false some_thm vars NOBR t), vars);
haftmann@41781
   127
            fun print_match is_first ((IVar NONE, ty), t) =
haftmann@41784
   128
                  if Code_Thingol.is_IAbs t andalso is_first
haftmann@41781
   129
                    then print_match_val ((IVar NONE, ty), t)
haftmann@41781
   130
                    else print_match_seq t
haftmann@41781
   131
              | print_match _ ((pat, ty), t) =
haftmann@41781
   132
                  print_match_val ((pat, ty), t);
haftmann@41781
   133
            val (seps_ps, vars') =
haftmann@41781
   134
              vars |> print_match true bind ||>> fold_map (print_match false) binds |>> uncurry cons;
haftmann@38059
   135
            val all_seps_ps = seps_ps @ [(true, print_term tyvars false some_thm vars' NOBR body)];
haftmann@38059
   136
            fun insert_seps [(_, p)] = [p]
haftmann@38059
   137
              | insert_seps ((_, p) :: (seps_ps as (sep, _) :: _)) =
haftmann@38059
   138
                  (if sep then Pretty.block [p, str ";"] else p) :: insert_seps seps_ps
haftmann@41781
   139
          in brackify_block fxy (str "{") (insert_seps all_seps_ps) (str "}") end
haftmann@48072
   140
      | print_case tyvars some_thm vars fxy { term = t, typ = ty, clauses = clauses as _ :: _, ... } =
haftmann@34294
   141
          let
haftmann@34294
   142
            fun print_select (pat, body) =
haftmann@34294
   143
              let
haftmann@37464
   144
                val (p_pat, vars') = print_bind tyvars some_thm NOBR pat vars;
haftmann@37464
   145
                val p_body = print_term tyvars false some_thm vars' NOBR body
haftmann@37464
   146
              in concat [str "case", p_pat, str "=>", p_body] end;
haftmann@46850
   147
          in
haftmann@46850
   148
            map print_select clauses
haftmann@46850
   149
            |> Pretty.block_enclose (concat [print_term tyvars false some_thm vars NOBR t, str "match", str "{"], str "}")
haftmann@46850
   150
            |> single
haftmann@46850
   151
            |> enclose "(" ")"
haftmann@48072
   152
          end;
haftmann@55147
   153
    fun print_context tyvars vs sym = applify "[" "]"
haftmann@37639
   154
      (fn (v, sort) => (Pretty.block o map str)
haftmann@55147
   155
        (lookup_tyvar tyvars v :: maps (fn class => [" : ", deresolve_class class]) sort))
haftmann@55147
   156
          NOBR ((str o deresolve) sym) vs;
haftmann@55679
   157
    fun print_defhead export tyvars vars const vs params tys ty =
haftmann@55776
   158
      concat [str "def", constraint (applify "(" ")" (fn (param, ty) =>
haftmann@37639
   159
        constraint ((str o lookup_var vars) param) (print_typ tyvars NOBR ty))
haftmann@55150
   160
          NOBR (print_context tyvars vs (Constant const)) (params ~~ tys)) (print_typ tyvars NOBR ty),
haftmann@55679
   161
            str "="];
haftmann@55679
   162
    fun print_def export const (vs, ty) [] =
haftmann@37639
   163
          let
haftmann@37639
   164
            val (tys, ty') = Code_Thingol.unfold_fun ty;
wenzelm@43329
   165
            val params = Name.invent (snd reserved) "a" (length tys);
haftmann@37639
   166
            val tyvars = intro_tyvars vs reserved;
haftmann@37639
   167
            val vars = intro_vars params reserved;
haftmann@37639
   168
          in
haftmann@55679
   169
            concat [print_defhead export tyvars vars const vs params tys ty',
haftmann@55147
   170
              str ("sys.error(\"" ^ const ^ "\")")]
haftmann@37639
   171
          end
haftmann@55679
   172
      | print_def export const (vs, ty) eqs =
haftmann@37639
   173
          let
haftmann@37639
   174
            val tycos = fold (fn ((ts, t), _) =>
haftmann@37639
   175
              fold Code_Thingol.add_tyconames (t :: ts)) eqs [];
haftmann@37639
   176
            val tyvars = reserved
haftmann@37639
   177
              |> intro_base_names
haftmann@55147
   178
                   (is_none o tyco_syntax) deresolve_tyco tycos
haftmann@37639
   179
              |> intro_tyvars vs;
haftmann@37639
   180
            val simple = case eqs
haftmann@37639
   181
             of [((ts, _), _)] => forall Code_Thingol.is_IVar ts
haftmann@37639
   182
              | _ => false;
haftmann@37639
   183
            val vars1 = reserved
haftmann@55145
   184
              |> intro_base_names_for (is_none o const_syntax)
haftmann@55145
   185
                   deresolve (map (snd o fst) eqs);
haftmann@37639
   186
            val params = if simple
haftmann@37639
   187
              then (map (fn IVar (SOME x) => x) o fst o fst o hd) eqs
haftmann@37639
   188
              else aux_params vars1 (map (fst o fst) eqs);
haftmann@37639
   189
            val vars2 = intro_vars params vars1;
haftmann@37639
   190
            val (tys', ty') = Code_Thingol.unfold_fun_n (length params) ty;
haftmann@38922
   191
            fun tuplify [p] = p
haftmann@38922
   192
              | tuplify ps = enum "," "(" ")" ps;
haftmann@37639
   193
            fun print_rhs vars' ((_, t), (some_thm, _)) =
haftmann@37639
   194
              print_term tyvars false some_thm vars' NOBR t;
haftmann@37639
   195
            fun print_clause (eq as ((ts, _), (some_thm, _))) =
haftmann@34294
   196
              let
haftmann@37639
   197
                val vars' = intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@37639
   198
                  (insert (op =)) ts []) vars1;
haftmann@37639
   199
              in
haftmann@37639
   200
                concat [str "case",
haftmann@38922
   201
                  tuplify (map (print_term tyvars true some_thm vars' NOBR) ts),
haftmann@37639
   202
                  str "=>", print_rhs vars' eq]
haftmann@37639
   203
              end;
haftmann@55679
   204
            val head = print_defhead export tyvars vars2 const vs params tys' ty';
haftmann@37639
   205
          in if simple then
haftmann@37639
   206
            concat [head, print_rhs vars2 (hd eqs)]
haftmann@37639
   207
          else
haftmann@37639
   208
            Pretty.block_enclose
haftmann@38922
   209
              (concat [head, tuplify (map (str o lookup_var vars2) params),
haftmann@37639
   210
                str "match", str "{"], str "}")
haftmann@37639
   211
              (map print_clause eqs)
haftmann@37639
   212
          end;
haftmann@55150
   213
    val print_method = str o Library.enclose "`" "`" o deresolve_full o Constant;
haftmann@55679
   214
    fun print_stmt (Constant const, (export, Code_Thingol.Fun (((vs, ty), raw_eqs), _))) =
haftmann@55679
   215
          print_def export const (vs, ty) (filter (snd o snd) raw_eqs)
haftmann@55679
   216
      | print_stmt (Type_Constructor tyco, (export, Code_Thingol.Datatype (vs, cos))) =
haftmann@34294
   217
          let
haftmann@48003
   218
            val tyvars = intro_tyvars (map (rpair []) vs) reserved;
haftmann@50626
   219
            fun print_co ((co, vs_args), tys) =
haftmann@50626
   220
              concat [Pretty.block ((applify "[" "]" (str o lookup_tyvar tyvars) NOBR
haftmann@55776
   221
                ((concat o map str) ["final", "case", "class", deresolve_const co]) vs_args)
haftmann@50626
   222
                @@ enum "," "(" ")" (map (fn (v, arg) => constraint (str v) (print_typ tyvars NOBR arg))
haftmann@50626
   223
                  (Name.invent_names (snd reserved) "a" tys))),
haftmann@50626
   224
                str "extends",
haftmann@50626
   225
                applify "[" "]" (str o lookup_tyvar tyvars) NOBR
haftmann@55147
   226
                  ((str o deresolve_tyco) tyco) vs
haftmann@50626
   227
              ];
haftmann@34294
   228
          in
haftmann@50626
   229
            Pretty.chunks (applify "[" "]" (str o lookup_tyvar tyvars)
haftmann@55776
   230
              NOBR ((concat o map str) ["abstract", "sealed", "class", deresolve_tyco tyco]) vs
haftmann@37639
   231
                :: map print_co cos)
haftmann@34294
   232
          end
haftmann@55679
   233
      | print_stmt (Type_Class class, (export, Code_Thingol.Class (v, (classrels, classparams)))) =
haftmann@34294
   234
          let
haftmann@55147
   235
            val tyvars = intro_tyvars [(v, [class])] reserved;
haftmann@37639
   236
            fun add_typarg s = Pretty.block
haftmann@37639
   237
              [str s, str "[", (str o lookup_tyvar tyvars) v, str "]"];
haftmann@37384
   238
            fun print_super_classes [] = NONE
haftmann@55147
   239
              | print_super_classes classrels = SOME (concat (str "extends"
haftmann@55147
   240
                  :: separate (str "with") (map (add_typarg o deresolve_class o snd) classrels)));
haftmann@34294
   241
            fun print_classparam_val (classparam, ty) =
haftmann@37639
   242
              concat [str "val", constraint (print_method classparam)
haftmann@37639
   243
                ((print_tupled_typ tyvars o Code_Thingol.unfold_fun) ty)];
haftmann@34294
   244
            fun print_classparam_def (classparam, ty) =
haftmann@34294
   245
              let
haftmann@34294
   246
                val (tys, ty) = Code_Thingol.unfold_fun ty;
wenzelm@43329
   247
                val [implicit_name] = Name.invent (snd reserved) (lookup_tyvar tyvars v) 1;
haftmann@37639
   248
                val proto_vars = intro_vars [implicit_name] reserved;
wenzelm@43329
   249
                val auxs = Name.invent (snd proto_vars) "a" (length tys);
haftmann@37639
   250
                val vars = intro_vars auxs proto_vars;
haftmann@34294
   251
              in
haftmann@55776
   252
                concat [str "def", constraint (Pretty.block [applify "(" ")"
haftmann@37639
   253
                  (fn (aux, ty) => constraint ((str o lookup_var vars) aux)
haftmann@55147
   254
                  (print_typ tyvars NOBR ty)) NOBR (add_typarg (deresolve_const classparam))
haftmann@37639
   255
                  (auxs ~~ tys), str "(implicit ", str implicit_name, str ": ",
haftmann@55147
   256
                  add_typarg (deresolve_class class), str ")"]) (print_typ tyvars NOBR ty), str "=",
haftmann@37639
   257
                  applify "(" ")" (str o lookup_var vars) NOBR
haftmann@37639
   258
                  (Pretty.block [str implicit_name, str ".", print_method classparam]) auxs]
haftmann@34294
   259
              end;
haftmann@34294
   260
          in
haftmann@34294
   261
            Pretty.chunks (
haftmann@34294
   262
              (Pretty.block_enclose
haftmann@55776
   263
                (concat ([str "trait", (add_typarg o deresolve_class) class]
haftmann@55147
   264
                  @ the_list (print_super_classes classrels) @ [str "{"]), str "}")
haftmann@34294
   265
                (map print_classparam_val classparams))
haftmann@34294
   266
              :: map print_classparam_def classparams
haftmann@34294
   267
            )
haftmann@34294
   268
          end
haftmann@55679
   269
      | print_stmt (sym, (export, Code_Thingol.Classinst
haftmann@55679
   270
          { class, tyco, vs, inst_params, superinst_params, ... })) =
haftmann@34294
   271
          let
haftmann@37639
   272
            val tyvars = intro_tyvars vs reserved;
haftmann@37639
   273
            val classtyp = (class, tyco `%% map (ITyVar o fst) vs);
haftmann@52520
   274
            fun print_classparam_instance ((classparam, (const as { dom, ... }, dom_length)), (thm, _)) =
haftmann@37450
   275
              let
haftmann@48072
   276
                val aux_dom = Name.invent_names (snd reserved) "a" dom;
haftmann@48072
   277
                val auxs = map fst aux_dom;
haftmann@37450
   278
                val vars = intro_vars auxs reserved;
haftmann@52520
   279
                val (aux_dom1, aux_dom2) = chop dom_length aux_dom;
haftmann@52520
   280
                fun abstract_using [] = []
haftmann@52520
   281
                  | abstract_using aux_dom = [enum "," "(" ")"
haftmann@52520
   282
                      (map (fn (aux, ty) => constraint ((str o lookup_var vars) aux)
haftmann@52520
   283
                      (print_typ tyvars NOBR ty)) aux_dom), str "=>"];
haftmann@52520
   284
                val aux_abstr1 = abstract_using aux_dom1;
haftmann@52520
   285
                val aux_abstr2 = abstract_using aux_dom2;
wenzelm@41939
   286
              in
haftmann@55684
   287
                concat ([str "val", print_method classparam, str "="]
haftmann@52520
   288
                  @ aux_abstr1 @ aux_abstr2 @| print_app tyvars false (SOME thm) vars NOBR
haftmann@37639
   289
                    (const, map (IVar o SOME) auxs))
haftmann@37450
   290
              end;
haftmann@37639
   291
          in
haftmann@55776
   292
            Pretty.block_enclose (concat [str "implicit def",
haftmann@55147
   293
              constraint (print_context tyvars vs sym) (print_dicttyp tyvars classtyp),
haftmann@37639
   294
              str "=", str "new", print_dicttyp tyvars classtyp, str "{"], str "}")
haftmann@48072
   295
                (map print_classparam_instance (inst_params @ superinst_params))
haftmann@37639
   296
          end;
haftmann@34294
   297
  in print_stmt end;
haftmann@34294
   298
haftmann@55683
   299
fun scala_program_of_program ctxt module_name reserved identifiers exports program =
haftmann@34294
   300
  let
haftmann@58520
   301
    val variant = if Config.get ctxt case_insensitive
haftmann@58520
   302
      then Code_Namespace.variant_case_insensitive
haftmann@58520
   303
      else Name.variant;
haftmann@38809
   304
    fun namify_module name_fragment ((nsp_class, nsp_object), nsp_common) =
haftmann@38809
   305
      let
haftmann@38809
   306
        val declare = Name.declare name_fragment;
haftmann@38809
   307
      in (name_fragment, ((declare nsp_class, declare nsp_object), declare nsp_common)) end;
haftmann@38769
   308
    fun namify_class base ((nsp_class, nsp_object), nsp_common) =
haftmann@38769
   309
      let
haftmann@58520
   310
        val (base', nsp_class') = variant base nsp_class
haftmann@38769
   311
      in (base', ((nsp_class', nsp_object), Name.declare base' nsp_common)) end;
haftmann@38769
   312
    fun namify_object base ((nsp_class, nsp_object), nsp_common) =
haftmann@38769
   313
      let
haftmann@58520
   314
        val (base', nsp_object') = variant base nsp_object
haftmann@38769
   315
      in (base', ((nsp_class, nsp_object'), Name.declare base' nsp_common)) end;
haftmann@56826
   316
    fun namify_common base ((nsp_class, nsp_object), nsp_common) =
haftmann@38769
   317
      let
haftmann@58520
   318
        val (base', nsp_common') = variant base nsp_common
haftmann@38769
   319
      in
haftmann@56826
   320
        (base', ((Name.declare base' nsp_class, Name.declare base' nsp_object), nsp_common'))
haftmann@38769
   321
      end;
haftmann@38809
   322
    fun namify_stmt (Code_Thingol.Fun _) = namify_object
haftmann@38809
   323
      | namify_stmt (Code_Thingol.Datatype _) = namify_class
haftmann@56826
   324
      | namify_stmt (Code_Thingol.Datatypecons _) = namify_common
haftmann@38809
   325
      | namify_stmt (Code_Thingol.Class _) = namify_class
haftmann@38809
   326
      | namify_stmt (Code_Thingol.Classrel _) = namify_object
haftmann@38809
   327
      | namify_stmt (Code_Thingol.Classparam _) = namify_object
haftmann@56826
   328
      | namify_stmt (Code_Thingol.Classinst _) = namify_common;
haftmann@55147
   329
    fun memorize_implicits sym =
haftmann@38769
   330
      let
haftmann@38970
   331
        fun is_classinst stmt = case stmt
haftmann@38970
   332
         of Code_Thingol.Classinst _ => true
haftmann@38970
   333
          | _ => false;
haftmann@55147
   334
        val implicits = filter (is_classinst o Code_Symbol.Graph.get_node program)
haftmann@55147
   335
          (Code_Symbol.Graph.immediate_succs program sym);
haftmann@38970
   336
      in union (op =) implicits end;
haftmann@55684
   337
    fun modify_stmt (_, (_, Code_Thingol.Fun (_, SOME _))) = NONE
haftmann@55684
   338
      | modify_stmt (_, (_, Code_Thingol.Datatypecons _)) = NONE
haftmann@55684
   339
      | modify_stmt (_, (_, Code_Thingol.Classrel _)) = NONE
haftmann@55684
   340
      | modify_stmt (_, (_, Code_Thingol.Classparam _)) = NONE
haftmann@55684
   341
      | modify_stmt (_, export_stmt) = SOME export_stmt;
haftmann@38970
   342
  in
haftmann@55147
   343
    Code_Namespace.hierarchical_program ctxt
haftmann@52138
   344
      { module_name = module_name, reserved = reserved, identifiers = identifiers,
wenzelm@41939
   345
        empty_nsp = ((reserved, reserved), reserved), namify_module = namify_module,
haftmann@55684
   346
        namify_stmt = namify_stmt, cyclic_modules = true,
haftmann@55684
   347
        class_transitive = true, class_relation_public = false, empty_data = [],
haftmann@55683
   348
        memorize_data = memorize_implicits, modify_stmts = map modify_stmt } exports program
haftmann@38970
   349
  end;
haftmann@34294
   350
haftmann@55147
   351
fun serialize_scala ctxt { module_name, reserved_syms, identifiers,
haftmann@55683
   352
    includes, class_syntax, tyco_syntax, const_syntax } exports program =
haftmann@34294
   353
  let
haftmann@38769
   354
haftmann@38809
   355
    (* build program *)
haftmann@39147
   356
    val { deresolver, hierarchical_program = scala_program } =
haftmann@55681
   357
      scala_program_of_program ctxt module_name (Name.make_context reserved_syms)
haftmann@55683
   358
        identifiers exports program;
haftmann@38769
   359
haftmann@38769
   360
    (* print statements *)
haftmann@55150
   361
    fun lookup_constr tyco constr = case Code_Symbol.Graph.get_node program (Type_Constructor tyco)
haftmann@55147
   362
     of Code_Thingol.Datatype (_, constrs) =>
haftmann@37639
   363
          the (AList.lookup (op = o apsnd fst) constrs constr);
haftmann@55150
   364
    fun classparams_of_class class = case Code_Symbol.Graph.get_node program (Type_Class class)
haftmann@55147
   365
     of Code_Thingol.Class (_, (_, classparams)) => classparams;
haftmann@55150
   366
    fun args_num (sym as Constant const) = case Code_Symbol.Graph.get_node program sym
haftmann@55147
   367
     of Code_Thingol.Fun (((_, ty), []), _) =>
haftmann@37464
   368
          (length o fst o Code_Thingol.unfold_fun) ty
haftmann@55147
   369
      | Code_Thingol.Fun ((_, ((ts, _), _) :: _), _) => length ts
haftmann@55147
   370
      | Code_Thingol.Datatypecons tyco => length (lookup_constr tyco const)
haftmann@55147
   371
      | Code_Thingol.Classparam class =>
haftmann@37639
   372
          (length o fst o Code_Thingol.unfold_fun o the o AList.lookup (op =)
haftmann@55147
   373
            (classparams_of_class class)) const;
haftmann@47609
   374
    fun print_stmt prefix_fragments = print_scala_stmt
haftmann@39147
   375
      tyco_syntax const_syntax (make_vars reserved_syms) args_num
haftmann@50626
   376
      (Code_Thingol.is_constr program) (deresolver prefix_fragments, deresolver []);
haftmann@38769
   377
haftmann@39147
   378
    (* print modules *)
haftmann@38809
   379
    fun print_implicit prefix_fragments implicit =
haftmann@38782
   380
      let
haftmann@38809
   381
        val s = deresolver prefix_fragments implicit;
haftmann@38782
   382
      in if length (Long_Name.explode s) = 1 then NONE else SOME (str s) end;
haftmann@39147
   383
    fun print_module prefix_fragments base implicits ps = Pretty.chunks2
haftmann@39147
   384
      ([str ("object " ^ base ^ " {")]
haftmann@39147
   385
        @ (case map_filter (print_implicit prefix_fragments) implicits
haftmann@39147
   386
            of [] => [] | implicit_ps => (single o Pretty.block)
haftmann@39147
   387
            (str "import /*implicits*/" :: Pretty.brk 1 :: commas implicit_ps))
haftmann@39147
   388
        @ ps @ [str ("} /* object " ^ base ^ " */")]);
haftmann@38769
   389
haftmann@38769
   390
    (* serialization *)
haftmann@39147
   391
    val p = Pretty.chunks2 (map snd includes
haftmann@39147
   392
      @ Code_Namespace.print_hierarchical {
haftmann@39147
   393
        print_module = print_module, print_stmt = print_stmt,
haftmann@39147
   394
        lift_markup = I } scala_program);
haftmann@39056
   395
    fun write width NONE = writeln o format [] width
haftmann@39056
   396
      | write width (SOME p) = File.write p o format [] width;
haftmann@55147
   397
    fun prepare syms width p = ([("", format syms width p)], try (deresolver []));
haftmann@34294
   398
  in
haftmann@48568
   399
    Code_Target.serialization write prepare p
haftmann@34294
   400
  end;
haftmann@34294
   401
haftmann@38966
   402
val serializer : Code_Target.serializer =
haftmann@38966
   403
  Code_Target.parse_args (Scan.succeed ()) #> K serialize_scala;
haftmann@38966
   404
haftmann@34294
   405
val literals = let
haftmann@37224
   406
  fun char_scala c = if c = "'" then "\\'"
haftmann@37224
   407
    else if c = "\"" then "\\\""
haftmann@37224
   408
    else if c = "\\" then "\\\\"
haftmann@37224
   409
    else let val k = ord c
haftmann@37224
   410
    in if k < 32 orelse k > 126 then "\\" ^ radixstring (8, "0", k) else c end
haftmann@58398
   411
  fun numeral_scala k =
haftmann@58398
   412
    if ~2147483647 < k andalso k <= 2147483647
haftmann@58398
   413
    then signed_string_of_int k
haftmann@58398
   414
    else quote (signed_string_of_int k)
haftmann@34294
   415
in Literals {
haftmann@34294
   416
  literal_char = Library.enclose "'" "'" o char_scala,
haftmann@34294
   417
  literal_string = quote o translate_string char_scala,
haftmann@34944
   418
  literal_numeral = fn k => "BigInt(" ^ numeral_scala k ^ ")",
haftmann@34888
   419
  literal_list = fn [] => str "Nil" | ps => Pretty.block [str "List", enum "," "(" ")" ps],
haftmann@34294
   420
  infix_cons = (6, "::")
haftmann@34294
   421
} end;
haftmann@34294
   422
haftmann@34294
   423
haftmann@34294
   424
(** Isar setup **)
haftmann@34294
   425
haftmann@34294
   426
val setup =
haftmann@59104
   427
  Code_Target.add_language
haftmann@38966
   428
    (target, { serializer = serializer, literals = literals,
wenzelm@41939
   429
      check = { env_var = "SCALA_HOME",
wenzelm@41939
   430
        make_destination = fn p => Path.append p (Path.explode "ROOT.scala"),
wenzelm@41940
   431
        make_command = fn _ =>
wenzelm@41940
   432
          "env JAVA_OPTS='-Xms128m -Xmx512m -Xss2m' \"$SCALA_HOME/bin/scalac\" ROOT.scala" } })
haftmann@55150
   433
  #> Code_Target.set_printings (Type_Constructor ("fun",
haftmann@52435
   434
    [(target, SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@52435
   435
      brackify_infix (1, R) fxy (
haftmann@52435
   436
        print_typ BR ty1 (*product type vs. tupled arguments!*),
haftmann@52435
   437
        str "=>",
haftmann@52435
   438
        print_typ (INFX (1, R)) ty2
haftmann@52435
   439
      )))]))
haftmann@34294
   440
  #> fold (Code_Target.add_reserved target) [
haftmann@34294
   441
      "abstract", "case", "catch", "class", "def", "do", "else", "extends", "false",
haftmann@34294
   442
      "final", "finally", "for", "forSome", "if", "implicit", "import", "lazy",
haftmann@34294
   443
      "match", "new", "null", "object", "override", "package", "private", "protected",
haftmann@34294
   444
      "requires", "return", "sealed", "super", "this", "throw", "trait", "try",
haftmann@37243
   445
      "true", "type", "val", "var", "while", "with", "yield"
haftmann@34294
   446
    ]
haftmann@34294
   447
  #> fold (Code_Target.add_reserved target) [
haftmann@48073
   448
      "apply", "sys", "scala", "BigInt", "Nil", "List"
haftmann@34294
   449
    ];
haftmann@34294
   450
haftmann@34294
   451
end; (*struct*)