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