Search code examples
scalacompiler-constructionprogram-entry-pointscalacscala-compiler

Main method invocation in scala nsc


I was trying to go through the code for nsc(new scala compiler). I am a little confused about Main.scala. It is implemented as follows:

/* NSC -- new Scala compiler
 * Copyright 2005-2013 LAMP/EPFL
 * @author  Martin Odersky
 */
package scala.tools
package nsc

import scala.language.postfixOps

/** The main class for NSC, a compiler for the programming
 *  language Scala.
 */
class MainClass extends Driver with EvalLoop {
  def resident(compiler: Global): Unit = loop { line =>
    val command = new CompilerCommand(line split "\\s+" toList, new Settings(scalacError))
    compiler.reporter.reset()
    new compiler.Run() compile command.files
  }

  override def newCompiler(): Global = Global(settings, reporter)
  override def doCompile(compiler: Global) {
    if (settings.resident) resident(compiler)
    else super.doCompile(compiler)
  }
}

object Main extends MainClass { }

My first question is, how is Main being called by the compiler process? When I call something along the lines of:

scalac [ <options> ] <source files>

Somewhere along the lines the newCompiler and doCompile is being called, can somebody help me with tracing through how this is being called and how the compiler is being initialized?

Any pointers will be much appreciated.

Thanks


Solution

  • MainClass extends Driver which has the main method:

    def main(args: Array[String]) {
      process(args)
      sys.exit(if (reporter.hasErrors) 1 else 0)
    }
    

    At the same time, object Main extends MainClass which means that there is a Main.class file that contains a public static void main(String[] args) forwarder method that actually invokes aforementioned non-static method on object Main. See for example this question for more details on how object is compiled in Scala.

    This means that scala.tools.nsc.Main can be used as a main class when running the scala compiler (this is hardcoded somewhere in the scalac script).

    newCompiler and doCompile are called by process.