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