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