A new way to compile

Together with the IDEA 12 release Scala plugin brings a brand new Scala compilation subsystem. Here are the main updates:

  • The compilation is now “external”.
  • Incremental compilation is now handled by SBT (instead of IDEA itself).
  • Compile server is now implemented via Nailgun (instead of FSC).

Of course, a lot of explanations is needed to clarify all the details.

External build

External build is a one of the major features of IntelliJ IDEA 12.

External build implies that all compilation tasks (including project model interpretation) are performed in a separate process, fully isolated from the main IDE’s process.

As a result, we can:

  • lower IDEA memory consumption and free its garbage collector;
  • reduce load on IDEA’s code model (PSI) and virtual file system (VFS);
  • speedup compilation (according to this and that).

Now we can compile IDEA projects without running IDEA itself, e. g. from command line or from build tools (like Ant, Maven, etc.).

An additional benefit is an ability to use an automatic background compilation, so that your project will be kept in compiled state all the time.

Background compilation can be also used as a means to reveal code errors when type-aware highlighting can’t keep up with code complexity.

For more information on external build you may check the Brand New Compiler Mode in IntelliJ IDEA 12 blog post.

SBT compiler

Although “SBT compiler” sounds like a completely new kind of Scala compiler, that is not really so. To see what SBT compiler is and how it fits into Scala compilation, let’s start with a “big picture”.

Here are the main tasks we need to perform during Scala project compilation:

  • We need to compile source code to bytecode (and to search for all kind of errors along the way). This task is always performed by Scalac (or Javac, for Java sources) no matter what tool is used to invoke it (IDE, SBT, Maven, Ant, Zinc or whatnot). So, Scalac (and Javac) is the actual “true” compiler, however it knows nothing about project structure, incremental compilation and so on. All it can do is to take a list of source files and produce a set of corresponding compiled classes.
  • We need to perform compilation incrementally (as opposed to compiling all sources all the time). Strictly speaking, this task is not required for project compilation (and it can even slow down a full project build). The whole point here is to save time during subsequent compilations. To do that, we need to track code changes and re-compile only affected files. And it is harder than it sounds — we need to monitor timestamps, store source-to-output mappings, check for public API changes, analyze direct and transitive dependencies (including ones between Scala and Java) and so on. There are not many tools capable of such a feat, and that is exactly what SBT “compiler” (as well as IDEA) does.
  • We need to compile project parts according to project structure i. e. to split project into separate, possibly dependent, modules of various types (test, production, resources, etc.), devise compilation order, apply compiler settings, provide required libraries and so on. Each tool (like IDEs, SBT, Maven, etc.) uses its own way of describing and storing project information.

So, bytecode is still generated by Scalac (and Javac), project format is still IDEA’s, but incremental compilation is now handled by SBT instead of IDEA (so, we don’t use SBT project model, only SBT compiler, that acts as a wrapper around Scalac).

What’s the point of such an update? – Because there is a qualitative difference between how IDEA and SBT discover dependencies and process changes.

IDEA analysis is bytecode-based and language-agnostic. While it’s a very fine-grained, robust and time-proved method, there may be some rare unexpected glitches, specific to Scala code.

For example, let’s define a class C (in C.scala):

and then “add” a method name via an implicit conversion (in Main.scala):

After we compile and run the main method, we will see that the output is “foo”, and that’s what we expect it to be.

Then, let’s add a “real” method name to the class C:

After the next compilation, we will discover that the output is … still “foo”, and that is is not what we expected… Why so? – Because, in terms of the bytecode, there’s no need to recompile Main class yet.

There are many additional cases (for example, related to named- and default parameters) which demonstrate, that bytecode analysis is not enough for proper incremental compilation of Scala code.

That is where SBT compiler comes to rescue, because it relies on source-based analysis of compiled code (to do that, SBT intercepts internal Scala compiler data), so it can take account of Scala-specific details to perform incremental compilation correctly (though SBT analysis of Java classes is still bytecode-based).

As a bonus, because SBT uses a so-called compiler interface layer to communicate with the Scala compiler, we can now run multiple versions of in-process Scala compilers in the same JVM. That’s how we can:

  • reap the benefit of JIT compilation (either during compilation of multiple modules or when using a compile server),
  • avoid creation of temporary files (with compiler arguments),
  • avoid compiler output parsing,
  • make compiler JVM parameters (in Scala facet) obsolete.

It’s worth noting, that there is a one side-effect of using SBT compiler, resulting in how Java files are handled in Scala projects (ones with a least one Scala facet). Because we need to maintain a coherent model of dependencies, compilation of all Java files, event in “pure” Java modules, is routed through SBT. For most use cases that is perfectly OK, unless you need to use a non-standard Java compiler (by the way, SBT supports in-process Java compiler as well).

For more information on SBT compiler you may check Understanding Incremental Recompilation article in SBT documentation.

New compile server

Scala compiler is a quite complex piece of software, so it takes time to load and initialize it. When you compile a project with hundreds (or thousands) of files, this time is negligible comparing to the time needed to compile the code. However, when incremental compilation is used, and all you need is to re-compile a few files, it may take longer to warm-up a Scala compiler than to actually compile those files.

One solution to this problem is to run Scala compiler in-process to avoid compiler re-instantiation when compiling subsequent modules. This, however, still cannot liberate us form a first compiler initialization. To speedup compilation further, we need to use a pre-initialized compiler instance, and that is exactly what compile server does.

Originally, Scala compile server was implemented via FSC (Fast Scala Compiler). While it works well enough, it has several limitations:

  • FSC instance is bound to a single compiler version, so compile server settings were a part of project configuration and FSC instances are not shared between projects.
  • Because FSC reuses symbol table between runs, it sometimes might produce various errors during compilation.

Now, because of our newfound ability to run multiple versions of Scala compiler in a single JVM, we can do better than that. New compile server is implemented using Nailgun (basically, it’s just a JVM process that can be accessed via a TCP/IP connection), so:

  • It is now a matter of personal preference whether or not to use a compile server. Compile server configuration is moved from project settings to application settings.
  • Compile server is now application-wide – it is reused for multiple compiler versions and shared between all projects (so we can save a lot of RAM).

Compile server configuration is now located in Settings / Scala:

It’s recommended to use the following JVM parameters for the Scala compile server:

  • -server – to maximize peak operating speed (for the price of longer start-up time) and to encourage soft references retention (that we use to cache compiler instances).
  • -XX:MaxPermSize=256m – to provide enough memory for loading of multiple sets of compiler classes.
  • -Xss1m – to ensure that there will be enough stack space for recursive code in Scala compiler.

If compile server is not used, it’s still recommended to use the same parameters (except, maybe, -server) in Project Settings / Compiler / Additional compiler process VM options.

How all this is related to Zinc

Zinc is a stand-alone launcher for SBT incremental compiler (and Nailgun server). It was created, primarily, to be used in command line tools (like Scala Maven Plugin).

Because both Zinc and the new compilation subsystem use the same tools and techniques, they are essentially equivalent. There is not much sense in using a launcher from another launcher, so we run both SBT compiler and Nailgun directly, rather than via Zinc.

Besides, we need much more data from the compiler (to display compilation messages, report progress, compile UI forms, run annotation processors, etc.) which is not available from Zinc output. Zinc’s Nailgun server also cannot be used by IDEA because its process is started without IDEA-specific classes (communication protocol) in JVM classpath.

As Zinc cannot build a project by itself, it must be invoked from another tool (like Maven), which stores all incremental compilation data using its own scheme, that differs from IDEA’s one. So, currently we cannot unite IDEA’s and Zinc/Maven’s incremental compilation even though they are very much alike.

Summary

Let’s sum-up all the advantages of the new Scala compilation subsystem:

  • Less load on IDEA process.
  • External project build.
  • Background compilation.
  • Source-based incremental compilation.
  • In-process Scala and Java compilers.
  • Simplified project configuration.
  • Application-wide compile server.

There must be a catch in it somewhere, you know… And here it is – because the new compilation subsystem is written completely from scratch, some bugs are simply inevitable. Please, report them so we can fix them as soon as possible.

Keep in mind, that the previous compilation subsystem is still available, and can be always turned on by clearing “Use external build” checkbox in Project Settings / Compiler page:

IDEA compiler configuration

You may also check there whether the external build is enabled in your existing projects.

For those who want to know even more details, here is source code for all the tools:

About Pavel Fatin

IntelliJ Scala plugin developer (http://pavelfatin.com)
This entry was posted in Uncategorized. Bookmark the permalink.

43 Responses to A new way to compile

  1. Good work guys!

    I’m looking forward to try new support.

    FSC used to eat tons of memory during often builds on several projects.
    If I understand correctly Nailgun should reuse some memory in single process?
    At least when the compilers for different modules are the same.

    Cheers

  2. Raman Gupta says:

    This is excellent. But yes, there are bugs :) I logged the first one I encountered here:

    http://youtrack.jetbrains.com/issue/SCL-5119

  3. Pingback: A new way to compile | IntelliJ Scala plugin blog | Stoneburners Blog

  4. Awesome! Definitely looking forward to working with it.

    I was unable to get existing projects to use it though, even if I removed the Scala facet and re-added it. The “Run compile server (in external build mode)” is checked. For existing projects under Project / Compiler / Scala it still has the old settings (Joint Compilation / Project FSC), instead of “Nothing to show here in external build mode”.

    Workaround is to remove .idea and reimport the project from the pom.xml.

  5. Emilio Lopez-Gabeiras says:

    How do you manage running a code generator using the new compilation subsystem ?
    (Say that you want to generate some code when a given file is modified)

  6. Mike Gehard says:

    Is this available with the Play2 plugin?

  7. Marc says:

    I second Mike Gehard — how does this interact with the Play2 plugin, since Play2 internally is based on SBT as well?

  8. Mark Harrah says:

    Nice writeup and nice work. Please let me know if there is something sbt can do to address issues with non-standard Java compilers.

  9. Ilya says:

    Now we can compile IDEA projects without running IDEA itself, e. g. from command line

    Can you please provide some links on compiling IDEA scala project from command line?

  10. Luke says:

    Does this do away with the need for the separate SBT plugin? (if so how so? i.e. how would I call SBT tasks directly?)

    Will IDEA use my build.sbt and build.scala files now?

    I currently use the gen-idea plugin to create IDEA projects from SBT build files, is functionality like this now available via the Intellij Scala plugin?

  11. Kostas Kougios says:

    But how about “compile independent modules in parallel”? This can’t be active in scala projects which makes big multi-module projects compilation slow.

  12. Kostas Kougios says:

    I can confirm that without parallel compilation (due to scala projects can’t have this enabled), compiling the project I work on is more than 2x slower (from 4 minutes to 9). On intellij 12.1.1.

  13. Kurt says:

    I get the following when using the external build with automake on:

    Automake is not supported with Scala compile server. Please either disable the compile server or turn off “Project Setings / Compiler / Make project automatically”.

    Automake used to work for me a few weeks ago. Not sure what has changed.

    • Kurt says:

      I may be a little confused here regarding the external build and the Scala compile server. The above error occurs when external-build, run-compile-server and automake are selected. How do you turn on automatic background compile when “Run compile server” is checked?

      sorry for the double post…

  14. Steve Turner says:

    Is it possible to run the build server on a different host? Would be great for remote building/debugging on different targets systems!

  15. I don’t know generate income appeared here, however idea this kind of publish was excellent. I really don’t understand who seem to you are and surely you will some sort of well-known blogger while you are certainly not already. Cheers!

  16. Stefan Endrullis says:

    I really appreciate your ongoing work on improving the Scala support in IDEA. However, in this case I regret the recent development. IDEA had a great support for fsc (fast scala compiler) and it worked very well. The full and incremental compilation was fast and usually without recompilation issues.

    Now you introduce a new compiler system and advertise it with “lower IDEA memory consumption”, “reduce load on IDEA’s code model”, and “seedup compilation” and I wonder what was your reference for that: the standard Scala compiler or fsc?

    When I switched from fsc to the new external build server I noticed a dramatic regression regarding compilation time for my projects. The time for incremental compilations (after changing one code line) rose from 8s (fsc) to incredible 21s (new compile server). And even the compile time for a complete rebuild was with fsc 20s faster than with the new compile system. I posted my results on http://devnet.jetbrains.com/message/5475005#5491387. And regression got confirmed by http://devnet.jetbrains.com/message/5474953#5474953 and is still present.

    As long as IDEA offered the option to switch back to fsc I didn’t care about this regression, but today after updating IDEA I regretfully noticed that this option has gone and we are forced to use the 2-3 time slower external compiler now. That’s really sad.

    So what about your claims?
    - “lower IDEA memory consumption” -> might be, but is definitely not significant (at least I don’t see it) regarding fsc
    - “reduce load on IDEA’s code model” -> I don’t see a difference. I could always work with IDEA while fsc was compiling.
    - “speedup compilation” -> That’s only true if you compare the new compiler regarding the standard scala compile (that nobody uses) but not fsc. And it’s probably true if you run the new compiler in parallel on multi module projects. But what’s the major benefit of that? The usual developer compiles his/her project around 100 times or more a day and does not work in multiple modules in parallel. He/she only wants a fast incremental compilation of the module he/she currently works on. And that’s exactly where the new compiler fails.

    I’m sure you had the best intentions when you wrote the new compiler and could prove the benefits for some (more theoretical) test cases. It’s a pity that those cases did not include the most common ones of daily use.

    For the future I hope that you manage to improve the compiler performance or bring back the old fsc integration again. However, IDEA is still the most advanced Scala IDE. I just don’t know if it’s worth to upgrade to IDEA 13.

  17. Pavel Fatin says:

    Hi Stefan! Thank you for the detailed comment. We’re aware of some issues with the SBT compiler, and we’re going to add an alternative to SBT compiler in IDEA 13 soon.

  18. jianhong.li says:

    from certain time. my intellijIdea does not work well with the “use external build” and i find “use external build” is a default select option.but from last friday.my svn resposity code is not working well will this option. when this option is selected .the compiler will compile nothing. and idea will start build artifact immediately.so ,what ‘s wrong with my config ?

  19. Pingback: Crazy IntelliJ with Play Integration | Leo's Aqu-Blog-Arium

  20. Jasper says:

    It’s perfect time to make some plans for the future and it is time to be happy.
    I have read this publish and if I could I wish
    to recommend you some interesting things or suggestions.

    Perhaps you could write next articles relating to this article.

    I desire to learn more issues approximately it!

  21. Thanks for every other informative website. Where else may I get that kind of info written in such a perfect way?

    I’ve a mission that I’m simply now working on, and I’ve been at the look out for such info.

  22. Heya i’m for the first time here. I found this board and I find It truly useful & it helped me
    out a lot. I hope to give something back and aid others like you helped me.

  23. It’s perfect time to make some plans for the future
    and it is time to be happy. I’ve read this post and if I could I wish to suggest you some interesting things or suggestions.

    Perhaps you could write next articles referring to this
    article. I want to read even more things about it!

  24. Useful info. Fortunate me I discovered your web site
    by accident, and I am stunned why this twist of fate didn’t happened in advance!
    I bookmarked it.

    My web page … Bicicletas electricas Cordoba

  25. On line coaching pertaining to school diplomas has a tendency to create
    exceptional outcomes regarding a number of factors. The availability of 4GB capacity in both the SD and SDHC
    families has caused much compatibility confusion with users since each has a slightly different communication protocol.
    The Pandora 3DS Card is highly compatible with the latestcommercial ROM’s.

  26. cheat osm says:

    I was suggested this web site by my cousin. I’m not sure whether this
    post is written by him as nobody else know such detailed about my difficulty.
    You’re amazing! Thanks!

  27. reklamy says:

    Do you have a spam problem on this blog; I also am a blogger,
    and I was wanting to know your situation; many of us have created some nice
    practices and we are looking to exchange strategies with others, be sure to shoot me an email if interested.

  28. I have not checked in here for some time because I thought it was getting boring, but the last few posts are great quality so I guess I will add you back to my everyday bloglist. You deserve it my friend

  29. Mika Mingee says:

    Good work! My order was delivered within a one week. I recommend

  30. judi bola says:

    I have learn ѕome ǥood stuff ɦere. Ɗefinitely
    worth bookmarking fߋr revisiting. I աonder
    how a lot effort уou set to create tɦe sort of
    greɑt infordmative web site.

    Feel free tօ surf to my homepage; judi bola

  31. Kareem says:

    The similar applies to this game as well and as a result most
    of the participants are often on the lookout for the right hack and tool selections to increase their strength and also appreciably increase the
    possibility of winning.

  32. Great article post.Much thanks again. Really Cool.

  33. andy says:

    10:39:48 AM Scala compile server: java.net.BindException: Address already in use: JVM_Bind
    at java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:96)
    at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:175)
    at java.net.ServerSocket.bind(ServerSocket.java:376)
    at java.net.ServerSocket.(ServerSocket.java:237)
    at com.martiansoftware.nailgun.NGServer.run(NGServer.java:413)
    at java.lang.Thread.run(Thread.java:722)

  34. “wow, awesome article.Much thanks again. Awesome.”

  35. Hey, you used to write great, but the last several posts have been kinda boringโ€ฆ I miss your super writings. Past few posts are just a bit out of track! come on!

  36. Enjoyed every bit of your article. Keep writing.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">