src/Tools/Code/code_scala.ML
author haftmann
Thu Aug 26 12:30:43 2010 +0200 (2010-08-26)
changeset 38778 49b885736e8f
parent 38772 eb7bc47f062b
child 38779 89f654951200
permissions -rw-r--r--
private version of commas, cf. printmode
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@37464
    27
fun print_scala_stmt labelled_name syntax_tyco syntax_const reserved
haftmann@37639
    28
    args_num is_singleton_constr deresolve =
haftmann@34294
    29
  let
haftmann@34294
    30
    val deresolve_base = Long_Name.base_name o deresolve;
haftmann@37639
    31
    fun lookup_tyvar tyvars = lookup_var tyvars o first_upper;
haftmann@37639
    32
    fun intro_tyvars vs = intro_vars (map (first_upper o fst) vs);
haftmann@37639
    33
    fun print_tyco_expr tyvars fxy (tyco, tys) = applify "[" "]"
haftmann@37639
    34
          (print_typ tyvars NOBR) fxy ((str o deresolve) tyco) tys
haftmann@37639
    35
    and print_typ tyvars fxy (tyco `%% tys) = (case syntax_tyco tyco
haftmann@37639
    36
         of NONE => print_tyco_expr tyvars fxy (tyco, tys)
haftmann@34294
    37
          | SOME (i, print) => print (print_typ tyvars) fxy tys)
haftmann@37243
    38
      | print_typ tyvars fxy (ITyVar v) = (str o lookup_tyvar tyvars) v;
haftmann@37639
    39
    fun print_dicttyp tyvars (class, ty) = print_tyco_expr tyvars NOBR (class, [ty]);
haftmann@37639
    40
    fun print_tupled_typ tyvars ([], ty) =
haftmann@37639
    41
          print_typ tyvars NOBR ty
haftmann@37639
    42
      | print_tupled_typ tyvars ([ty1], ty2) =
haftmann@37639
    43
          concat [print_typ tyvars BR ty1, str "=>", print_typ tyvars NOBR ty2]
haftmann@37639
    44
      | print_tupled_typ tyvars (tys, ty) =
haftmann@37639
    45
          concat [enum "," "(" ")" (map (print_typ tyvars NOBR) tys),
haftmann@37639
    46
            str "=>", print_typ tyvars NOBR ty];
haftmann@37639
    47
    fun constraint p1 p2 = Pretty.block [p1, str ":", Pretty.brk 1, p2];
haftmann@34294
    48
    fun print_var vars NONE = str "_"
haftmann@34294
    49
      | print_var vars (SOME v) = (str o lookup_var vars) v
haftmann@35228
    50
    fun print_term tyvars is_pat some_thm vars fxy (IConst c) =
haftmann@35228
    51
          print_app tyvars is_pat some_thm vars fxy (c, [])
haftmann@35228
    52
      | print_term tyvars is_pat some_thm vars fxy (t as (t1 `$ t2)) =
haftmann@34294
    53
          (case Code_Thingol.unfold_const_app t
haftmann@35228
    54
           of SOME app => print_app tyvars is_pat some_thm vars fxy app
haftmann@37639
    55
            | _ => applify "(" ")" (print_term tyvars is_pat some_thm vars NOBR) fxy
haftmann@37639
    56
                (print_term tyvars is_pat some_thm vars BR t1) [t2])
haftmann@35228
    57
      | print_term tyvars is_pat some_thm vars fxy (IVar v) =
haftmann@34294
    58
          print_var vars v
haftmann@35228
    59
      | print_term tyvars is_pat some_thm vars fxy ((v, ty) `|=> t) =
haftmann@34294
    60
          let
haftmann@34294
    61
            val vars' = intro_vars (the_list v) vars;
haftmann@34294
    62
          in
haftmann@34294
    63
            concat [
haftmann@37639
    64
              enclose "(" ")" [constraint (print_var vars' v) (print_typ tyvars NOBR ty)],
haftmann@34294
    65
              str "=>",
haftmann@35228
    66
              print_term tyvars false some_thm vars' NOBR t
haftmann@34294
    67
            ]
haftmann@34294
    68
          end 
haftmann@35228
    69
      | print_term tyvars is_pat some_thm vars fxy (ICase (cases as (_, t0))) =
haftmann@34294
    70
          (case Code_Thingol.unfold_const_app t0
haftmann@34294
    71
           of SOME (c_ts as ((c, _), _)) => if is_none (syntax_const c)
haftmann@35228
    72
                then print_case tyvars some_thm vars fxy cases
haftmann@35228
    73
                else print_app tyvars is_pat some_thm vars fxy c_ts
haftmann@35228
    74
            | NONE => print_case tyvars some_thm vars fxy cases)
haftmann@37464
    75
    and print_app tyvars is_pat some_thm vars fxy
haftmann@37464
    76
        (app as ((c, ((arg_typs, _), function_typs)), ts)) =
haftmann@34294
    77
      let
haftmann@34294
    78
        val k = length ts;
haftmann@37450
    79
        val arg_typs' = if is_pat orelse
haftmann@37639
    80
          (is_none (syntax_const c) andalso is_singleton_constr c) then [] else arg_typs;
haftmann@37881
    81
        val (l, print') = case syntax_const c
haftmann@38059
    82
         of NONE => (args_num c, fn fxy => fn ts => applify "(" ")"
haftmann@37639
    83
              (print_term tyvars is_pat some_thm vars NOBR) fxy
haftmann@37639
    84
                (applify "[" "]" (print_typ tyvars NOBR)
haftmann@37639
    85
                  NOBR ((str o deresolve) c) arg_typs') ts)
haftmann@38059
    86
          | SOME (Plain_const_syntax (k, s)) => (k, fn fxy => fn ts => applify "(" ")"
haftmann@37881
    87
              (print_term tyvars is_pat some_thm vars NOBR) fxy
haftmann@37881
    88
                (applify "[" "]" (print_typ tyvars NOBR)
haftmann@37881
    89
                  NOBR (str s) arg_typs') ts)
haftmann@37881
    90
          | SOME (Complex_const_syntax (k, print)) =>
haftmann@38059
    91
              (k, fn fxy => fn ts => print (print_term tyvars is_pat some_thm) some_thm vars fxy
haftmann@37881
    92
                (ts ~~ take k function_typs))
haftmann@38059
    93
      in if k = l then print' fxy ts
haftmann@34294
    94
      else if k < l then
haftmann@35228
    95
        print_term tyvars is_pat some_thm vars fxy (Code_Thingol.eta_expand l app)
haftmann@34294
    96
      else let
haftmann@34294
    97
        val (ts1, ts23) = chop l ts;
haftmann@34294
    98
      in
haftmann@38059
    99
        Pretty.block (print' BR ts1 :: map (fn t => Pretty.block
haftmann@35228
   100
          [str ".apply(", print_term tyvars is_pat some_thm vars NOBR t, str ")"]) ts23)
haftmann@34294
   101
      end end
haftmann@37464
   102
    and print_bind tyvars some_thm fxy p =
haftmann@37464
   103
      gen_print_bind (print_term tyvars true) some_thm fxy p
haftmann@35228
   104
    and print_case tyvars some_thm vars fxy (cases as ((_, [_]), _)) =
haftmann@34294
   105
          let
haftmann@34294
   106
            val (binds, body) = Code_Thingol.unfold_let (ICase cases);
haftmann@38059
   107
            fun print_match ((IVar NONE, _), t) vars =
haftmann@38059
   108
                  ((true, print_term tyvars false some_thm vars NOBR t), vars)
haftmann@38059
   109
              | print_match ((pat, ty), t) vars =
haftmann@38059
   110
                  vars
haftmann@38059
   111
                  |> print_bind tyvars some_thm BR pat
haftmann@38059
   112
                  |>> (fn p => (false, concat [str "val", constraint p (print_typ tyvars NOBR ty),
haftmann@38059
   113
                      str "=", print_term tyvars false some_thm vars NOBR t]))
haftmann@38059
   114
            val (seps_ps, vars') = fold_map print_match binds vars;
haftmann@38059
   115
            val all_seps_ps = seps_ps @ [(true, print_term tyvars false some_thm vars' NOBR body)];
haftmann@38059
   116
            fun insert_seps [(_, p)] = [p]
haftmann@38059
   117
              | insert_seps ((_, p) :: (seps_ps as (sep, _) :: _)) =
haftmann@38059
   118
                  (if sep then Pretty.block [p, str ";"] else p) :: insert_seps seps_ps
haftmann@38059
   119
          in brackify_block fxy (str "{") (insert_seps all_seps_ps) (str "}")
haftmann@34294
   120
          end
haftmann@35228
   121
      | print_case tyvars some_thm vars fxy (((t, ty), clauses as _ :: _), _) =
haftmann@34294
   122
          let
haftmann@34294
   123
            fun print_select (pat, body) =
haftmann@34294
   124
              let
haftmann@37464
   125
                val (p_pat, vars') = print_bind tyvars some_thm NOBR pat vars;
haftmann@37464
   126
                val p_body = print_term tyvars false some_thm vars' NOBR body
haftmann@37464
   127
              in concat [str "case", p_pat, str "=>", p_body] end;
haftmann@34294
   128
          in brackify_block fxy
haftmann@35228
   129
            (concat [print_term tyvars false some_thm vars NOBR t, str "match", str "{"])
haftmann@34294
   130
            (map print_select clauses)
haftmann@34294
   131
            (str "}") 
haftmann@34294
   132
          end
haftmann@35228
   133
      | print_case tyvars some_thm vars fxy ((_, []), _) =
haftmann@34294
   134
          (brackify fxy o Pretty.breaks o map str) ["error(\"empty case\")"];
haftmann@37639
   135
    fun print_context tyvars vs name = applify "[" "]"
haftmann@37639
   136
      (fn (v, sort) => (Pretty.block o map str)
haftmann@37639
   137
        (lookup_tyvar tyvars v :: maps (fn sort => [": ", deresolve sort]) sort))
haftmann@38769
   138
          NOBR ((str o deresolve_base) name) vs;
haftmann@37639
   139
    fun print_defhead tyvars vars name vs params tys ty =
haftmann@37639
   140
      Pretty.block [str "def ", constraint (applify "(" ")" (fn (param, ty) =>
haftmann@37639
   141
        constraint ((str o lookup_var vars) param) (print_typ tyvars NOBR ty))
haftmann@37639
   142
          NOBR (print_context tyvars vs name) (params ~~ tys)) (print_typ tyvars NOBR ty),
haftmann@37639
   143
            str " ="];
haftmann@37639
   144
    fun print_def name (vs, ty) [] =
haftmann@37639
   145
          let
haftmann@37639
   146
            val (tys, ty') = Code_Thingol.unfold_fun ty;
haftmann@37639
   147
            val params = Name.invents (snd reserved) "a" (length tys);
haftmann@37639
   148
            val tyvars = intro_tyvars vs reserved;
haftmann@37639
   149
            val vars = intro_vars params reserved;
haftmann@37639
   150
          in
haftmann@37639
   151
            concat [print_defhead tyvars vars name vs params tys ty',
haftmann@37639
   152
              str ("error(\"" ^ name ^ "\")")]
haftmann@37639
   153
          end
haftmann@37639
   154
      | print_def name (vs, ty) eqs =
haftmann@37639
   155
          let
haftmann@37639
   156
            val tycos = fold (fn ((ts, t), _) =>
haftmann@37639
   157
              fold Code_Thingol.add_tyconames (t :: ts)) eqs [];
haftmann@37639
   158
            val tyvars = reserved
haftmann@37639
   159
              |> intro_base_names
haftmann@37639
   160
                   (is_none o syntax_tyco) deresolve tycos
haftmann@37639
   161
              |> intro_tyvars vs;
haftmann@37639
   162
            val simple = case eqs
haftmann@37639
   163
             of [((ts, _), _)] => forall Code_Thingol.is_IVar ts
haftmann@37639
   164
              | _ => false;
haftmann@37639
   165
            val consts = fold Code_Thingol.add_constnames
haftmann@37639
   166
              (map (snd o fst) eqs) [];
haftmann@37639
   167
            val vars1 = reserved
haftmann@37639
   168
              |> intro_base_names
haftmann@37639
   169
                   (is_none o syntax_const) deresolve consts
haftmann@37639
   170
            val params = if simple
haftmann@37639
   171
              then (map (fn IVar (SOME x) => x) o fst o fst o hd) eqs
haftmann@37639
   172
              else aux_params vars1 (map (fst o fst) eqs);
haftmann@37639
   173
            val vars2 = intro_vars params vars1;
haftmann@37639
   174
            val (tys', ty') = Code_Thingol.unfold_fun_n (length params) ty;
haftmann@37639
   175
            fun print_tuple [p] = p
haftmann@37639
   176
              | print_tuple ps = enum "," "(" ")" ps;
haftmann@37639
   177
            fun print_rhs vars' ((_, t), (some_thm, _)) =
haftmann@37639
   178
              print_term tyvars false some_thm vars' NOBR t;
haftmann@37639
   179
            fun print_clause (eq as ((ts, _), (some_thm, _))) =
haftmann@34294
   180
              let
haftmann@37639
   181
                val vars' = intro_vars ((fold o Code_Thingol.fold_varnames)
haftmann@37639
   182
                  (insert (op =)) ts []) vars1;
haftmann@37639
   183
              in
haftmann@37639
   184
                concat [str "case",
haftmann@37639
   185
                  print_tuple (map (print_term tyvars true some_thm vars' NOBR) ts),
haftmann@37639
   186
                  str "=>", print_rhs vars' eq]
haftmann@37639
   187
              end;
haftmann@37639
   188
            val head = print_defhead tyvars vars2 name vs params tys' ty';
haftmann@37639
   189
          in if simple then
haftmann@37639
   190
            concat [head, print_rhs vars2 (hd eqs)]
haftmann@37639
   191
          else
haftmann@37639
   192
            Pretty.block_enclose
haftmann@37639
   193
              (concat [head, print_tuple (map (str o lookup_var vars2) params),
haftmann@37639
   194
                str "match", str "{"], str "}")
haftmann@37639
   195
              (map print_clause eqs)
haftmann@37639
   196
          end;
haftmann@38769
   197
    val print_method = str o Library.enclose "`" "`" o space_implode "+"
haftmann@38769
   198
      o fst o split_last o Long_Name.explode;
haftmann@37639
   199
    fun print_stmt (name, Code_Thingol.Fun (_, (((vs, ty), raw_eqs), _))) =
haftmann@37639
   200
          print_def name (vs, ty) (filter (snd o snd) raw_eqs)
haftmann@34294
   201
      | print_stmt (name, Code_Thingol.Datatype (_, (vs, cos))) =
haftmann@34294
   202
          let
haftmann@37639
   203
            val tyvars = intro_tyvars vs reserved;
haftmann@37450
   204
            fun print_co ((co, _), []) =
haftmann@34294
   205
                  concat [str "final", str "case", str "object", (str o deresolve_base) co,
haftmann@37639
   206
                    str "extends", applify "[" "]" I NOBR ((str o deresolve_base) name)
haftmann@34294
   207
                      (replicate (length vs) (str "Nothing"))]
haftmann@37450
   208
              | print_co ((co, vs_args), tys) =
haftmann@37639
   209
                  concat [applify "(" ")"
haftmann@37639
   210
                    (fn (v, arg) => constraint (str v) (print_typ tyvars NOBR arg)) NOBR
haftmann@37639
   211
                    (applify "[" "]" (str o lookup_tyvar tyvars) NOBR ((concat o map str)
haftmann@37639
   212
                      ["final", "case", "class", deresolve_base co]) vs_args)
haftmann@37639
   213
                    (Name.names (snd reserved) "a" tys),
haftmann@37639
   214
                    str "extends",
haftmann@37639
   215
                    applify "[" "]" (str o lookup_tyvar tyvars o fst) NOBR
haftmann@37639
   216
                      ((str o deresolve_base) name) vs
haftmann@37639
   217
                  ];
haftmann@34294
   218
          in
haftmann@37639
   219
            Pretty.chunks (applify "[" "]" (str o prefix "+" o lookup_tyvar tyvars o fst)
haftmann@37893
   220
              NOBR ((concat o map str) ["abstract", "sealed", "class", deresolve_base name]) vs
haftmann@37639
   221
                :: map print_co cos)
haftmann@34294
   222
          end
haftmann@37447
   223
      | print_stmt (name, Code_Thingol.Class (_, (v, (super_classes, classparams)))) =
haftmann@34294
   224
          let
haftmann@37639
   225
            val tyvars = intro_tyvars [(v, [name])] reserved;
haftmann@37639
   226
            fun add_typarg s = Pretty.block
haftmann@37639
   227
              [str s, str "[", (str o lookup_tyvar tyvars) v, str "]"];
haftmann@37384
   228
            fun print_super_classes [] = NONE
haftmann@37384
   229
              | print_super_classes classes = SOME (concat (str "extends"
haftmann@37639
   230
                  :: separate (str "with") (map (add_typarg o deresolve o fst) classes)));
haftmann@34294
   231
            fun print_classparam_val (classparam, ty) =
haftmann@37639
   232
              concat [str "val", constraint (print_method classparam)
haftmann@37639
   233
                ((print_tupled_typ tyvars o Code_Thingol.unfold_fun) ty)];
haftmann@34294
   234
            fun print_classparam_def (classparam, ty) =
haftmann@34294
   235
              let
haftmann@34294
   236
                val (tys, ty) = Code_Thingol.unfold_fun ty;
haftmann@37639
   237
                val [implicit_name] = Name.invents (snd reserved) (lookup_tyvar tyvars v) 1;
haftmann@37639
   238
                val proto_vars = intro_vars [implicit_name] reserved;
haftmann@37639
   239
                val auxs = Name.invents (snd proto_vars) "a" (length tys);
haftmann@37639
   240
                val vars = intro_vars auxs proto_vars;
haftmann@34294
   241
              in
haftmann@37639
   242
                concat [str "def", constraint (Pretty.block [applify "(" ")"
haftmann@37639
   243
                  (fn (aux, ty) => constraint ((str o lookup_var vars) aux)
haftmann@38769
   244
                  (print_typ tyvars NOBR ty)) NOBR (add_typarg (deresolve_base classparam))
haftmann@37639
   245
                  (auxs ~~ tys), str "(implicit ", str implicit_name, str ": ",
haftmann@37639
   246
                  add_typarg (deresolve name), str ")"]) (print_typ tyvars NOBR ty), str "=",
haftmann@37639
   247
                  applify "(" ")" (str o lookup_var vars) NOBR
haftmann@37639
   248
                  (Pretty.block [str implicit_name, str ".", print_method classparam]) auxs]
haftmann@34294
   249
              end;
haftmann@34294
   250
          in
haftmann@34294
   251
            Pretty.chunks (
haftmann@34294
   252
              (Pretty.block_enclose
haftmann@37639
   253
                (concat ([str "trait", (add_typarg o deresolve_base) name]
haftmann@37384
   254
                  @ the_list (print_super_classes super_classes) @ [str "{"]), str "}")
haftmann@34294
   255
                (map print_classparam_val classparams))
haftmann@34294
   256
              :: map print_classparam_def classparams
haftmann@34294
   257
            )
haftmann@34294
   258
          end
haftmann@34294
   259
      | print_stmt (name, Code_Thingol.Classinst ((class, (tyco, vs)),
haftmann@37450
   260
            (super_instances, (classparam_instances, further_classparam_instances)))) =
haftmann@34294
   261
          let
haftmann@37639
   262
            val tyvars = intro_tyvars vs reserved;
haftmann@37639
   263
            val classtyp = (class, tyco `%% map (ITyVar o fst) vs);
haftmann@37450
   264
            fun print_classparam_instance ((classparam, const as (_, (_, tys))), (thm, _)) =
haftmann@37450
   265
              let
haftmann@37639
   266
                val aux_tys = Name.names (snd reserved) "a" tys;
haftmann@37639
   267
                val auxs = map fst aux_tys;
haftmann@37450
   268
                val vars = intro_vars auxs reserved;
haftmann@37639
   269
                val aux_abstr = if null auxs then [] else [enum "," "(" ")"
haftmann@37639
   270
                  (map (fn (aux, ty) => constraint ((str o lookup_var vars) aux)
haftmann@37639
   271
                  (print_typ tyvars NOBR ty)) aux_tys), str "=>"];
haftmann@37450
   272
              in 
haftmann@37639
   273
                concat ([str "val", print_method classparam, str "="]
haftmann@37639
   274
                  @ aux_abstr @| print_app tyvars false (SOME thm) vars NOBR
haftmann@37639
   275
                    (const, map (IVar o SOME) auxs))
haftmann@37450
   276
              end;
haftmann@37639
   277
          in
haftmann@37639
   278
            Pretty.block_enclose (concat [str "implicit def",
haftmann@37639
   279
              constraint (print_context tyvars vs name) (print_dicttyp tyvars classtyp),
haftmann@37639
   280
              str "=", str "new", print_dicttyp tyvars classtyp, str "{"], str "}")
haftmann@37639
   281
                (map print_classparam_instance (classparam_instances @ further_classparam_instances))
haftmann@37639
   282
          end;
haftmann@34294
   283
  in print_stmt end;
haftmann@34294
   284
haftmann@38769
   285
local
haftmann@38769
   286
haftmann@38769
   287
(* hierarchical module name space *)
haftmann@38769
   288
haftmann@38769
   289
datatype node =
haftmann@38769
   290
    Dummy
haftmann@38769
   291
  | Stmt of Code_Thingol.stmt
haftmann@38769
   292
  | Module of ((Name.context * Name.context) * Name.context) * (string list * (string * node) Graph.T);
haftmann@38769
   293
haftmann@38769
   294
in
haftmann@38769
   295
haftmann@34294
   296
fun scala_program_of_program labelled_name module_name reserved raw_module_alias program =
haftmann@34294
   297
  let
haftmann@38769
   298
haftmann@38769
   299
    (* building module name hierarchy *)
haftmann@38769
   300
    val module_alias = if is_some module_name then K module_name else raw_module_alias;
haftmann@38769
   301
    fun alias_fragments name = case module_alias name
haftmann@38769
   302
     of SOME name' => Long_Name.explode name'
haftmann@38769
   303
      | NONE => map (fn name => fst (yield_singleton Name.variants name reserved))
haftmann@38769
   304
          (Long_Name.explode name);
haftmann@38769
   305
    val module_names = Graph.fold (insert (op =) o fst o dest_name o fst) program [];
haftmann@38769
   306
    val fragments_tab = fold (fn name => Symtab.update
haftmann@38769
   307
      (name, alias_fragments name)) module_names Symtab.empty;
haftmann@38769
   308
    val dest_name = Code_Printer.dest_name #>> (the o Symtab.lookup fragments_tab);
haftmann@38769
   309
haftmann@38769
   310
    (* building empty module hierarchy *)
haftmann@38769
   311
    val empty_module = (((reserved, reserved), reserved), ([], Graph.empty));
haftmann@38769
   312
    fun map_module f (Module content) = Module (f content);
haftmann@38769
   313
    fun declare_module name_fragement ((nsp_class, nsp_object), nsp_common) =
haftmann@34294
   314
      let
haftmann@38769
   315
        val declare = Name.declare name_fragement;
haftmann@38769
   316
      in ((declare nsp_class, declare nsp_object), declare nsp_common) end;
haftmann@38769
   317
    fun ensure_module name_fragement (nsps, (implicits, nodes)) =
haftmann@38769
   318
      if can (Graph.get_node nodes) name_fragement then (nsps, (implicits, nodes))
haftmann@38769
   319
      else
haftmann@38769
   320
        (nsps |> declare_module name_fragement, (implicits,
haftmann@38769
   321
          nodes |> Graph.new_node (name_fragement, (name_fragement, Module empty_module))));
haftmann@38769
   322
    fun allocate_module [] = I
haftmann@38769
   323
      | allocate_module (name_fragment :: name_fragments) =
haftmann@38769
   324
          ensure_module name_fragment
haftmann@38769
   325
          #> (apsnd o apsnd o Graph.map_node name_fragment o apsnd o map_module o allocate_module) name_fragments;
haftmann@38769
   326
    val empty_program = Symtab.fold (fn (_, fragments) => allocate_module fragments)
haftmann@38769
   327
      fragments_tab empty_module;
haftmann@38769
   328
    fun change_module [] = I
haftmann@38769
   329
      | change_module (name_fragment :: name_fragments) =
haftmann@38769
   330
          apsnd o apsnd o Graph.map_node name_fragment o apsnd o map_module
haftmann@38769
   331
            o change_module name_fragments;
haftmann@38769
   332
haftmann@38769
   333
    (* statement declaration *)
haftmann@38769
   334
    fun namify_class base ((nsp_class, nsp_object), nsp_common) =
haftmann@38769
   335
      let
haftmann@38769
   336
        val (base', nsp_class') = yield_singleton Name.variants base nsp_class
haftmann@38769
   337
      in (base', ((nsp_class', nsp_object), Name.declare base' nsp_common)) end;
haftmann@38769
   338
    fun namify_object base ((nsp_class, nsp_object), nsp_common) =
haftmann@38769
   339
      let
haftmann@38769
   340
        val (base', nsp_object') = yield_singleton Name.variants base nsp_object
haftmann@38769
   341
      in (base', ((nsp_class, nsp_object'), Name.declare base' nsp_common)) end;
haftmann@38769
   342
    fun namify_common upper base ((nsp_class, nsp_object), nsp_common) =
haftmann@38769
   343
      let
haftmann@38769
   344
        val (base', nsp_common') =
haftmann@38769
   345
          yield_singleton Name.variants (if upper then first_upper base else base) nsp_common
haftmann@38769
   346
      in
haftmann@38769
   347
        (base',
haftmann@38769
   348
          ((Name.declare base' nsp_class, Name.declare base' nsp_object), nsp_common'))
haftmann@38769
   349
      end;
haftmann@38769
   350
    fun declare_stmt name stmt =
haftmann@38769
   351
      let
haftmann@38769
   352
        val (name_fragments, base) = dest_name name;
haftmann@38769
   353
        val namify = case stmt
haftmann@38769
   354
         of Code_Thingol.Fun _ => namify_object
haftmann@38769
   355
          | Code_Thingol.Datatype _ => namify_class
haftmann@38769
   356
          | Code_Thingol.Datatypecons _ => namify_common true
haftmann@38769
   357
          | Code_Thingol.Class _ => namify_class
haftmann@38769
   358
          | Code_Thingol.Classrel _ => namify_object
haftmann@38769
   359
          | Code_Thingol.Classparam _ => namify_object
haftmann@38769
   360
          | Code_Thingol.Classinst _ => namify_common false;
haftmann@38769
   361
        val stmt' = case stmt
haftmann@38769
   362
         of Code_Thingol.Datatypecons _ => Dummy
haftmann@38769
   363
          | Code_Thingol.Classrel _ => Dummy
haftmann@38769
   364
          | Code_Thingol.Classparam _ => Dummy
haftmann@38769
   365
          | _ => Stmt stmt;
haftmann@38769
   366
        fun is_classinst stmt = case stmt
haftmann@38769
   367
         of Code_Thingol.Classinst _ => true
haftmann@38769
   368
          | _ => false;
haftmann@38769
   369
        val implicit_deps = filter (is_classinst o Graph.get_node program)
haftmann@38769
   370
          (Graph.imm_succs program name);
haftmann@38769
   371
        fun declaration (nsps, (implicits, nodes)) =
haftmann@34294
   372
          let
haftmann@38769
   373
            val (base', nsps') = namify base nsps;
haftmann@38769
   374
            val implicits' = union (op =) implicit_deps implicits;
haftmann@38769
   375
            val nodes' = Graph.new_node (name, (base', stmt')) nodes;
haftmann@38769
   376
          in (nsps', (implicits', nodes')) end;
haftmann@38769
   377
      in change_module name_fragments declaration end;
haftmann@38769
   378
haftmann@38769
   379
    (* dependencies *)
haftmann@38769
   380
    fun add_dependency name name' =
haftmann@38769
   381
      let
haftmann@38769
   382
        val (name_fragments, base) = dest_name name;
haftmann@38769
   383
        val (name_fragments', base') = dest_name name';
haftmann@38769
   384
        val (name_fragments_common, (diff, diff')) =
haftmann@38769
   385
          chop_prefix (op =) (name_fragments, name_fragments');
haftmann@38769
   386
        val dep = if null diff then (name, name') else (hd diff, hd diff')
haftmann@38769
   387
      in (change_module name_fragments_common o apsnd o apsnd) (Graph.add_edge dep) end;
haftmann@38769
   388
haftmann@38769
   389
    (* producing program *)
haftmann@38769
   390
    val (_, (_, sca_program)) = empty_program
haftmann@38769
   391
      |> Graph.fold (fn (name, (stmt, _)) => declare_stmt name stmt) program
haftmann@38769
   392
      |> Graph.fold (fn (name, (_, (_, names))) => fold (add_dependency name) names) program;
haftmann@38769
   393
haftmann@38769
   394
    (* deresolving *)
haftmann@38769
   395
    fun deresolve name =
haftmann@38769
   396
      let
haftmann@38769
   397
        val (name_fragments, _) = dest_name name;
haftmann@38769
   398
        val nodes = fold (fn name_fragement => fn nodes => case Graph.get_node nodes name_fragement
haftmann@38769
   399
         of (_, Module (_, (_, nodes))) => nodes) name_fragments sca_program;
haftmann@38769
   400
        val (base', _) = Graph.get_node nodes name;
haftmann@38769
   401
      in Long_Name.implode (name_fragments @ [base']) end
haftmann@38769
   402
        handle Graph.UNDEF _ => error ("Unknown statement name: " ^ labelled_name name);
haftmann@38769
   403
haftmann@38769
   404
  in (deresolve, sca_program) end;
haftmann@34294
   405
haftmann@34294
   406
fun serialize_scala raw_module_name labelled_name
haftmann@34294
   407
    raw_reserved includes raw_module_alias
haftmann@37464
   408
    _ syntax_tyco syntax_const (code_of_pretty, code_writeln)
haftmann@37464
   409
    program stmt_names destination =
haftmann@34294
   410
  let
haftmann@38769
   411
haftmann@38769
   412
    (* generic nonsense *)
haftmann@36535
   413
    val presentation_stmt_names = Code_Target.stmt_names_of_destination destination;
haftmann@36535
   414
    val module_name = if null presentation_stmt_names then raw_module_name else SOME "Code";
haftmann@38769
   415
haftmann@38769
   416
    (* preprocess program *)
haftmann@34294
   417
    val reserved = fold (insert (op =) o fst) includes raw_reserved;
haftmann@38769
   418
    val (deresolve, sca_program) = scala_program_of_program labelled_name
haftmann@38769
   419
      module_name (Name.make_context reserved) raw_module_alias program;
haftmann@38769
   420
haftmann@38769
   421
    (* print statements *)
haftmann@37639
   422
    fun lookup_constr tyco constr = case Graph.get_node program tyco
haftmann@37639
   423
     of Code_Thingol.Datatype (_, (_, constrs)) =>
haftmann@37639
   424
          the (AList.lookup (op = o apsnd fst) constrs constr);
haftmann@37639
   425
    fun classparams_of_class class = case Graph.get_node program class
haftmann@37639
   426
     of Code_Thingol.Class (_, (_, (_, classparams))) => classparams;
haftmann@34294
   427
    fun args_num c = case Graph.get_node program c
haftmann@37464
   428
     of Code_Thingol.Fun (_, (((_, ty), []), _)) =>
haftmann@37464
   429
          (length o fst o Code_Thingol.unfold_fun) ty
haftmann@37437
   430
      | Code_Thingol.Fun (_, ((_, ((ts, _), _) :: _), _)) => length ts
haftmann@37639
   431
      | Code_Thingol.Datatypecons (_, tyco) => length (lookup_constr tyco c)
haftmann@34294
   432
      | Code_Thingol.Classparam (_, class) =>
haftmann@37639
   433
          (length o fst o Code_Thingol.unfold_fun o the o AList.lookup (op =)
haftmann@37639
   434
            (classparams_of_class class)) c;
haftmann@37639
   435
    fun is_singleton_constr c = case Graph.get_node program c
haftmann@37639
   436
     of Code_Thingol.Datatypecons (_, tyco) => null (lookup_constr tyco c)
haftmann@34294
   437
      | _ => false;
haftmann@34294
   438
    val print_stmt = print_scala_stmt labelled_name syntax_tyco syntax_const
haftmann@38769
   439
      (make_vars reserved) args_num is_singleton_constr deresolve;
haftmann@38769
   440
haftmann@38769
   441
    (* print nodes *)
haftmann@38769
   442
    fun print_implicits [] = NONE
haftmann@38769
   443
      | print_implicits implicits = (SOME o Pretty.block)
haftmann@38778
   444
          (str "import /*implicits*/" :: Pretty.brk 1 :: commas (map (str o deresolve) implicits));
haftmann@38769
   445
    fun print_module base implicits p = Pretty.chunks2
haftmann@38769
   446
      ([str ("object " ^ base ^ " {")] @ the_list (print_implicits implicits)
haftmann@38769
   447
        @ [p, str ("} /* object " ^ base ^ " */")]);
haftmann@38769
   448
    fun print_node (_, Dummy) = NONE
haftmann@38772
   449
      | print_node (name, Stmt stmt) = if null presentation_stmt_names
haftmann@38772
   450
          orelse member (op =) presentation_stmt_names name
haftmann@38769
   451
          then SOME (print_stmt (name, stmt))
haftmann@38769
   452
          else NONE
haftmann@38769
   453
      | print_node (name, Module (_, (implicits, nodes))) = if null presentation_stmt_names
haftmann@38769
   454
          then case print_nodes nodes
haftmann@38769
   455
           of NONE => NONE
haftmann@38769
   456
            | SOME p => SOME (print_module (Long_Name.base_name name) implicits p)
haftmann@38769
   457
          else print_nodes nodes
haftmann@38769
   458
    and print_nodes nodes = let
haftmann@38769
   459
        val ps = map_filter (fn name => print_node (name,
haftmann@38769
   460
          snd (Graph.get_node nodes name)))
haftmann@38769
   461
            ((rev o flat o Graph.strong_conn) nodes);
haftmann@38769
   462
      in if null ps then NONE else SOME (Pretty.chunks2 ps) end;
haftmann@38769
   463
haftmann@38769
   464
    (* serialization *)
haftmann@38772
   465
    val p_includes = if null presentation_stmt_names
haftmann@38772
   466
      then map (fn (base, p) => print_module base [] p) includes else [];
haftmann@38772
   467
    val p = Pretty.chunks2 (p_includes @ the_list (print_nodes sca_program));
haftmann@34294
   468
  in
haftmann@37748
   469
    Code_Target.mk_serialization target
haftmann@38769
   470
      (fn NONE => code_writeln | SOME file => File.write file o code_of_pretty)
haftmann@38769
   471
      (rpair [] o code_of_pretty) p destination
haftmann@34294
   472
  end;
haftmann@34294
   473
haftmann@38769
   474
end; (*local*)
haftmann@38769
   475
haftmann@34294
   476
val literals = let
haftmann@37224
   477
  fun char_scala c = if c = "'" then "\\'"
haftmann@37224
   478
    else if c = "\"" then "\\\""
haftmann@37224
   479
    else if c = "\\" then "\\\\"
haftmann@37224
   480
    else let val k = ord c
haftmann@37224
   481
    in if k < 32 orelse k > 126 then "\\" ^ radixstring (8, "0", k) else c end
haftmann@34944
   482
  fun numeral_scala k = if k < 0
haftmann@37958
   483
    then if k > ~ 2147483647 then "- " ^ string_of_int (~ k)
haftmann@34944
   484
      else quote ("- " ^ string_of_int (~ k))
haftmann@34944
   485
    else if k <= 2147483647 then string_of_int k
haftmann@34944
   486
      else quote (string_of_int k)
haftmann@34294
   487
in Literals {
haftmann@34294
   488
  literal_char = Library.enclose "'" "'" o char_scala,
haftmann@34294
   489
  literal_string = quote o translate_string char_scala,
haftmann@34944
   490
  literal_numeral = fn k => "BigInt(" ^ numeral_scala k ^ ")",
haftmann@38771
   491
  literal_positive_numeral = fn k => "Nat.Nat(" ^ numeral_scala k ^ ")",
haftmann@38771
   492
  literal_alternative_numeral = fn k => "Natural.Nat(" ^ numeral_scala k ^ ")",
haftmann@37958
   493
  literal_naive_numeral = fn k => "BigInt(" ^ numeral_scala k ^ ")",
haftmann@34888
   494
  literal_list = fn [] => str "Nil" | ps => Pretty.block [str "List", enum "," "(" ")" ps],
haftmann@34294
   495
  infix_cons = (6, "::")
haftmann@34294
   496
} end;
haftmann@34294
   497
haftmann@34294
   498
haftmann@34294
   499
(** Isar setup **)
haftmann@34294
   500
haftmann@37821
   501
fun isar_serializer module_name =
haftmann@34294
   502
  Code_Target.parse_args (Scan.succeed ())
haftmann@34294
   503
  #> (fn () => serialize_scala module_name);
haftmann@34294
   504
haftmann@34294
   505
val setup =
haftmann@37821
   506
  Code_Target.add_target
haftmann@37822
   507
    (target, { serializer = isar_serializer, literals = literals,
haftmann@38769
   508
      check = { env_var = "SCALA_HOME", make_destination = fn p => Path.append p (Path.explode "ROOT.scala"),
haftmann@37822
   509
        make_command = fn scala_home => fn p => fn _ =>
haftmann@37932
   510
          "export JAVA_OPTS='-Xms128m -Xmx512m -Xss2m' && "
haftmann@38769
   511
            ^ Path.implode (Path.append (Path.explode scala_home) (Path.explode "bin/scalac")) ^ " " ^ File.shell_path p } })
haftmann@37464
   512
  #> Code_Target.add_syntax_tyco target "fun"
haftmann@37464
   513
     (SOME (2, fn print_typ => fn fxy => fn [ty1, ty2] =>
haftmann@37464
   514
        brackify_infix (1, R) fxy (
haftmann@37464
   515
          print_typ BR ty1 (*product type vs. tupled arguments!*),
haftmann@37464
   516
          str "=>",
haftmann@37464
   517
          print_typ (INFX (1, R)) ty2
haftmann@37464
   518
        )))
haftmann@34294
   519
  #> fold (Code_Target.add_reserved target) [
haftmann@34294
   520
      "abstract", "case", "catch", "class", "def", "do", "else", "extends", "false",
haftmann@34294
   521
      "final", "finally", "for", "forSome", "if", "implicit", "import", "lazy",
haftmann@34294
   522
      "match", "new", "null", "object", "override", "package", "private", "protected",
haftmann@34294
   523
      "requires", "return", "sealed", "super", "this", "throw", "trait", "try",
haftmann@37243
   524
      "true", "type", "val", "var", "while", "with", "yield"
haftmann@34294
   525
    ]
haftmann@34294
   526
  #> fold (Code_Target.add_reserved target) [
haftmann@37639
   527
      "apply", "error", "BigInt", "Nil", "List"
haftmann@34294
   528
    ];
haftmann@34294
   529
haftmann@34294
   530
end; (*struct*)