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