global.scala

来自「JAVA 语言的函数式编程扩展」· SCALA 代码 · 共 724 行 · 第 1/2 页

SCALA
724
字号
/* NSC -- new Scala compiler * Copyright 2005-2007 LAMP/EPFL * @author  Martin Odersky */// $Id: Global.scala 14599 2008-04-10 12:24:12Z odersky $package scala.tools.nscimport java.io.{File, FileOutputStream, PrintWriter}import java.io.{IOException, FileNotFoundException}import java.nio.charset._import compat.Platform.currentTimeimport scala.tools.nsc.io.{SourceReader, AbstractFile, PlainFile}import scala.tools.nsc.reporters._import scala.tools.nsc.util.{ClassPath, SourceFile, BatchSourceFile}import scala.collection.mutable.{HashSet, HashMap, ListBuffer}import symtab._import symtab.classfile.{PickleBuffer, Pickler}import util.Statisticsimport plugins.Pluginsimport ast._import ast.parser._import typechecker._//import matching.TransMatcherimport transform._import backend.icode.{ICodes, GenICode, Checkers}import backend.ScalaPrimitivesimport backend.jvm.GenJVMimport backend.msil.GenMSILimport backend.opt.{Inliners, ClosureElimination, DeadCodeElimination}import backend.icode.analysis._class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable                                                             with CompilationUnits                                                             with Plugins{  // alternate constructors ------------------------------------------  def this(reporter: Reporter) =    this(new Settings(err => reporter.error(null,err)),          reporter)  def this(settings: Settings) =    this(settings, new ConsoleReporter(settings))  //def this() = this(new Settings, new ConsoleReporter)  // sub-components --------------------------------------------------  object nodePrinters extends NodePrinters {    val global: Global.this.type = Global.this    infolevel = InfoLevel.Verbose  }  val nodeToString = nodePrinters.nodeToString  object gen extends TreeGen {    val global: Global.this.type = Global.this    def mkAttributedCast(tree: Tree, pt: Type): Tree =      typer.typed(mkAttributedCastUntyped(tree, pt))  }  object constfold extends ConstantFolder {    val global: Global.this.type = Global.this  }  object checker extends TreeCheckers {    val global: Global.this.type = Global.this  }  object icodes extends ICodes {    val global: Global.this.type = Global.this  }  object analysis extends TypeFlowAnalysis {    val global: Global.this.type = Global.this  }  object copyPropagation extends CopyPropagation {    val global: Global.this.type = Global.this  }  object checkers extends Checkers {    val global: Global.this.type = Global.this  }  object statistics extends Statistics {    val global: Global.this.type = Global.this  }  object overridingPairs extends OverridingPairs {    val global: Global.this.type = Global.this  }  object treeBrowsers extends TreeBrowsers {    val global: Global.this.type = Global.this  }  val treeBrowser = treeBrowsers.create()//  val copy = new LazyTreeCopier()  val comments =    if (onlyPresentation) new HashMap[Symbol,String]    else null  val methodArgumentNames =    if (onlyPresentation) new HashMap[Symbol,List[List[Symbol]]]    else null// reporting -------------------------------------------------------  import nsc.util.NoPosition  def error(msg: String) = reporter.error(NoPosition, msg)  def warning(msg: String) = reporter.warning(NoPosition, msg)  def inform(msg: String) = Console.err.println(msg)  def inform[T](msg: String, value: T): T = { inform(msg+value); value }  //reporter.info(null, msg, true)  def informProgress(msg: String) =    if (settings.verbose.value) inform("[" + msg + "]")  def informTime(msg: String, start: Long) =    informProgress(msg + " in " + (currentTime - start) + "ms")  def log(msg: AnyRef) {    if (settings.logAll.value || (settings.log contains phase.name))      inform("[log " + phase + "] " + msg)  }  class ErrorWithPosition(val pos: Int, val error: Throwable) extends Error  def tryWith[T](pos: Int, body: => T): T = try {    body  } catch {    case e : ErrorWithPosition => throw e    case te: TypeError => throw te    case e : Error            => throw new ErrorWithPosition(pos, e)    case e : RuntimeException => throw new ErrorWithPosition(pos, e)  }  def catchWith[T](source : SourceFile, body : => T) : T = try {    body  } catch {    case e : ErrorWithPosition =>      logError("POS: " + source.dbg(e.pos), e)      throw e.error  }  def logError(msg: String, t: Throwable): Unit = ()  def abort(msg: String) = throw new Error(msg)// file interface -------------------------------------------------------  private val reader: SourceReader = {    def stdCharset: Charset = {      settings.encoding.value = Properties.encodingString // A mandatory charset      Charset.forName(settings.encoding.value)    }    val charset =      try {        Charset.forName(settings.encoding.value)      } catch {        case _: IllegalCharsetNameException =>          error("illegal charset name '" + settings.encoding.value + "'")          stdCharset        case _: UnsupportedCharsetException =>          error("unsupported charset '" + settings.encoding.value + "'")          stdCharset      }    try {      val clazz = Class.forName(settings.sourceReader.value)      val ccon  = clazz.getConstructor(Array[Class[T] forSome { type T }](classOf[java.nio.charset.CharsetDecoder]))      ccon.newInstance(Array[AnyRef] (charset.newDecoder())).asInstanceOf[SourceReader];      //new SourceReader(charset.newDecoder())    } catch {      case e =>         error("exception while trying to instantiate source reader \""+settings.sourceReader.value+"\" ");        new SourceReader(charset.newDecoder())    }  }  lazy val classPath0 = new ClassPath(false && onlyPresentation)  lazy val classPath =    if (forMSIL)      new classPath0.Build(settings.sourcepath.value, settings.outdir.value)    else      new classPath0.Build(settings.classpath.value, settings.sourcepath.value,                           settings.outdir.value, settings.bootclasspath.value,                           settings.extdirs.value, settings.Xcodebase.value)  /* .NET's equivalent of a classpath */  lazy val assemrefs = {    import java.util.{StringTokenizer}    val set = new HashSet[File]      val assems = new StringTokenizer(settings.assemrefs.value, File.pathSeparator)    while (assems.hasMoreTokens())       set += new java.io.File(assems.nextToken())    set    }                             if (settings.verbose.value) {    inform("[Classpath = " + classPath + "]")    if (forMSIL) inform("[AssemRefs = " + settings.assemrefs.value + "]")  }  def getSourceFile(f: AbstractFile): SourceFile =    new BatchSourceFile(f, reader.read(f))  def getSourceFile(name: String): SourceFile = {    val f = AbstractFile.getFile(name)    if (f eq null) throw new FileNotFoundException(      "source file '" + name + "' could not be found")    getSourceFile(f)  }  def getSourceFile(clazz: Symbol): SourceFile = {    val ret = classPath.root.find(clazz.fullNameString(File.separatorChar), false)    if (!ret.isSourceFile) throw new FileNotFoundException(      "source file for " + clazz + " could not be found")    getSourceFile(ret.sourceFile)  }    val loaders = new SymbolLoaders {    lazy val global: Global.this.type = Global.this  }  def rootLoader: LazyType =    if (forMSIL) new loaders.NamespaceLoader(classPath.root)    else new loaders.PackageLoader(classPath.root /* getRoot() */)// Phases ------------------------------------------------------------  var globalPhase: Phase = NoPhase  val MaxPhases = 64  val phaseWithId = new Array[Phase](MaxPhases)  for (i <- List.range(0, MaxPhases)) phaseWithId(i) = NoPhase  abstract class GlobalPhase(prev: Phase) extends Phase(prev) {    phaseWithId(id) = this    def run { currentRun.units foreach applyPhase }    def apply(unit: CompilationUnit): Unit    private val isErased = prev.name == "erasure" || prev.erasedTypes    override def erasedTypes: Boolean = isErased    private val isFlat = prev.name == "flatten" || prev.flatClasses    override def flatClasses: Boolean = isFlat    final def applyPhase(unit: CompilationUnit) {      if (settings.debug.value) inform("[running phase " + name + " on " + unit + "]")      val unit0 = currentRun.currentUnit      currentRun.currentUnit = unit      reporter.setSource(unit.source)      if (!reporter.cancelled) apply(unit)      currentRun.advanceUnit      assert(currentRun.currentUnit == unit)      currentRun.currentUnit = unit0    }  }  class TerminalPhase(prev: Phase) extends GlobalPhase(prev) {    def name = "terminal"    def apply(unit: CompilationUnit) {}  }  object syntaxAnalyzer extends SyntaxAnalyzer {    val global: Global.this.type = Global.this  }  object analyzer extends Analyzer {    val global: Global.this.type = Global.this  }  object superAccessors extends SuperAccessors {    val global: Global.this.type = Global.this  }  object pickler extends Pickler {    val global: Global.this.type = Global.this  }  object refchecks extends RefChecks {    val global: Global.this.type = Global.this  }  object liftcode extends LiftCode {    val global: Global.this.type = Global.this  }  object uncurry extends UnCurry {    val global: Global.this.type = Global.this  }  object tailCalls extends TailCalls {    val global: Global.this.type = Global.this  }  //object transMatcher extends TransMatcher {  //  val global: Global.this.type = Global.this  //}//  object checkDefined extends CheckDefined {//    val global: Global.this.type = Global.this//  }  object explicitOuter extends ExplicitOuter {    val global: Global.this.type = Global.this  }  object erasure extends Erasure {    val global: Global.this.type = Global.this  }    object lazyVals extends LazyVals {    val global: Global.this.type = Global.this    final val FLAGS_PER_WORD = 32  }  object lambdaLift extends LambdaLift {    val global: Global.this.type = Global.this  }  object constructors extends Constructors {    val global: Global.this.type = Global.this  }  object flatten extends Flatten {    val global: Global.this.type = Global.this  }/*  object detach extends Detach {    val global: Global.this.type = Global.this  }*/  object mixer extends Mixin {    val global: Global.this.type = Global.this  }  object cleanup extends CleanUp {    val global: Global.this.type = Global.this  }  object sampleTransform extends SampleTransform {    val global: Global.this.type = Global.this  }  object genicode extends GenICode {    val global: Global.this.type = Global.this  }/*  object icodePrinter extends backend.icode.Printers {    val global: Global.this.type = Global.this  }*/  object scalaPrimitives extends ScalaPrimitives {    val global: Global.this.type = Global.this  }  object inliner extends Inliners {

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?