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