From d5e3f85946af966111f88af90a666a709df0ba6f Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Tue, 13 Nov 2012 00:14:40 -0800 Subject: Revert "Commenting out unused members." This reverts commit 951fc3a486. --- src/compiler/scala/reflect/reify/Errors.scala | 8 +- .../scala/reflect/reify/codegen/GenUtils.scala | 40 ++-- .../scala/reflect/reify/phases/Metalevels.scala | 4 +- .../scala/reflect/reify/utils/SymbolTables.scala | 2 +- src/compiler/scala/tools/ant/sabbus/Settings.scala | 2 +- src/compiler/scala/tools/cmd/FromString.scala | 14 +- src/compiler/scala/tools/cmd/Reference.scala | 2 +- .../scala/tools/nsc/CompilationUnits.scala | 22 +-- src/compiler/scala/tools/nsc/CompileServer.scala | 2 +- src/compiler/scala/tools/nsc/CompilerCommand.scala | 6 +- src/compiler/scala/tools/nsc/CompilerRun.scala | 36 ++-- src/compiler/scala/tools/nsc/Global.scala | 107 +++++------ src/compiler/scala/tools/nsc/ObjectRunner.scala | 4 +- src/compiler/scala/tools/nsc/Phases.scala | 4 +- src/compiler/scala/tools/nsc/Properties.scala | 2 +- src/compiler/scala/tools/nsc/ScriptRunner.scala | 2 +- src/compiler/scala/tools/nsc/ast/DocComments.scala | 8 +- src/compiler/scala/tools/nsc/ast/Printers.scala | 82 +++++++- src/compiler/scala/tools/nsc/ast/TreeDSL.scala | 76 ++++---- src/compiler/scala/tools/nsc/ast/TreeGen.scala | 170 ++++++++--------- src/compiler/scala/tools/nsc/ast/TreeInfo.scala | 6 +- .../scala/tools/nsc/ast/parser/Parsers.scala | 25 ++- .../scala/tools/nsc/ast/parser/Scanners.scala | 59 +++--- .../scala/tools/nsc/ast/parser/Tokens.scala | 62 +++--- .../scala/tools/nsc/ast/parser/TreeBuilder.scala | 26 +-- .../tools/nsc/backend/icode/BasicBlocks.scala | 36 ++-- .../nsc/backend/icode/ExceptionHandlers.scala | 10 +- .../scala/tools/nsc/backend/icode/GenICode.scala | 28 +-- .../scala/tools/nsc/backend/icode/Members.scala | 50 ++--- .../scala/tools/nsc/backend/icode/Opcodes.scala | 20 +- .../scala/tools/nsc/backend/icode/Primitives.scala | 16 +- .../scala/tools/nsc/backend/icode/Repository.scala | 14 +- .../scala/tools/nsc/backend/icode/TypeKinds.scala | 4 +- .../scala/tools/nsc/backend/icode/TypeStacks.scala | 6 +- .../backend/icode/analysis/CopyPropagation.scala | 20 +- .../backend/icode/analysis/DataFlowAnalysis.scala | 10 +- .../backend/icode/analysis/TypeFlowAnalysis.scala | 62 +++--- .../scala/tools/nsc/backend/jvm/GenASM.scala | 12 +- .../scala/tools/nsc/backend/jvm/GenJVM.scala | 26 +-- .../scala/tools/nsc/backend/msil/GenMSIL.scala | 12 +- .../tools/nsc/backend/opt/ClosureElimination.scala | 4 +- .../scala/tools/nsc/backend/opt/Inliners.scala | 6 +- src/compiler/scala/tools/nsc/doc/html/Page.scala | 6 +- .../scala/tools/nsc/doc/model/Entity.scala | 14 +- .../tools/nsc/doc/model/IndexModelFactory.scala | 2 +- .../scala/tools/nsc/doc/model/ModelFactory.scala | 48 ++--- .../doc/model/ModelFactoryImplicitSupport.scala | 32 ++-- .../tools/nsc/doc/model/comment/Comment.scala | 2 +- .../nsc/doc/model/comment/CommentFactory.scala | 36 ++-- .../tools/nsc/doc/model/diagram/Diagram.scala | 18 +- .../scala/tools/nsc/interactive/BuildManager.scala | 2 +- .../scala/tools/nsc/interactive/Global.scala | 68 +++---- .../scala/tools/nsc/interpreter/ByteCode.scala | 28 +-- .../scala/tools/nsc/interpreter/CodeHandlers.scala | 100 +++++----- .../scala/tools/nsc/interpreter/CommandLine.scala | 2 +- .../scala/tools/nsc/interpreter/Completion.scala | 2 +- .../tools/nsc/interpreter/CompletionAware.scala | 46 ++--- .../tools/nsc/interpreter/CompletionOutput.scala | 2 +- .../nsc/interpreter/ConsoleReaderHelper.scala | 10 +- .../scala/tools/nsc/interpreter/Delimited.scala | 6 +- .../scala/tools/nsc/interpreter/ExprTyper.scala | 9 +- .../scala/tools/nsc/interpreter/ILoop.scala | 55 +++--- .../scala/tools/nsc/interpreter/IMain.scala | 199 ++++++++++---------- .../scala/tools/nsc/interpreter/ISettings.scala | 10 +- .../scala/tools/nsc/interpreter/Imports.scala | 22 +-- .../tools/nsc/interpreter/InteractiveReader.scala | 12 +- .../tools/nsc/interpreter/JLineCompletion.scala | 12 +- .../scala/tools/nsc/interpreter/JLineReader.scala | 8 +- .../scala/tools/nsc/interpreter/Logger.scala | 6 +- .../scala/tools/nsc/interpreter/LoopCommands.scala | 38 ++-- .../tools/nsc/interpreter/MemberHandlers.scala | 26 +-- .../scala/tools/nsc/interpreter/NamedParam.scala | 6 +- .../scala/tools/nsc/interpreter/Naming.scala | 2 +- .../scala/tools/nsc/interpreter/Parsed.scala | 14 +- .../scala/tools/nsc/interpreter/Phased.scala | 30 +-- .../scala/tools/nsc/interpreter/Power.scala | 152 +++++++-------- .../scala/tools/nsc/interpreter/ReplConfig.scala | 24 +-- .../scala/tools/nsc/interpreter/ReplProps.scala | 6 +- .../scala/tools/nsc/interpreter/ReplStrings.scala | 2 +- .../scala/tools/nsc/interpreter/RichClass.scala | 7 +- .../scala/tools/nsc/interpreter/SimpleReader.scala | 8 +- .../scala/tools/nsc/interpreter/TypeStrings.scala | 18 +- .../scala/tools/nsc/interpreter/package.scala | 54 +++--- .../tools/nsc/interpreter/session/History.scala | 10 +- .../nsc/interpreter/session/SimpleHistory.scala | 6 +- src/compiler/scala/tools/nsc/io/Fileish.scala | 52 +++--- src/compiler/scala/tools/nsc/io/Jar.scala | 24 +-- src/compiler/scala/tools/nsc/io/MsilFile.scala | 2 +- src/compiler/scala/tools/nsc/io/Pickler.scala | 74 ++++---- src/compiler/scala/tools/nsc/io/Socket.scala | 8 +- src/compiler/scala/tools/nsc/io/SourceReader.scala | 2 +- src/compiler/scala/tools/nsc/io/package.scala | 22 +-- .../scala/tools/nsc/javac/JavaParsers.scala | 8 +- .../scala/tools/nsc/javac/JavaScanners.scala | 48 ++--- .../scala/tools/nsc/javac/JavaTokens.scala | 12 +- .../scala/tools/nsc/matching/MatchSupport.scala | 38 ++-- src/compiler/scala/tools/nsc/matching/Matrix.scala | 48 ++--- .../tools/nsc/matching/ParallelMatching.scala | 6 +- .../scala/tools/nsc/matching/PatternBindings.scala | 2 +- .../scala/tools/nsc/matching/Patterns.scala | 48 ++--- .../scala/tools/nsc/settings/AbsSettings.scala | 16 +- .../tools/nsc/settings/AdvancedScalaSettings.scala | 148 +++++++-------- .../scala/tools/nsc/settings/MutableSettings.scala | 10 +- .../scala/tools/nsc/settings/ScalaSettings.scala | 10 +- .../tools/nsc/settings/StandardScalaSettings.scala | 2 +- .../scala/tools/nsc/settings/Warnings.scala | 14 +- .../nsc/symtab/classfile/AbstractFileReader.scala | 12 +- .../nsc/symtab/classfile/ClassfileParser.scala | 20 +- .../tools/nsc/symtab/classfile/ICodeReader.scala | 6 +- .../scala/tools/nsc/symtab/classfile/Pickler.scala | 208 ++++++++++----------- .../tools/nsc/transform/SpecializeTypes.scala | 28 +-- .../scala/tools/nsc/transform/TailCalls.scala | 2 +- .../tools/nsc/transform/TypingTransformers.scala | 2 +- .../scala/tools/nsc/typechecker/Contexts.scala | 32 ++-- .../tools/nsc/typechecker/DestructureTypes.scala | 20 +- .../scala/tools/nsc/typechecker/Duplicators.scala | 38 ++-- .../scala/tools/nsc/typechecker/Implicits.scala | 12 +- .../tools/nsc/typechecker/MethodSynthesis.scala | 70 +++---- .../scala/tools/nsc/typechecker/Namers.scala | 22 +-- .../tools/nsc/typechecker/NamesDefaults.scala | 2 +- .../tools/nsc/typechecker/PatternMatching.scala | 102 +++++----- .../scala/tools/nsc/typechecker/TreeCheckers.scala | 14 +- .../tools/nsc/typechecker/TypeDiagnostics.scala | 16 +- .../scala/tools/nsc/typechecker/Typers.scala | 14 +- .../scala/tools/nsc/typechecker/Unapplies.scala | 10 +- src/compiler/scala/tools/nsc/util/ClassPath.scala | 44 ++--- .../scala/tools/nsc/util/CommandLineParser.scala | 8 +- .../scala/tools/nsc/util/JavaCharArrayReader.scala | 51 ++--- .../scala/tools/nsc/util/ScalaClassLoader.scala | 62 +++--- .../scala/tools/nsc/util/SimpleTracer.scala | 2 +- src/compiler/scala/tools/nsc/util/package.scala | 22 +-- .../scala/tools/reflect/ToolBoxFactory.scala | 4 +- src/compiler/scala/tools/util/Javap.scala | 4 +- src/compiler/scala/tools/util/PathResolver.scala | 12 +- 134 files changed, 1885 insertions(+), 1815 deletions(-) (limited to 'src/compiler/scala') diff --git a/src/compiler/scala/reflect/reify/Errors.scala b/src/compiler/scala/reflect/reify/Errors.scala index 9e59b40236..a72233274e 100644 --- a/src/compiler/scala/reflect/reify/Errors.scala +++ b/src/compiler/scala/reflect/reify/Errors.scala @@ -21,10 +21,10 @@ trait Errors { throw new ReificationException(defaultErrorPosition, msg) } - // def CannotReifySymbol(sym: Symbol) = { - // val msg = "implementation restriction: cannot reify symbol %s (%s)".format(sym, sym.accurateKindString) - // throw new ReificationException(defaultErrorPosition, msg) - // } + def CannotReifySymbol(sym: Symbol) = { + val msg = "implementation restriction: cannot reify symbol %s (%s)".format(sym, sym.accurateKindString) + throw new ReificationException(defaultErrorPosition, msg) + } def CannotReifyWeakType(details: Any) = { val msg = "cannot create a TypeTag" + details + ": use WeakTypeTag instead" diff --git a/src/compiler/scala/reflect/reify/codegen/GenUtils.scala b/src/compiler/scala/reflect/reify/codegen/GenUtils.scala index d0f8ae76e2..6554947f88 100644 --- a/src/compiler/scala/reflect/reify/codegen/GenUtils.scala +++ b/src/compiler/scala/reflect/reify/codegen/GenUtils.scala @@ -91,20 +91,20 @@ trait GenUtils { def termPath(fullname: String): Tree = path(fullname, newTermName) /** An (unreified) path that refers to type definition with given fully qualified name */ - // def typePath(fullname: String): Tree = path(fullname, newTypeName) - - // def isTough(tpe: Type) = { - // def isTough(tpe: Type) = tpe match { - // case _: RefinedType => true - // case _: ExistentialType => true - // case _: ClassInfoType => true - // case _: MethodType => true - // case _: PolyType => true - // case _ => false - // } + def typePath(fullname: String): Tree = path(fullname, newTypeName) + + def isTough(tpe: Type) = { + def isTough(tpe: Type) = tpe match { + case _: RefinedType => true + case _: ExistentialType => true + case _: ClassInfoType => true + case _: MethodType => true + case _: PolyType => true + case _ => false + } - // tpe != null && (tpe exists isTough) - // } + tpe != null && (tpe exists isTough) + } object TypedOrAnnotated { def unapply(tree: Tree): Option[Tree] = tree match { @@ -117,14 +117,14 @@ trait GenUtils { } } - // def isAnnotated(tpe: Type) = { - // def isAnnotated(tpe: Type) = tpe match { - // case _: AnnotatedType => true - // case _ => false - // } + def isAnnotated(tpe: Type) = { + def isAnnotated(tpe: Type) = tpe match { + case _: AnnotatedType => true + case _ => false + } - // tpe != null && (tpe exists isAnnotated) - // } + tpe != null && (tpe exists isAnnotated) + } def isSemiConcreteTypeMember(tpe: Type) = tpe match { case TypeRef(SingleType(_, _), sym, _) if sym.isAbstractType && !sym.isExistential => true diff --git a/src/compiler/scala/reflect/reify/phases/Metalevels.scala b/src/compiler/scala/reflect/reify/phases/Metalevels.scala index cccf080dbf..92d951c3a1 100644 --- a/src/compiler/scala/reflect/reify/phases/Metalevels.scala +++ b/src/compiler/scala/reflect/reify/phases/Metalevels.scala @@ -1,8 +1,6 @@ package scala.reflect.reify package phases -import scala.collection.{ mutable } - trait Metalevels { self: Reifier => @@ -103,7 +101,7 @@ trait Metalevels { */ val metalevels = new Transformer { var insideSplice = false - val inlineableBindings = mutable.Map[TermName, Tree]() + var inlineableBindings = scala.collection.mutable.Map[TermName, Tree]() def withinSplice[T](op: => T) = { val old = insideSplice diff --git a/src/compiler/scala/reflect/reify/utils/SymbolTables.scala b/src/compiler/scala/reflect/reify/utils/SymbolTables.scala index 6e34d64847..99118c4f2e 100644 --- a/src/compiler/scala/reflect/reify/utils/SymbolTables.scala +++ b/src/compiler/scala/reflect/reify/utils/SymbolTables.scala @@ -15,7 +15,7 @@ trait SymbolTables { private[SymbolTable] val original: Option[List[Tree]] = None) { def syms: List[Symbol] = symtab.keys.toList - // def isConcrete: Boolean = symtab.values forall (sym => !FreeTypeDef.unapply(sym).isDefined) + def isConcrete: Boolean = symtab.values forall (sym => !FreeTypeDef.unapply(sym).isDefined) // def aliases: Map[Symbol, List[TermName]] = aliases.distinct groupBy (_._1) mapValues (_ map (_._2)) diff --git a/src/compiler/scala/tools/ant/sabbus/Settings.scala b/src/compiler/scala/tools/ant/sabbus/Settings.scala index d0fefdaa03..fde61e9564 100644 --- a/src/compiler/scala/tools/ant/sabbus/Settings.scala +++ b/src/compiler/scala/tools/ant/sabbus/Settings.scala @@ -10,7 +10,7 @@ package scala.tools.ant.sabbus import java.io.File -import org.apache.tools.ant.types.Path +import org.apache.tools.ant.types.{Path, Reference} class Settings { diff --git a/src/compiler/scala/tools/cmd/FromString.scala b/src/compiler/scala/tools/cmd/FromString.scala index c9df9f9145..2a624875ee 100644 --- a/src/compiler/scala/tools/cmd/FromString.scala +++ b/src/compiler/scala/tools/cmd/FromString.scala @@ -25,17 +25,17 @@ abstract class FromString[+T](implicit t: ru.TypeTag[T]) extends PartialFunction object FromString { // We need these because we clash with the String => Path implicits. - // private def toFile(s: String) = new File(new java.io.File(s)) + private def toFile(s: String) = new File(new java.io.File(s)) private def toDir(s: String) = new Directory(new java.io.File(s)) /** Path related stringifiers. */ - // val ExistingFile: FromString[File] = new FromString[File]()(tagOfFile) { - // override def isDefinedAt(s: String) = toFile(s).isFile - // def apply(s: String): File = - // if (isDefinedAt(s)) toFile(s) - // else cmd.runAndExit(println("'%s' is not an existing file." format s)) - // } + val ExistingFile: FromString[File] = new FromString[File]()(tagOfFile) { + override def isDefinedAt(s: String) = toFile(s).isFile + def apply(s: String): File = + if (isDefinedAt(s)) toFile(s) + else cmd.runAndExit(println("'%s' is not an existing file." format s)) + } val ExistingDir: FromString[Directory] = new FromString[Directory]()(tagOfDirectory) { override def isDefinedAt(s: String) = toDir(s).isDirectory def apply(s: String): Directory = diff --git a/src/compiler/scala/tools/cmd/Reference.scala b/src/compiler/scala/tools/cmd/Reference.scala index 4f1620d61a..d4f2060f81 100644 --- a/src/compiler/scala/tools/cmd/Reference.scala +++ b/src/compiler/scala/tools/cmd/Reference.scala @@ -26,7 +26,7 @@ trait Reference extends Spec { def isUnaryOption(s: String) = unary contains toOpt(s) def isBinaryOption(s: String) = binary contains toOpt(s) def isExpandOption(s: String) = expansionMap contains toOpt(s) - // def isAnyOption(s: String) = isUnaryOption(s) || isBinaryOption(s) || isExpandOption(s) + def isAnyOption(s: String) = isUnaryOption(s) || isBinaryOption(s) || isExpandOption(s) def expandArg(arg: String) = expansionMap.getOrElse(fromOpt(arg), List(arg)) diff --git a/src/compiler/scala/tools/nsc/CompilationUnits.scala b/src/compiler/scala/tools/nsc/CompilationUnits.scala index 6d523552b8..5be819c134 100644 --- a/src/compiler/scala/tools/nsc/CompilationUnits.scala +++ b/src/compiler/scala/tools/nsc/CompilationUnits.scala @@ -26,7 +26,7 @@ trait CompilationUnits { self: Global => class CompilationUnit(val source: SourceFile) extends CompilationUnitContextApi { /** the fresh name creator */ - val fresh: FreshNameCreator = new FreshNameCreator.Default + var fresh: FreshNameCreator = new FreshNameCreator.Default def freshTermName(prefix: String): TermName = newTermName(fresh.newName(prefix)) def freshTypeName(prefix: String): TypeName = newTypeName(fresh.newName(prefix)) @@ -108,16 +108,16 @@ trait CompilationUnits { self: Global => override def toString() = source.toString() - // def clear() { - // fresh = new FreshNameCreator.Default - // body = EmptyTree - // depends.clear() - // defined.clear() - // synthetics.clear() - // toCheck.clear() - // checkedFeatures = Set() - // icode.clear() - // } + def clear() { + fresh = new FreshNameCreator.Default + body = EmptyTree + depends.clear() + defined.clear() + synthetics.clear() + toCheck.clear() + checkedFeatures = Set() + icode.clear() + } } } diff --git a/src/compiler/scala/tools/nsc/CompileServer.scala b/src/compiler/scala/tools/nsc/CompileServer.scala index 11ee34af99..521f788fa1 100644 --- a/src/compiler/scala/tools/nsc/CompileServer.scala +++ b/src/compiler/scala/tools/nsc/CompileServer.scala @@ -29,7 +29,7 @@ class StandardCompileServer extends SocketServer { var shutdown = false var verbose = false - // val versionMsg = "Fast " + Properties.versionMsg + val versionMsg = "Fast " + Properties.versionMsg val MaxCharge = 0.8 diff --git a/src/compiler/scala/tools/nsc/CompilerCommand.scala b/src/compiler/scala/tools/nsc/CompilerCommand.scala index 577d28f5f6..829e097714 100644 --- a/src/compiler/scala/tools/nsc/CompilerCommand.scala +++ b/src/compiler/scala/tools/nsc/CompilerCommand.scala @@ -15,7 +15,7 @@ class CompilerCommand(arguments: List[String], val settings: Settings) { type Setting = Settings#Setting /** file extensions of files that the compiler can process */ - // lazy val fileEndings = Properties.fileEndings + lazy val fileEndings = Properties.fileEndings private val processArgumentsResult = if (shouldProcessArguments) processArguments @@ -40,8 +40,8 @@ class CompilerCommand(arguments: List[String], val settings: Settings) { """.stripMargin.trim + "\n" def shortUsage = "Usage: %s " format cmdName - // def createUsagePreface(shouldExplain: Boolean) = - // if (shouldExplain) shortUsage + "\n" + explainAdvanced else "" + def createUsagePreface(shouldExplain: Boolean) = + if (shouldExplain) shortUsage + "\n" + explainAdvanced else "" /** Creates a help message for a subset of options based on cond */ def createUsageMsg(cond: Setting => Boolean): String = { diff --git a/src/compiler/scala/tools/nsc/CompilerRun.scala b/src/compiler/scala/tools/nsc/CompilerRun.scala index daad704534..6746b08155 100644 --- a/src/compiler/scala/tools/nsc/CompilerRun.scala +++ b/src/compiler/scala/tools/nsc/CompilerRun.scala @@ -1,21 +1,21 @@ -// /* NSC -- new Scala compiler -// * Copyright 2005-2013 LAMP/EPFL -// * @author Martin Odersky -// */ +/* NSC -- new Scala compiler + * Copyright 2005-2013 LAMP/EPFL + * @author Martin Odersky + */ -// package scala.tools.nsc +package scala.tools.nsc -// class CompilerRun { -// def firstPhase: Phase = NoPhase -// def terminalPhase: Phase = NoPhase -// def namerPhase: Phase = NoPhase -// def typerPhase: Phase = NoPhase -// def refchecksPhase: Phase = NoPhase -// def explicitouterPhase: Phase = NoPhase -// def erasurePhase: Phase = NoPhase -// def flattenPhase: Phase = NoPhase -// def mixinPhase: Phase = NoPhase -// def icodePhase: Phase = NoPhase -// def phaseNamed(name: String): Phase = NoPhase -// } +class CompilerRun { + def firstPhase: Phase = NoPhase + def terminalPhase: Phase = NoPhase + def namerPhase: Phase = NoPhase + def typerPhase: Phase = NoPhase + def refchecksPhase: Phase = NoPhase + def explicitouterPhase: Phase = NoPhase + def erasurePhase: Phase = NoPhase + def flattenPhase: Phase = NoPhase + def mixinPhase: Phase = NoPhase + def icodePhase: Phase = NoPhase + def phaseNamed(name: String): Phase = NoPhase +} diff --git a/src/compiler/scala/tools/nsc/Global.scala b/src/compiler/scala/tools/nsc/Global.scala index 8802c3ec80..13bec828ca 100644 --- a/src/compiler/scala/tools/nsc/Global.scala +++ b/src/compiler/scala/tools/nsc/Global.scala @@ -70,7 +70,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) def this(settings: Settings) = this(settings, new ConsoleReporter(settings)) - // def mkAttributedQualifier(tpe: Type, termSym: Symbol): Tree = gen.mkAttributedQualifier(tpe, termSym) + def mkAttributedQualifier(tpe: Type, termSym: Symbol): Tree = gen.mkAttributedQualifier(tpe, termSym) def picklerPhase: Phase = if (currentRun.isDefined) currentRun.picklerPhase else NoPhase @@ -265,14 +265,14 @@ class Global(var currentSettings: Settings, var reporter: Reporter) def informComplete(msg: String): Unit = reporter.withoutTruncating(inform(msg)) def informProgress(msg: String) = if (settings.verbose.value) inform("[" + msg + "]") - // def inform[T](msg: String, value: T): T = returning(value)(x => inform(msg + x)) + def inform[T](msg: String, value: T): T = returning(value)(x => inform(msg + x)) def informTime(msg: String, start: Long) = informProgress(elapsedMessage(msg, start)) def logError(msg: String, t: Throwable): Unit = () - // def logAfterEveryPhase[T](msg: String)(op: => T) { - // log("Running operation '%s' after every phase.\n".format(msg) + describeAfterEveryPhase(op)) - // } + def logAfterEveryPhase[T](msg: String)(op: => T) { + log("Running operation '%s' after every phase.\n".format(msg) + describeAfterEveryPhase(op)) + } override def shouldLogAtThisPhase = settings.log.isSetByUser && ( (settings.log containsPhase globalPhase) || (settings.log containsPhase phase) @@ -419,8 +419,8 @@ class Global(var currentSettings: Settings, var reporter: Reporter) } /** Switch to turn on detailed type logs */ - val printTypings = settings.Ytyperdebug.value - val printInfers = settings.Yinferdebug.value + var printTypings = settings.Ytyperdebug.value + var printInfers = settings.Yinferdebug.value // phaseName = "parser" object syntaxAnalyzer extends { @@ -639,11 +639,11 @@ class Global(var currentSettings: Settings, var reporter: Reporter) } // phaseName = "SAMPLE PHASE" - // object sampleTransform extends { - // val global: Global.this.type = Global.this - // val runsAfter = List[String]() - // val runsRightAfter = None - // } with SampleTransform + object sampleTransform extends { + val global: Global.this.type = Global.this + val runsAfter = List[String]() + val runsRightAfter = None + } with SampleTransform /** The checkers are for validating the compiler data structures * at phase boundaries. @@ -778,7 +778,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) /** Returns List of (phase, value) pairs, including only those * where the value compares unequal to the previous phase's value. */ - def afterEachPhase[T](op: => T): List[(Phase, T)] = { // used in tests + def afterEachPhase[T](op: => T): List[(Phase, T)] = { phaseDescriptors.map(_.ownPhase).filterNot(_ eq NoPhase).foldLeft(List[(Phase, T)]()) { (res, ph) => val value = exitingPhase(ph)(op) if (res.nonEmpty && res.head._2 == value) res @@ -790,17 +790,17 @@ class Global(var currentSettings: Settings, var reporter: Reporter) * phase transitions where the result of the operation gave a different * list than it had when run during the previous phase. */ - // def changesAfterEachPhase[T](op: => List[T]): List[ChangeAfterPhase[T]] = { - // val ops = ((NoPhase, Nil)) :: afterEachPhase(op) - - // ops sliding 2 map { - // case (_, before) :: (ph, after) :: Nil => - // val lost = before filterNot (after contains _) - // val gained = after filterNot (before contains _) - // ChangeAfterPhase(ph, lost, gained) - // case _ => ??? - // } toList - // } + def changesAfterEachPhase[T](op: => List[T]): List[ChangeAfterPhase[T]] = { + val ops = ((NoPhase, Nil)) :: afterEachPhase(op) + + ops sliding 2 map { + case (_, before) :: (ph, after) :: Nil => + val lost = before filterNot (after contains _) + val gained = after filterNot (before contains _) + ChangeAfterPhase(ph, lost, gained) + case _ => ??? + } toList + } private def numberedPhase(ph: Phase) = "%2d/%s".format(ph.id, ph.name) case class ChangeAfterPhase[+T](ph: Phase, lost: List[T], gained: List[T]) { @@ -811,14 +811,14 @@ class Global(var currentSettings: Settings, var reporter: Reporter) override def toString = mkStr("Lost", lost) + mkStr("Gained", gained) } - // def describeAfterEachPhase[T](op: => T): List[String] = - // afterEachPhase(op) map { case (ph, t) => "[after %-15s] %s".format(numberedPhase(ph), t) } + def describeAfterEachPhase[T](op: => T): List[String] = + afterEachPhase(op) map { case (ph, t) => "[after %-15s] %s".format(numberedPhase(ph), t) } - // def describeAfterEveryPhase[T](op: => T): String = - // describeAfterEachPhase(op) map (" " + _ + "\n") mkString + def describeAfterEveryPhase[T](op: => T): String = + describeAfterEachPhase(op) map (" " + _ + "\n") mkString - // def printAfterEachPhase[T](op: => T): Unit = - // describeAfterEachPhase(op) foreach (m => println(" " + m)) + def printAfterEachPhase[T](op: => T): Unit = + describeAfterEachPhase(op) foreach (m => println(" " + m)) // ------------ Invalidations --------------------------------- @@ -1057,7 +1057,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) @inline final def exitingPostErasure[T](op: => T): T = exitingPhase(currentRun.posterasurePhase)(op) @inline final def exitingExplicitOuter[T](op: => T): T = exitingPhase(currentRun.explicitouterPhase)(op) @inline final def exitingFlatten[T](op: => T): T = exitingPhase(currentRun.flattenPhase)(op) - // @inline final def exitingIcode[T](op: => T): T = exitingPhase(currentRun.icodePhase)(op) + @inline final def exitingIcode[T](op: => T): T = exitingPhase(currentRun.icodePhase)(op) @inline final def exitingMixin[T](op: => T): T = exitingPhase(currentRun.mixinPhase)(op) @inline final def exitingPickler[T](op: => T): T = exitingPhase(currentRun.picklerPhase)(op) @inline final def exitingRefchecks[T](op: => T): T = exitingPhase(currentRun.refchecksPhase)(op) @@ -1071,21 +1071,21 @@ class Global(var currentSettings: Settings, var reporter: Reporter) @inline final def enteringMixin[T](op: => T): T = enteringPhase(currentRun.mixinPhase)(op) @inline final def enteringPickler[T](op: => T): T = enteringPhase(currentRun.picklerPhase)(op) @inline final def enteringRefchecks[T](op: => T): T = enteringPhase(currentRun.refchecksPhase)(op) - // @inline final def enteringSpecialize[T](op: => T): T = enteringPhase(currentRun.specializePhase)(op) + @inline final def enteringSpecialize[T](op: => T): T = enteringPhase(currentRun.specializePhase)(op) @inline final def enteringTyper[T](op: => T): T = enteringPhase(currentRun.typerPhase)(op) @inline final def enteringUncurry[T](op: => T): T = enteringPhase(currentRun.uncurryPhase)(op) - // def explainContext(c: analyzer.Context): String = ( - // if (c == null) "" else ( - // """| context owners: %s - // | - // |Enclosing block or template: - // |%s""".format( - // c.owner.ownerChain.takeWhile(!_.isPackageClass).mkString(" -> "), - // nodePrinters.nodeToString(c.enclClassOrMethod.tree) - // ) - // ) - // ) + def explainContext(c: analyzer.Context): String = ( + if (c == null) "" else ( + """| context owners: %s + | + |Enclosing block or template: + |%s""".format( + c.owner.ownerChain.takeWhile(!_.isPackageClass).mkString(" -> "), + nodePrinters.nodeToString(c.enclClassOrMethod.tree) + ) + ) + ) // Owners up to and including the first package class. private def ownerChainString(sym: Symbol): String = ( if (sym == null) "" @@ -1098,8 +1098,8 @@ class Global(var currentSettings: Settings, var reporter: Reporter) pairs.toList collect { case (k, v) if v != null => "%20s: %s".format(k, v) } mkString "\n" ) - // def explainTree(t: Tree): String = formatExplain( - // ) + def explainTree(t: Tree): String = formatExplain( + ) /** Don't want to introduce new errors trying to report errors, * so swallow exceptions. @@ -1158,7 +1158,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) } def newUnitParser(code: String) = new syntaxAnalyzer.UnitParser(newCompilationUnit(code)) - // def newUnitScanner(code: String) = new syntaxAnalyzer.UnitScanner(newCompilationUnit(code)) + def newUnitScanner(code: String) = new syntaxAnalyzer.UnitScanner(newCompilationUnit(code)) def newCompilationUnit(code: String) = new CompilationUnit(newSourceFile(code)) def newSourceFile(code: String) = new BatchSourceFile("", code) @@ -1181,8 +1181,9 @@ class Global(var currentSettings: Settings, var reporter: Reporter) val inlinerWarnings = new ConditionalWarning("inliner", settings.YinlinerWarnings) val allConditionalWarnings = List(deprecationWarnings0, uncheckedWarnings0, featureWarnings, inlinerWarnings) - def uncheckedWarnings: List[(Position, String)] = uncheckedWarnings0.warnings.toList // used in sbt - def deprecationWarnings: List[(Position, String)] = deprecationWarnings0.warnings.toList // used in sbt + // for sbt's benefit + def uncheckedWarnings: List[(Position, String)] = uncheckedWarnings0.warnings.toList + def deprecationWarnings: List[(Position, String)] = deprecationWarnings0.warnings.toList var reportedFeature = Set[Symbol]() @@ -1349,7 +1350,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) val namerPhase = phaseNamed("namer") // val packageobjectsPhase = phaseNamed("packageobjects") val typerPhase = phaseNamed("typer") - // val inlineclassesPhase = phaseNamed("inlineclasses") + val inlineclassesPhase = phaseNamed("inlineclasses") // val superaccessorsPhase = phaseNamed("superaccessors") val picklerPhase = phaseNamed("pickler") val refchecksPhase = phaseNamed("refchecks") @@ -1362,7 +1363,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) val erasurePhase = phaseNamed("erasure") val posterasurePhase = phaseNamed("posterasure") // val lazyvalsPhase = phaseNamed("lazyvals") - // val lambdaliftPhase = phaseNamed("lambdalift") + val lambdaliftPhase = phaseNamed("lambdalift") // val constructorsPhase = phaseNamed("constructors") val flattenPhase = phaseNamed("flatten") val mixinPhase = phaseNamed("mixin") @@ -1372,11 +1373,11 @@ class Global(var currentSettings: Settings, var reporter: Reporter) val inlineExceptionHandlersPhase = phaseNamed("inlineExceptionHandlers") val closelimPhase = phaseNamed("closelim") val dcePhase = phaseNamed("dce") - // val jvmPhase = phaseNamed("jvm") + val jvmPhase = phaseNamed("jvm") // val msilPhase = phaseNamed("msil") def runIsAt(ph: Phase) = globalPhase.id == ph.id - // def runIsPast(ph: Phase) = globalPhase.id > ph.id + def runIsPast(ph: Phase) = globalPhase.id > ph.id // def runIsAtBytecodeGen = (runIsAt(jvmPhase) || runIsAt(msilPhase)) def runIsAtOptimiz = { runIsAt(inlinerPhase) || // listing phases in full for robustness when -Ystop-after has been given. @@ -1742,7 +1743,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) // and forScaladoc default to onlyPresentation, which is the same as defaulting // to false except in old code. The downside is that this leaves us calling a // deprecated method: but I see no simple way out, so I leave it for now. - // def forJVM = settings.target.value startsWith "jvm" + def forJVM = settings.target.value startsWith "jvm" override def forMSIL = settings.target.value startsWith "msil" def forInteractive = false def forScaladoc = false diff --git a/src/compiler/scala/tools/nsc/ObjectRunner.scala b/src/compiler/scala/tools/nsc/ObjectRunner.scala index e36e154925..3c75429311 100644 --- a/src/compiler/scala/tools/nsc/ObjectRunner.scala +++ b/src/compiler/scala/tools/nsc/ObjectRunner.scala @@ -13,8 +13,8 @@ import util.Exceptional.unwrap trait CommonRunner { /** Check whether a class with the specified name * exists on the specified class path. */ - // def classExists(urls: List[URL], objectName: String): Boolean = - // ScalaClassLoader.classExists(urls, objectName) + def classExists(urls: List[URL], objectName: String): Boolean = + ScalaClassLoader.classExists(urls, objectName) /** Run a given object, specified by name, using a * specified classpath and argument list. diff --git a/src/compiler/scala/tools/nsc/Phases.scala b/src/compiler/scala/tools/nsc/Phases.scala index e81d3ebc8a..aad70a9c5e 100644 --- a/src/compiler/scala/tools/nsc/Phases.scala +++ b/src/compiler/scala/tools/nsc/Phases.scala @@ -20,7 +20,7 @@ object Phases { } val values = new Array[Cell](MaxPhases + 1) def results = values filterNot (_ == null) - // def apply(ph: Phase): T = values(ph.id).value + def apply(ph: Phase): T = values(ph.id).value def update(ph: Phase, value: T): Unit = values(ph.id) = Cell(ph, value) } /** A class for recording the elapsed time of each phase in the @@ -38,7 +38,7 @@ object Phases { >> ("ms" -> (_.value)) >+ " " << ("share" -> (_.value.toDouble * 100 / total formatted "%.2f")) } - // def formatted = "" + table() + def formatted = "" + table() } } diff --git a/src/compiler/scala/tools/nsc/Properties.scala b/src/compiler/scala/tools/nsc/Properties.scala index 028fc24efb..55fd196716 100644 --- a/src/compiler/scala/tools/nsc/Properties.scala +++ b/src/compiler/scala/tools/nsc/Properties.scala @@ -21,5 +21,5 @@ object Properties extends scala.util.PropertiesTrait { // derived values def isEmacsShell = propOrEmpty("env.emacs") != "" - // def fileEndings = fileEndingString.split("""\|""").toList + def fileEndings = fileEndingString.split("""\|""").toList } diff --git a/src/compiler/scala/tools/nsc/ScriptRunner.scala b/src/compiler/scala/tools/nsc/ScriptRunner.scala index 344a60903a..0b307a861e 100644 --- a/src/compiler/scala/tools/nsc/ScriptRunner.scala +++ b/src/compiler/scala/tools/nsc/ScriptRunner.scala @@ -48,7 +48,7 @@ class ScriptRunner extends HasCompileSocket { case x => x } - // def isScript(settings: Settings) = settings.script.value != "" + def isScript(settings: Settings) = settings.script.value != "" /** Choose a jar filename to hold the compiled version of a script. */ private def jarFileFor(scriptFile: String)= File( diff --git a/src/compiler/scala/tools/nsc/ast/DocComments.scala b/src/compiler/scala/tools/nsc/ast/DocComments.scala index 40f97222a9..21407289db 100755 --- a/src/compiler/scala/tools/nsc/ast/DocComments.scala +++ b/src/compiler/scala/tools/nsc/ast/DocComments.scala @@ -22,9 +22,9 @@ trait DocComments { self: Global => val docComments = mutable.HashMap[Symbol, DocComment]() /** Associate comment with symbol `sym` at position `pos`. */ - // def docComment(sym: Symbol, docStr: String, pos: Position = NoPosition) = - // if ((sym ne null) && (sym ne NoSymbol)) - // docComments += (sym -> DocComment(docStr, pos)) + def docComment(sym: Symbol, docStr: String, pos: Position = NoPosition) = + if ((sym ne null) && (sym ne NoSymbol)) + docComments += (sym -> DocComment(docStr, pos)) /** The raw doc comment of symbol `sym`, as it appears in the source text, "" if missing. */ @@ -120,7 +120,7 @@ trait DocComments { self: Global => getDocComment(sym) map getUseCases getOrElse List() } - // def useCases(sym: Symbol): List[(Symbol, String, Position)] = useCases(sym, sym.enclClass) + def useCases(sym: Symbol): List[(Symbol, String, Position)] = useCases(sym, sym.enclClass) /** Returns the javadoc format of doc comment string `s`, including wiki expansion */ diff --git a/src/compiler/scala/tools/nsc/ast/Printers.scala b/src/compiler/scala/tools/nsc/ast/Printers.scala index d0aa004c9a..0414e0f123 100644 --- a/src/compiler/scala/tools/nsc/ast/Printers.scala +++ b/src/compiler/scala/tools/nsc/ast/Printers.scala @@ -200,17 +200,91 @@ trait Printers extends scala.reflect.internal.Printers { this: Global => override def printTree(tree: Tree) { print(safe(tree)) } } + class TreeMatchTemplate { + // non-trees defined in Trees + // + // case class ImportSelector(name: Name, namePos: Int, rename: Name, renamePos: Int) + // case class Modifiers(flags: Long, privateWithin: Name, annotations: List[Tree], positions: Map[Long, Position]) + // + def apply(t: Tree): Unit = t match { + // eliminated by typer + case Annotated(annot, arg) => + case AssignOrNamedArg(lhs, rhs) => + case DocDef(comment, definition) => + case Import(expr, selectors) => + + // eliminated by refchecks + case ModuleDef(mods, name, impl) => + case TypeTreeWithDeferredRefCheck() => + + // eliminated by erasure + case TypeDef(mods, name, tparams, rhs) => + case Typed(expr, tpt) => + + // eliminated by cleanup + case ApplyDynamic(qual, args) => + + // eliminated by explicitouter + case Alternative(trees) => + case Bind(name, body) => + case CaseDef(pat, guard, body) => + case Star(elem) => + case UnApply(fun, args) => + + // eliminated by lambdalift + case Function(vparams, body) => + + // eliminated by uncurry + case AppliedTypeTree(tpt, args) => + case CompoundTypeTree(templ) => + case ExistentialTypeTree(tpt, whereClauses) => + case SelectFromTypeTree(qual, selector) => + case SingletonTypeTree(ref) => + case TypeBoundsTree(lo, hi) => + + // survivors + case Apply(fun, args) => + case ArrayValue(elemtpt, trees) => + case Assign(lhs, rhs) => + case Block(stats, expr) => + case ClassDef(mods, name, tparams, impl) => + case DefDef(mods, name, tparams, vparamss, tpt, rhs) => + case EmptyTree => + case Ident(name) => + case If(cond, thenp, elsep) => + case LabelDef(name, params, rhs) => + case Literal(value) => + case Match(selector, cases) => + case New(tpt) => + case PackageDef(pid, stats) => + case Return(expr) => + case Select(qualifier, selector) => + case Super(qual, mix) => + case Template(parents, self, body) => + case This(qual) => + case Throw(expr) => + case Try(block, catches, finalizer) => + case TypeApply(fun, args) => + case TypeTree() => + case ValDef(mods, name, tpt, rhs) => + + // missing from the Trees comment + case Parens(args) => // only used during parsing + case SelectFromArray(qual, name, erasure) => // only used during erasure + } + } + def asString(t: Tree): String = render(t, newStandardTreePrinter, settings.printtypes.value, settings.uniqid.value, settings.Yshowsymkinds.value) def asCompactString(t: Tree): String = render(t, newCompactTreePrinter, settings.printtypes.value, settings.uniqid.value, settings.Yshowsymkinds.value) def asCompactDebugString(t: Tree): String = render(t, newCompactTreePrinter, true, true, true) def newStandardTreePrinter(writer: PrintWriter): TreePrinter = new TreePrinter(writer) - // def newStandardTreePrinter(stream: OutputStream): TreePrinter = newStandardTreePrinter(new PrintWriter(stream)) - // def newStandardTreePrinter(): TreePrinter = newStandardTreePrinter(new PrintWriter(ConsoleWriter)) + def newStandardTreePrinter(stream: OutputStream): TreePrinter = newStandardTreePrinter(new PrintWriter(stream)) + def newStandardTreePrinter(): TreePrinter = newStandardTreePrinter(new PrintWriter(ConsoleWriter)) def newCompactTreePrinter(writer: PrintWriter): CompactTreePrinter = new CompactTreePrinter(writer) - // def newCompactTreePrinter(stream: OutputStream): CompactTreePrinter = newCompactTreePrinter(new PrintWriter(stream)) - // def newCompactTreePrinter(): CompactTreePrinter = newCompactTreePrinter(new PrintWriter(ConsoleWriter)) + def newCompactTreePrinter(stream: OutputStream): CompactTreePrinter = newCompactTreePrinter(new PrintWriter(stream)) + def newCompactTreePrinter(): CompactTreePrinter = newCompactTreePrinter(new PrintWriter(ConsoleWriter)) override def newTreePrinter(writer: PrintWriter): TreePrinter = if (settings.Ycompacttrees.value) newCompactTreePrinter(writer) diff --git a/src/compiler/scala/tools/nsc/ast/TreeDSL.scala b/src/compiler/scala/tools/nsc/ast/TreeDSL.scala index 0696b0e673..3acefe9441 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeDSL.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeDSL.scala @@ -84,16 +84,16 @@ trait TreeDSL { def ANY_EQ (other: Tree) = OBJ_EQ(other AS ObjectClass.tpe) def ANY_== (other: Tree) = fn(target, Any_==, other) def ANY_!= (other: Tree) = fn(target, Any_!=, other) - // def OBJ_== (other: Tree) = fn(target, Object_==, other) + def OBJ_== (other: Tree) = fn(target, Object_==, other) def OBJ_!= (other: Tree) = fn(target, Object_!=, other) def OBJ_EQ (other: Tree) = fn(target, Object_eq, other) def OBJ_NE (other: Tree) = fn(target, Object_ne, other) - // def INT_| (other: Tree) = fn(target, getMember(IntClass, nme.OR), other) - // def INT_& (other: Tree) = fn(target, getMember(IntClass, nme.AND), other) + def INT_| (other: Tree) = fn(target, getMember(IntClass, nme.OR), other) + def INT_& (other: Tree) = fn(target, getMember(IntClass, nme.AND), other) def INT_>= (other: Tree) = fn(target, getMember(IntClass, nme.GE), other) def INT_== (other: Tree) = fn(target, getMember(IntClass, nme.EQ), other) - // def INT_!= (other: Tree) = fn(target, getMember(IntClass, nme.NE), other) + def INT_!= (other: Tree) = fn(target, getMember(IntClass, nme.NE), other) // generic operations on ByteClass, IntClass, LongClass def GEN_| (other: Tree, kind: ClassSymbol) = fn(target, getMember(kind, nme.OR), other) @@ -101,8 +101,8 @@ trait TreeDSL { def GEN_== (other: Tree, kind: ClassSymbol) = fn(target, getMember(kind, nme.EQ), other) def GEN_!= (other: Tree, kind: ClassSymbol) = fn(target, getMember(kind, nme.NE), other) - // def BOOL_&& (other: Tree) = fn(target, Boolean_and, other) - // def BOOL_|| (other: Tree) = fn(target, Boolean_or, other) + def BOOL_&& (other: Tree) = fn(target, Boolean_and, other) + def BOOL_|| (other: Tree) = fn(target, Boolean_or, other) /** Apply, Select, Match **/ def APPLY(params: Tree*) = Apply(target, params.toList) @@ -158,7 +158,7 @@ trait TreeDSL { def mkTree(rhs: Tree): ResultTreeType def ===(rhs: Tree): ResultTreeType - // private var _mods: Modifiers = null + private var _mods: Modifiers = null private var _tpt: Tree = null private var _pos: Position = null @@ -166,19 +166,19 @@ trait TreeDSL { _tpt = TypeTree(tp) this } - // def withFlags(flags: Long*): this.type = { - // if (_mods == null) - // _mods = defaultMods + def withFlags(flags: Long*): this.type = { + if (_mods == null) + _mods = defaultMods - // _mods = flags.foldLeft(_mods)(_ | _) - // this - // } + _mods = flags.foldLeft(_mods)(_ | _) + this + } def withPos(pos: Position): this.type = { _pos = pos this } - final def mods = defaultMods // if (_mods == null) defaultMods else _mods + final def mods = if (_mods == null) defaultMods else _mods final def tpt = if (_tpt == null) defaultTpt else _tpt final def pos = if (_pos == null) defaultPos else _pos } @@ -243,7 +243,7 @@ trait TreeDSL { } class TryStart(body: Tree, catches: List[CaseDef], fin: Tree) { def CATCH(xs: CaseDef*) = new TryStart(body, xs.toList, fin) - // def FINALLY(x: Tree) = Try(body, catches, x) + def FINALLY(x: Tree) = Try(body, catches, x) def ENDTRY = Try(body, catches, fin) } @@ -251,16 +251,16 @@ trait TreeDSL { def DEFAULT: CaseStart = new CaseStart(WILD.empty, EmptyTree) class SymbolMethods(target: Symbol) { - // def BIND(body: Tree) = Bind(target, body) + def BIND(body: Tree) = Bind(target, body) def IS_NULL() = REF(target) OBJ_EQ NULL - // def NOT_NULL() = REF(target) OBJ_NE NULL + def NOT_NULL() = REF(target) OBJ_NE NULL def GET() = fn(REF(target), nme.get) // name of nth indexed argument to a method (first parameter list), defaults to 1st - // def ARG(idx: Int = 0) = Ident(target.paramss.head(idx)) + def ARG(idx: Int = 0) = Ident(target.paramss.head(idx)) def ARGS = target.paramss.head - // def ARGNAMES = ARGS map Ident + def ARGNAMES = ARGS map Ident } /** Top level accessible. */ @@ -268,31 +268,31 @@ trait TreeDSL { def THROW(sym: Symbol, msg: Tree): Throw = Throw(sym.tpe, msg.TOSTRING()) def NEW(tpt: Tree, args: Tree*): Tree = New(tpt, List(args.toList)) - // def NEW(sym: Symbol, args: Tree*): Tree = New(sym.tpe, args: _*) + def NEW(sym: Symbol, args: Tree*): Tree = New(sym.tpe, args: _*) - // def DEF(name: Name, tp: Type): DefTreeStart = DEF(name) withType tp - // def DEF(name: Name): DefTreeStart = new DefTreeStart(name) + def DEF(name: Name, tp: Type): DefTreeStart = DEF(name) withType tp + def DEF(name: Name): DefTreeStart = new DefTreeStart(name) def DEF(sym: Symbol): DefSymStart = new DefSymStart(sym) - // def VAL(name: Name, tp: Type): ValTreeStart = VAL(name) withType tp - // def VAL(name: Name): ValTreeStart = new ValTreeStart(name) + def VAL(name: Name, tp: Type): ValTreeStart = VAL(name) withType tp + def VAL(name: Name): ValTreeStart = new ValTreeStart(name) def VAL(sym: Symbol): ValSymStart = new ValSymStart(sym) - // def VAR(name: Name, tp: Type): ValTreeStart = VAL(name, tp) withFlags Flags.MUTABLE - // def VAR(name: Name): ValTreeStart = VAL(name) withFlags Flags.MUTABLE - // def VAR(sym: Symbol): ValSymStart = VAL(sym) withFlags Flags.MUTABLE + def VAR(name: Name, tp: Type): ValTreeStart = VAL(name, tp) withFlags Flags.MUTABLE + def VAR(name: Name): ValTreeStart = VAL(name) withFlags Flags.MUTABLE + def VAR(sym: Symbol): ValSymStart = VAL(sym) withFlags Flags.MUTABLE - // def LAZYVAL(name: Name, tp: Type): ValTreeStart = VAL(name, tp) withFlags Flags.LAZY - // def LAZYVAL(name: Name): ValTreeStart = VAL(name) withFlags Flags.LAZY - // def LAZYVAL(sym: Symbol): ValSymStart = VAL(sym) withFlags Flags.LAZY + def LAZYVAL(name: Name, tp: Type): ValTreeStart = VAL(name, tp) withFlags Flags.LAZY + def LAZYVAL(name: Name): ValTreeStart = VAL(name) withFlags Flags.LAZY + def LAZYVAL(sym: Symbol): ValSymStart = VAL(sym) withFlags Flags.LAZY def AND(guards: Tree*) = if (guards.isEmpty) EmptyTree else guards reduceLeft gen.mkAnd - // def OR(guards: Tree*) = - // if (guards.isEmpty) EmptyTree - // else guards reduceLeft gen.mkOr + def OR(guards: Tree*) = + if (guards.isEmpty) EmptyTree + else guards reduceLeft gen.mkOr def IF(tree: Tree) = new IfStart(tree, EmptyTree) def TRY(tree: Tree) = new TryStart(tree, Nil, EmptyTree) @@ -311,11 +311,11 @@ trait TreeDSL { case List(tree) if flattenUnary => tree case _ => Apply(TupleClass(trees.length).companionModule, trees: _*) } - // def makeTupleType(trees: List[Tree], flattenUnary: Boolean): Tree = trees match { - // case Nil => gen.scalaUnitConstr - // case List(tree) if flattenUnary => tree - // case _ => AppliedTypeTree(REF(TupleClass(trees.length)), trees) - // } + def makeTupleType(trees: List[Tree], flattenUnary: Boolean): Tree = trees match { + case Nil => gen.scalaUnitConstr + case List(tree) if flattenUnary => tree + case _ => AppliedTypeTree(REF(TupleClass(trees.length)), trees) + } /** Implicits - some of these should probably disappear **/ implicit def mkTreeMethods(target: Tree): TreeMethods = new TreeMethods(target) diff --git a/src/compiler/scala/tools/nsc/ast/TreeGen.scala b/src/compiler/scala/tools/nsc/ast/TreeGen.scala index ea7f674809..983f355c58 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeGen.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeGen.scala @@ -63,71 +63,71 @@ abstract class TreeGen extends scala.reflect.internal.TreeGen with TreeDSL { Annotated(New(scalaDot(UncheckedClass.name), ListOfNil), expr) } // if it's a Match, mark the selector unchecked; otherwise nothing. - // def mkUncheckedMatch(tree: Tree) = tree match { - // case Match(selector, cases) => atPos(tree.pos)(Match(mkUnchecked(selector), cases)) - // case _ => tree - // } + def mkUncheckedMatch(tree: Tree) = tree match { + case Match(selector, cases) => atPos(tree.pos)(Match(mkUnchecked(selector), cases)) + case _ => tree + } - // def mkSynthSwitchSelector(expr: Tree): Tree = atPos(expr.pos) { - // // This can't be "Annotated(New(SwitchClass), expr)" because annotations - // // are very picky about things and it crashes the compiler with "unexpected new". - // Annotated(Ident(nme.synthSwitch), expr) - // } + def mkSynthSwitchSelector(expr: Tree): Tree = atPos(expr.pos) { + // This can't be "Annotated(New(SwitchClass), expr)" because annotations + // are very picky about things and it crashes the compiler with "unexpected new". + Annotated(Ident(nme.synthSwitch), expr) + } // TODO: would be so much nicer if we would know during match-translation (i.e., type checking) // whether we should emit missingCase-style apply (and isDefinedAt), instead of transforming trees post-factum - // class MatchMatcher { - // def caseMatch(orig: Tree, selector: Tree, cases: List[CaseDef], wrap: Tree => Tree): Tree = unknownTree(orig) - // def caseVirtualizedMatch(orig: Tree, _match: Tree, targs: List[Tree], scrut: Tree, matcher: Tree): Tree = unknownTree(orig) - // def caseVirtualizedMatchOpt(orig: Tree, prologue: List[Tree], cases: List[Tree], matchEndDef: Tree, wrap: Tree => Tree): Tree = unknownTree(orig) - - // def genVirtualizedMatch(prologue: List[Tree], cases: List[Tree], matchEndDef: Tree): Tree = Block(prologue ++ cases, matchEndDef) - - // def apply(matchExpr: Tree): Tree = matchExpr match { - // // old-style match or virtpatmat switch - // case Match(selector, cases) => // println("simple match: "+ (selector, cases) + "for:\n"+ matchExpr ) - // caseMatch(matchExpr, selector, cases, identity) - // // old-style match or virtpatmat switch - // case Block((vd: ValDef) :: Nil, orig@Match(selector, cases)) => // println("block match: "+ (selector, cases, vd) + "for:\n"+ matchExpr ) - // caseMatch(matchExpr, selector, cases, m => copyBlock(matchExpr, List(vd), m)) - // // virtpatmat - // case Apply(Apply(TypeApply(Select(tgt, nme.runOrElse), targs), List(scrut)), List(matcher)) if !settings.XoldPatmat.value => // println("virt match: "+ (tgt, targs, scrut, matcher) + "for:\n"+ matchExpr ) - // caseVirtualizedMatch(matchExpr, tgt, targs, scrut, matcher) - // // optimized version of virtpatmat - // case Block(stats, matchEndDef) if !settings.XoldPatmat.value && (stats forall treeInfo.hasSynthCaseSymbol) => - // // the assumption is once we encounter a case, the remainder of the block will consist of cases - // // the prologue may be empty, usually it is the valdef that stores the scrut - // val (prologue, cases) = stats span (s => !s.isInstanceOf[LabelDef]) - // caseVirtualizedMatchOpt(matchExpr, prologue, cases, matchEndDef, identity) - // // optimized version of virtpatmat - // case Block(outerStats, orig@Block(stats, matchEndDef)) if !settings.XoldPatmat.value && (stats forall treeInfo.hasSynthCaseSymbol) => - // val (prologue, cases) = stats span (s => !s.isInstanceOf[LabelDef]) - // caseVirtualizedMatchOpt(matchExpr, prologue, cases, matchEndDef, m => copyBlock(matchExpr, outerStats, m)) - // case other => - // unknownTree(other) - // } - - // def unknownTree(t: Tree): Tree = throw new MatchError(t) - // def copyBlock(orig: Tree, stats: List[Tree], expr: Tree): Block = Block(stats, expr) - - // def dropSyntheticCatchAll(cases: List[CaseDef]): List[CaseDef] = - // if (settings.XoldPatmat.value) cases - // else cases filter { - // case CaseDef(pat, EmptyTree, Throw(Apply(Select(New(exTpt), nme.CONSTRUCTOR), _))) if (treeInfo.isWildcardArg(pat) && (exTpt.tpe.typeSymbol eq MatchErrorClass)) => false - // case CaseDef(pat, guard, body) => true - // } - // } - - // def mkCached(cvar: Symbol, expr: Tree): Tree = { - // val cvarRef = mkUnattributedRef(cvar) - // Block( - // List( - // If(Apply(Select(cvarRef, nme.eq), List(Literal(Constant(null)))), - // Assign(cvarRef, expr), - // EmptyTree)), - // cvarRef - // ) - // } + class MatchMatcher { + def caseMatch(orig: Tree, selector: Tree, cases: List[CaseDef], wrap: Tree => Tree): Tree = unknownTree(orig) + def caseVirtualizedMatch(orig: Tree, _match: Tree, targs: List[Tree], scrut: Tree, matcher: Tree): Tree = unknownTree(orig) + def caseVirtualizedMatchOpt(orig: Tree, prologue: List[Tree], cases: List[Tree], matchEndDef: Tree, wrap: Tree => Tree): Tree = unknownTree(orig) + + def genVirtualizedMatch(prologue: List[Tree], cases: List[Tree], matchEndDef: Tree): Tree = Block(prologue ++ cases, matchEndDef) + + def apply(matchExpr: Tree): Tree = matchExpr match { + // old-style match or virtpatmat switch + case Match(selector, cases) => // println("simple match: "+ (selector, cases) + "for:\n"+ matchExpr ) + caseMatch(matchExpr, selector, cases, identity) + // old-style match or virtpatmat switch + case Block((vd: ValDef) :: Nil, orig@Match(selector, cases)) => // println("block match: "+ (selector, cases, vd) + "for:\n"+ matchExpr ) + caseMatch(matchExpr, selector, cases, m => copyBlock(matchExpr, List(vd), m)) + // virtpatmat + case Apply(Apply(TypeApply(Select(tgt, nme.runOrElse), targs), List(scrut)), List(matcher)) if !settings.XoldPatmat.value => // println("virt match: "+ (tgt, targs, scrut, matcher) + "for:\n"+ matchExpr ) + caseVirtualizedMatch(matchExpr, tgt, targs, scrut, matcher) + // optimized version of virtpatmat + case Block(stats, matchEndDef) if !settings.XoldPatmat.value && (stats forall treeInfo.hasSynthCaseSymbol) => + // the assumption is once we encounter a case, the remainder of the block will consist of cases + // the prologue may be empty, usually it is the valdef that stores the scrut + val (prologue, cases) = stats span (s => !s.isInstanceOf[LabelDef]) + caseVirtualizedMatchOpt(matchExpr, prologue, cases, matchEndDef, identity) + // optimized version of virtpatmat + case Block(outerStats, orig@Block(stats, matchEndDef)) if !settings.XoldPatmat.value && (stats forall treeInfo.hasSynthCaseSymbol) => + val (prologue, cases) = stats span (s => !s.isInstanceOf[LabelDef]) + caseVirtualizedMatchOpt(matchExpr, prologue, cases, matchEndDef, m => copyBlock(matchExpr, outerStats, m)) + case other => + unknownTree(other) + } + + def unknownTree(t: Tree): Tree = throw new MatchError(t) + def copyBlock(orig: Tree, stats: List[Tree], expr: Tree): Block = Block(stats, expr) + + def dropSyntheticCatchAll(cases: List[CaseDef]): List[CaseDef] = + if (settings.XoldPatmat.value) cases + else cases filter { + case CaseDef(pat, EmptyTree, Throw(Apply(Select(New(exTpt), nme.CONSTRUCTOR), _))) if (treeInfo.isWildcardArg(pat) && (exTpt.tpe.typeSymbol eq MatchErrorClass)) => false + case CaseDef(pat, guard, body) => true + } + } + + def mkCached(cvar: Symbol, expr: Tree): Tree = { + val cvarRef = mkUnattributedRef(cvar) + Block( + List( + If(Apply(Select(cvarRef, nme.eq), List(Literal(Constant(null)))), + Assign(cvarRef, expr), + EmptyTree)), + cvarRef + ) + } // Builds a tree of the form "{ lhs = rhs ; lhs }" def mkAssignAndReturn(lhs: Symbol, rhs: Tree): Tree = { @@ -152,8 +152,8 @@ abstract class TreeGen extends scala.reflect.internal.TreeGen with TreeDSL { // def m: T = { if (m$ eq null) m$ = new m$class(...) m$ } // where (...) are eventual outer accessors - // def mkCachedModuleAccessDef(accessor: Symbol, mvar: Symbol) = - // DefDef(accessor, mkCached(mvar, newModule(accessor, mvar.tpe))) + def mkCachedModuleAccessDef(accessor: Symbol, mvar: Symbol) = + DefDef(accessor, mkCached(mvar, newModule(accessor, mvar.tpe))) def mkModuleAccessDef(accessor: Symbol, msym: Symbol) = DefDef(accessor, Select(This(msym.owner), msym)) @@ -165,8 +165,8 @@ abstract class TreeGen extends scala.reflect.internal.TreeGen with TreeDSL { } // def m: T; - // def mkModuleAccessDcl(accessor: Symbol) = - // DefDef(accessor setFlag lateDEFERRED, EmptyTree) + def mkModuleAccessDcl(accessor: Symbol) = + DefDef(accessor setFlag lateDEFERRED, EmptyTree) def mkRuntimeCall(meth: Name, args: List[Tree]): Tree = mkRuntimeCall(meth, Nil, args) @@ -223,8 +223,8 @@ abstract class TreeGen extends scala.reflect.internal.TreeGen with TreeDSL { if (isRepeatedParam) wildcardStar(arg) else arg /** Make forwarder to method `target`, passing all parameters in `params` */ - // def mkForwarder(target: Tree, vparamss: List[List[Symbol]]) = - // (target /: vparamss)((fn, vparams) => Apply(fn, vparams map paramToArg)) + def mkForwarder(target: Tree, vparamss: List[List[Symbol]]) = + (target /: vparamss)((fn, vparams) => Apply(fn, vparams map paramToArg)) /** Applies a wrapArray call to an array, making it a WrappedArray. * Don't let a reference type parameter be inferred, in case it's a singleton: @@ -264,24 +264,24 @@ abstract class TreeGen extends scala.reflect.internal.TreeGen with TreeDSL { else mkCast(tree, pt) - // def mkZeroContravariantAfterTyper(tp: Type): Tree = { - // // contravariant -- for replacing an argument in a method call - // // must use subtyping, as otherwise we miss types like `Any with Int` - // val tree = - // if (NullClass.tpe <:< tp) Literal(Constant(null)) - // else if (UnitClass.tpe <:< tp) Literal(Constant()) - // else if (BooleanClass.tpe <:< tp) Literal(Constant(false)) - // else if (FloatClass.tpe <:< tp) Literal(Constant(0.0f)) - // else if (DoubleClass.tpe <:< tp) Literal(Constant(0.0d)) - // else if (ByteClass.tpe <:< tp) Literal(Constant(0.toByte)) - // else if (ShortClass.tpe <:< tp) Literal(Constant(0.toShort)) - // else if (IntClass.tpe <:< tp) Literal(Constant(0)) - // else if (LongClass.tpe <:< tp) Literal(Constant(0L)) - // else if (CharClass.tpe <:< tp) Literal(Constant(0.toChar)) - // else mkCast(Literal(Constant(null)), tp) - - // tree - // } + def mkZeroContravariantAfterTyper(tp: Type): Tree = { + // contravariant -- for replacing an argument in a method call + // must use subtyping, as otherwise we miss types like `Any with Int` + val tree = + if (NullClass.tpe <:< tp) Literal(Constant(null)) + else if (UnitClass.tpe <:< tp) Literal(Constant()) + else if (BooleanClass.tpe <:< tp) Literal(Constant(false)) + else if (FloatClass.tpe <:< tp) Literal(Constant(0.0f)) + else if (DoubleClass.tpe <:< tp) Literal(Constant(0.0d)) + else if (ByteClass.tpe <:< tp) Literal(Constant(0.toByte)) + else if (ShortClass.tpe <:< tp) Literal(Constant(0.toShort)) + else if (IntClass.tpe <:< tp) Literal(Constant(0)) + else if (LongClass.tpe <:< tp) Literal(Constant(0L)) + else if (CharClass.tpe <:< tp) Literal(Constant(0.toChar)) + else mkCast(Literal(Constant(null)), tp) + + tree + } /** Translate names in Select/Ident nodes to type names. */ diff --git a/src/compiler/scala/tools/nsc/ast/TreeInfo.scala b/src/compiler/scala/tools/nsc/ast/TreeInfo.scala index 5c1ab29548..97227a5b6e 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeInfo.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeInfo.scala @@ -6,7 +6,7 @@ package scala.tools.nsc package ast -// import scala.reflect.internal.HasFlags +import scala.reflect.internal.HasFlags /** This class ... * @@ -39,6 +39,6 @@ abstract class TreeInfo extends scala.reflect.internal.TreeInfo { case _ => super.firstDefinesClassOrObject(trees, name) } - // def isInterface(mods: HasFlags, body: List[Tree]) = - // mods.isTrait && (body forall isInterfaceMember) + def isInterface(mods: HasFlags, body: List[Tree]) = + mods.isTrait && (body forall isInterfaceMember) } diff --git a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala index 501127865b..efcde1f74f 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala @@ -9,8 +9,7 @@ package scala.tools.nsc package ast.parser -import scala.collection.{ mutable, immutable } -import mutable.{ ListBuffer, StringBuilder } +import scala.collection.mutable.{ListBuffer, StringBuilder} import scala.reflect.internal.{ ModifierFlags => Flags } import scala.reflect.internal.Chars.{ isScalaLetter } import scala.reflect.internal.util.{ SourceFile, OffsetPosition } @@ -168,7 +167,7 @@ self => object symbXMLBuilder extends SymbolicXMLBuilder(this, preserveWS = true) { // DEBUG choices val global: self.global.type = self.global - // def freshName(prefix: String): Name = SourceFileParser.this.freshName(prefix) + def freshName(prefix: String): Name = SourceFileParser.this.freshName(prefix) } def xmlLiteral : Tree = xmlp.xLiteral @@ -464,7 +463,7 @@ self => /* ------------- ERROR HANDLING ------------------------------------------- */ - val assumedClosingParens = mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0) + var assumedClosingParens = scala.collection.mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0) private var inFunReturnType = false @inline private def fromWithinReturnType[T](body: => T): T = { @@ -641,7 +640,7 @@ self => case _ => false } - // def isTypeIntro: Boolean = isTypeIntroToken(in.token) + def isTypeIntro: Boolean = isTypeIntroToken(in.token) def isStatSeqEnd = in.token == RBRACE || in.token == EOF @@ -766,9 +765,9 @@ self => } } - // def checkSize(kind: String, size: Int, max: Int) { - // if (size > max) syntaxError("too many "+kind+", maximum = "+max, false) - // } + def checkSize(kind: String, size: Int, max: Int) { + if (size > max) syntaxError("too many "+kind+", maximum = "+max, false) + } def checkAssoc(offset: Int, op: Name, leftAssoc: Boolean) = if (treeInfo.isLeftAssoc(op) != leftAssoc) @@ -1219,10 +1218,10 @@ self => * EqualsExpr ::= `=' Expr * }}} */ - // def equalsExpr(): Tree = { - // accept(EQUALS) - // expr() - // } + def equalsExpr(): Tree = { + accept(EQUALS) + expr() + } def condExpr(): Tree = { if (in.token == LPAREN) { @@ -1965,7 +1964,7 @@ self => /** Default entry points into some pattern contexts. */ def pattern(): Tree = noSeq.pattern() - // def patterns(): List[Tree] = noSeq.patterns() + def patterns(): List[Tree] = noSeq.patterns() def seqPatterns(): List[Tree] = seqOK.patterns() def xmlSeqPatterns(): List[Tree] = xmlSeqOK.patterns() // Called from xml parser def argumentPatterns(): List[Tree] = inParens { diff --git a/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala b/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala index b346ce0a14..1be5fb1782 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala @@ -10,8 +10,7 @@ import scala.reflect.internal.util._ import scala.reflect.internal.Chars._ import Tokens._ import scala.annotation.switch -import scala.collection.{ mutable, immutable } -import mutable.{ ListBuffer, ArrayBuffer } +import scala.collection.mutable.{ ListBuffer, ArrayBuffer } import scala.xml.Utility.{ isNameStart } /** See Parsers.scala / ParsersCommon for some explanation of ScannersCommon. @@ -27,7 +26,7 @@ trait ScannersCommon { trait ScannerCommon extends CommonTokenData { // things to fill in, in addition to buf, decodeUni which come from CharArrayReader - // def warning(off: Int, msg: String): Unit + def warning(off: Int, msg: String): Unit def error (off: Int, msg: String): Unit def incompleteInputError(off: Int, msg: String): Unit def deprecationWarning(off: Int, msg: String): Unit @@ -52,7 +51,7 @@ trait Scanners extends ScannersCommon { type Offset = Int /** An undefined offset */ - // val NoOffset: Offset = -1 + val NoOffset: Offset = -1 trait TokenData extends CommonTokenData { @@ -89,7 +88,7 @@ trait Scanners extends ScannersCommon { def isAtEnd = charOffset >= buf.length - // def flush = { charOffset = offset; nextChar(); this } + def flush = { charOffset = offset; nextChar(); this } def resume(lastCode: Int) = { token = lastCode @@ -101,7 +100,7 @@ trait Scanners extends ScannersCommon { /** the last error offset */ - // var errOffset: Offset = NoOffset + var errOffset: Offset = NoOffset /** A character buffer for literals */ @@ -1064,7 +1063,7 @@ trait Scanners extends ScannersCommon { def syntaxError(off: Offset, msg: String) { error(off, msg) token = ERROR - // errOffset = off + errOffset = off } /** generate an error at the current token offset @@ -1077,7 +1076,7 @@ trait Scanners extends ScannersCommon { def incompleteInputError(msg: String) { incompleteInputError(offset, msg) token = EOF - // errOffset = offset + errOffset = offset } override def toString() = token match { @@ -1242,7 +1241,7 @@ trait Scanners extends ScannersCommon { override val decodeUni: Boolean = !settings.nouescape.value // suppress warnings, throw exception on errors - // def warning(off: Offset, msg: String): Unit = () + def warning(off: Offset, msg: String): Unit = () def deprecationWarning(off: Offset, msg: String): Unit = () def error (off: Offset, msg: String): Unit = throw new MalformedInput(off, msg) def incompleteInputError(off: Offset, msg: String): Unit = throw new MalformedInput(off, msg) @@ -1253,7 +1252,7 @@ trait Scanners extends ScannersCommon { class UnitScanner(unit: CompilationUnit, patches: List[BracePatch]) extends SourceFileScanner(unit.source) { def this(unit: CompilationUnit) = this(unit, List()) - // override def warning(off: Offset, msg: String) = unit.warning(unit.position(off), msg) + override def warning(off: Offset, msg: String) = unit.warning(unit.position(off), msg) override def deprecationWarning(off: Offset, msg: String) = unit.deprecationWarning(unit.position(off), msg) override def error (off: Offset, msg: String) = unit.error(unit.position(off), msg) override def incompleteInputError(off: Offset, msg: String) = unit.incompleteInputError(unit.position(off), msg) @@ -1312,7 +1311,7 @@ trait Scanners extends ScannersCommon { } class ParensAnalyzer(unit: CompilationUnit, patches: List[BracePatch]) extends UnitScanner(unit, patches) { - val balance = mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0) + var balance = scala.collection.mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0) init() @@ -1434,17 +1433,17 @@ trait Scanners extends ScannersCommon { else bp :: insertPatch(bps, patch) } - // def leftColumn(offset: Int) = - // if (offset == -1) -1 else column(lineStart(line(offset))) + def leftColumn(offset: Int) = + if (offset == -1) -1 else column(lineStart(line(offset))) - // def rightColumn(offset: Int, default: Int) = - // if (offset == -1) -1 - // else { - // val rlin = line(offset) - // if (lineStart(rlin) == offset) column(offset) - // else if (rlin + 1 < lineStart.length) column(lineStart(rlin + 1)) - // else default - // } + def rightColumn(offset: Int, default: Int) = + if (offset == -1) -1 + else { + val rlin = line(offset) + if (lineStart(rlin) == offset) column(offset) + else if (rlin + 1 < lineStart.length) column(lineStart(rlin + 1)) + else default + } def insertRBrace(): List[BracePatch] = { def insert(bps: List[BracePair]): List[BracePatch] = bps match { @@ -1487,16 +1486,16 @@ trait Scanners extends ScannersCommon { delete(bracePairs) } - // def imbalanceMeasure: Int = { - // def measureList(bps: List[BracePair]): Int = - // (bps map measure).sum - // def measure(bp: BracePair): Int = - // (if (bp.lindent != bp.rindent) 1 else 0) + measureList(bp.nested) - // measureList(bracePairs) - // } + def imbalanceMeasure: Int = { + def measureList(bps: List[BracePair]): Int = + (bps map measure).sum + def measure(bp: BracePair): Int = + (if (bp.lindent != bp.rindent) 1 else 0) + measureList(bp.nested) + measureList(bracePairs) + } - // def improves(patches1: List[BracePatch]): Boolean = - // imbalanceMeasure > new ParensAnalyzer(unit, patches1).imbalanceMeasure + def improves(patches1: List[BracePatch]): Boolean = + imbalanceMeasure > new ParensAnalyzer(unit, patches1).imbalanceMeasure override def error(offset: Int, msg: String) {} } diff --git a/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala b/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala index be8e1bc8b4..c3fd414426 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala @@ -6,14 +6,14 @@ package scala.tools.nsc package ast.parser -// import scala.annotation.switch +import scala.annotation.switch /** Common code between JavaTokens and Tokens. Not as much (and not as concrete) * as one might like because JavaTokens for no clear reason chose new numbers for * identical token sets. */ abstract class Tokens { - // import scala.reflect.internal.Chars._ + import scala.reflect.internal.Chars._ /** special tokens */ final val EMPTY = -3 @@ -32,16 +32,16 @@ abstract class Tokens { def LPAREN: Int def RBRACE: Int - // def isIdentifier(code: Int): Boolean + def isIdentifier(code: Int): Boolean def isLiteral(code: Int): Boolean - // def isKeyword(code: Int): Boolean - // def isSymbol(code: Int): Boolean - - // final def isSpace(at: Char) = at == ' ' || at == '\t' - // final def isNewLine(at: Char) = at == CR || at == LF || at == FF - // final def isBrace(code: Int) = code >= LPAREN && code <= RBRACE - // final def isOpenBrace(code: Int) = isBrace(code) && (code % 2 == 0) - // final def isCloseBrace(code: Int) = isBrace(code) && (code % 2 == 1) + def isKeyword(code: Int): Boolean + def isSymbol(code: Int): Boolean + + final def isSpace(at: Char) = at == ' ' || at == '\t' + final def isNewLine(at: Char) = at == CR || at == LF || at == FF + final def isBrace(code: Int) = code >= LPAREN && code <= RBRACE + final def isOpenBrace(code: Int) = isBrace(code) && (code % 2 == 0) + final def isCloseBrace(code: Int) = isBrace(code) && (code % 2 == 1) } object Tokens extends Tokens { @@ -56,16 +56,16 @@ object Tokens extends Tokens { /** identifiers */ final val IDENTIFIER = 10 final val BACKQUOTED_IDENT = 11 - // def isIdentifier(code: Int) = - // code >= IDENTIFIER && code <= BACKQUOTED_IDENT + def isIdentifier(code: Int) = + code >= IDENTIFIER && code <= BACKQUOTED_IDENT - // @switch def canBeginExpression(code: Int) = code match { - // case IDENTIFIER|BACKQUOTED_IDENT|USCORE => true - // case LBRACE|LPAREN|LBRACKET|COMMENT => true - // case IF|DO|WHILE|FOR|NEW|TRY|THROW => true - // case NULL|THIS|TRUE|FALSE => true - // case code => isLiteral(code) - // } + @switch def canBeginExpression(code: Int) = code match { + case IDENTIFIER|BACKQUOTED_IDENT|USCORE => true + case LBRACE|LPAREN|LBRACKET|COMMENT => true + case IF|DO|WHILE|FOR|NEW|TRY|THROW => true + case NULL|THIS|TRUE|FALSE => true + case code => isLiteral(code) + } /** keywords */ final val IF = 20 @@ -113,16 +113,16 @@ object Tokens extends Tokens { final val MACRO = 62 // not yet used in 2.10 final val THEN = 63 // not yet used in 2.10 - // def isKeyword(code: Int) = - // code >= IF && code <= LAZY + def isKeyword(code: Int) = + code >= IF && code <= LAZY - // @switch def isDefinition(code: Int) = code match { - // case CLASS|TRAIT|OBJECT => true - // case CASECLASS|CASEOBJECT => true - // case DEF|VAL|VAR => true - // case TYPE => true - // case _ => false - // } + @switch def isDefinition(code: Int) = code match { + case CLASS|TRAIT|OBJECT => true + case CASECLASS|CASEOBJECT => true + case DEF|VAL|VAR => true + case TYPE => true + case _ => false + } /** special symbols */ final val COMMA = 70 @@ -141,8 +141,8 @@ object Tokens extends Tokens { final val AT = 83 final val VIEWBOUND = 84 - // def isSymbol(code: Int) = - // code >= COMMA && code <= VIEWBOUND + def isSymbol(code: Int) = + code >= COMMA && code <= VIEWBOUND /** parenthesis */ final val LPAREN = 90 diff --git a/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala b/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala index 6dc2055121..49b772ed2c 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala @@ -26,15 +26,15 @@ abstract class TreeBuilder { def o2p(offset: Int): Position def r2p(start: Int, point: Int, end: Int): Position - // def rootId(name: Name) = gen.rootId(name) + def rootId(name: Name) = gen.rootId(name) def rootScalaDot(name: Name) = gen.rootScalaDot(name) def scalaDot(name: Name) = gen.scalaDot(name) def scalaAnyRefConstr = scalaDot(tpnme.AnyRef) - // def scalaAnyValConstr = scalaDot(tpnme.AnyVal) - // def scalaAnyConstr = scalaDot(tpnme.Any) + def scalaAnyValConstr = scalaDot(tpnme.AnyVal) + def scalaAnyConstr = scalaDot(tpnme.Any) def scalaUnitConstr = scalaDot(tpnme.Unit) def productConstr = scalaDot(tpnme.Product) - // def productConstrN(n: Int) = scalaDot(newTypeName("Product" + n)) + def productConstrN(n: Int) = scalaDot(newTypeName("Product" + n)) def serializableConstr = scalaDot(tpnme.Serializable) def convertToTypeName(t: Tree) = gen.convertToTypeName(t) @@ -446,15 +446,15 @@ abstract class TreeBuilder { /** Create tree for a lifted expression XX-LIFTING */ - // def makeLifted(gs: List[ValFrom], body: Tree): Tree = { - // def combine(gs: List[ValFrom]): ValFrom = (gs: @unchecked) match { - // case g :: Nil => g - // case ValFrom(pos1, pat1, rhs1) :: gs2 => - // val ValFrom(_, pat2, rhs2) = combine(gs2) - // ValFrom(pos1, makeTuple(List(pat1, pat2), false), Apply(Select(rhs1, nme.zip), List(rhs2))) - // } - // makeForYield(List(combine(gs)), body) - // } + def makeLifted(gs: List[ValFrom], body: Tree): Tree = { + def combine(gs: List[ValFrom]): ValFrom = (gs: @unchecked) match { + case g :: Nil => g + case ValFrom(pos1, pat1, rhs1) :: gs2 => + val ValFrom(_, pat2, rhs2) = combine(gs2) + ValFrom(pos1, makeTuple(List(pat1, pat2), false), Apply(Select(rhs1, nme.zip), List(rhs2))) + } + makeForYield(List(combine(gs)), body) + } /** Create tree for a pattern alternative */ def makeAlternative(ts: List[Tree]): Tree = { diff --git a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala index 52fc3d08e1..b62d5cb4e4 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala @@ -281,12 +281,12 @@ trait BasicBlocks { } /** Insert instructions in 'is' immediately after index 'idx'. */ - // def insertAfter(idx: Int, is: List[Instruction]) { - // assert(closed, "Instructions can be replaced only after the basic block is closed") + def insertAfter(idx: Int, is: List[Instruction]) { + assert(closed, "Instructions can be replaced only after the basic block is closed") - // instrs = instrs.patch(idx + 1, is, 0) - // code.touched = true - // } + instrs = instrs.patch(idx + 1, is, 0) + code.touched = true + } /** Removes instructions found at the given positions. * @@ -436,10 +436,10 @@ trait BasicBlocks { ignore = true } - // def exitIgnoreMode() { - // assert(ignore, "Exit ignore mode when not in ignore mode: " + this) - // ignore = false - // } + def exitIgnoreMode() { + assert(ignore, "Exit ignore mode when not in ignore mode: " + this) + ignore = false + } /** Return the last instruction of this basic block. */ def lastInstruction = @@ -498,15 +498,15 @@ trait BasicBlocks { override def hashCode = label * 41 + code.hashCode // Instead of it, rather use a printer - // def print() { print(java.lang.System.out) } - - // def print(out: java.io.PrintStream) { - // out.println("block #"+label+" :") - // foreach(i => out.println(" " + i)) - // out.print("Successors: ") - // successors.foreach((x: BasicBlock) => out.print(" "+x.label.toString())) - // out.println() - // } + def print() { print(java.lang.System.out) } + + def print(out: java.io.PrintStream) { + out.println("block #"+label+" :") + foreach(i => out.println(" " + i)) + out.print("Successors: ") + successors.foreach((x: BasicBlock) => out.print(" "+x.label.toString())) + out.println() + } private def succString = if (successors.isEmpty) "[S: N/A]" else successors.distinct.mkString("[S: ", ", ", "]") private def predString = if (predecessors.isEmpty) "[P: N/A]" else predecessors.distinct.mkString("[P: ", ", ", "]") diff --git a/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala b/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala index e1732d5775..f35996eeb9 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala @@ -72,9 +72,9 @@ trait ExceptionHandlers { override def dup: Finalizer = new Finalizer(method, label, pos) } - // object NoFinalizer extends Finalizer(null, newTermNameCached(""), NoPosition) { - // override def startBlock: BasicBlock = sys.error("NoFinalizer cannot have a start block."); - // override def setStartBlock(b: BasicBlock): Unit = sys.error("NoFinalizer cannot have a start block."); - // override def dup = this - // } + object NoFinalizer extends Finalizer(null, newTermNameCached(""), NoPosition) { + override def startBlock: BasicBlock = sys.error("NoFinalizer cannot have a start block."); + override def setStartBlock(b: BasicBlock): Unit = sys.error("NoFinalizer cannot have a start block."); + override def dup = this + } } diff --git a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala index d521f893d1..720896d0b3 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala @@ -1960,12 +1960,12 @@ abstract class GenICode extends SubComponent { this } - // def removeFinalizer(f: Tree): this.type = { - // assert(cleanups.head contains f, - // "Illegal nesting of cleanup operations: " + cleanups + " while exiting finalizer " + f); - // cleanups = cleanups.tail - // this - // } + def removeFinalizer(f: Tree): this.type = { + assert(cleanups.head contains f, + "Illegal nesting of cleanup operations: " + cleanups + " while exiting finalizer " + f); + cleanups = cleanups.tail + this + } /** Prepare a new context upon entry into a method. * @@ -2044,14 +2044,14 @@ abstract class GenICode extends SubComponent { } /** Remove the given handler from the list of active exception handlers. */ - // def removeActiveHandler(exh: ExceptionHandler): Unit = { - // assert(handlerCount > 0 && handlers.head == exh, - // "Wrong nesting of exception handlers." + this + " for " + exh) - // handlerCount -= 1 - // handlers = handlers.tail - // debuglog("removed handler: " + exh); + def removeActiveHandler(exh: ExceptionHandler): Unit = { + assert(handlerCount > 0 && handlers.head == exh, + "Wrong nesting of exception handlers." + this + " for " + exh) + handlerCount -= 1 + handlers = handlers.tail + debuglog("removed handler: " + exh); - // } + } /** Clone the current context */ def dup: Context = new Context(this) @@ -2339,7 +2339,7 @@ abstract class GenICode extends SubComponent { val locals: ListBuffer[Local] = new ListBuffer def add(l: Local) = locals += l - // def remove(l: Local) = locals -= l + def remove(l: Local) = locals -= l /** Return all locals that are in scope. */ def varsInScope: Buffer[Local] = outer.varsInScope.clone() ++= locals diff --git a/src/compiler/scala/tools/nsc/backend/icode/Members.scala b/src/compiler/scala/tools/nsc/backend/icode/Members.scala index 4192d794f9..07abe9d74f 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Members.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Members.scala @@ -126,9 +126,9 @@ trait Members { override def toString() = symbol.fullName - // def lookupField(s: Symbol) = fields find (_.symbol == s) + def lookupField(s: Symbol) = fields find (_.symbol == s) def lookupMethod(s: Symbol) = methods find (_.symbol == s) - // def lookupMethod(s: Name) = methods find (_.symbol.name == s) + def lookupMethod(s: Name) = methods find (_.symbol.name == s) /* returns this methods static ctor if it has one. */ def lookupStaticCtor: Option[IMethod] = methods find (_.symbol.isStaticConstructor) @@ -159,7 +159,7 @@ trait Members { def linearizedBlocks(lin: Linearizer = self.linearizer): List[BasicBlock] = lin linearize this def foreachBlock[U](f: BasicBlock => U): Unit = blocks foreach f - // def foreachInstr[U](f: Instruction => U): Unit = foreachBlock(_.toList foreach f) + def foreachInstr[U](f: Instruction => U): Unit = foreachBlock(_.toList foreach f) var native = false @@ -192,7 +192,7 @@ trait Members { } def addLocals(ls: List[Local]) = ls foreach addLocal - // def addParams(as: List[Local]) = as foreach addParam + def addParams(as: List[Local]) = as foreach addParam def lookupLocal(n: Name): Option[Local] = locals find (_.sym.name == n) def lookupLocal(sym: Symbol): Option[Local] = locals find (_.sym == sym) @@ -207,28 +207,28 @@ trait Members { override def toString() = symbol.fullName - // def matchesSignature(other: IMethod) = { - // (symbol.name == other.symbol.name) && - // (params corresponds other.params)(_.kind == _.kind) && - // (returnType == other.returnType) - // } + def matchesSignature(other: IMethod) = { + (symbol.name == other.symbol.name) && + (params corresponds other.params)(_.kind == _.kind) && + (returnType == other.returnType) + } import opcodes._ - // def checkLocals(): Unit = { - // def localsSet = (code.blocks flatMap { bb => - // bb.iterator collect { - // case LOAD_LOCAL(l) => l - // case STORE_LOCAL(l) => l - // } - // }).toSet - - // if (hasCode) { - // log("[checking locals of " + this + "]") - // locals filterNot localsSet foreach { l => - // log("Local " + l + " is not declared in " + this) - // } - // } - // } + def checkLocals(): Unit = { + def localsSet = (code.blocks flatMap { bb => + bb.iterator collect { + case LOAD_LOCAL(l) => l + case STORE_LOCAL(l) => l + } + }).toSet + + if (hasCode) { + log("[checking locals of " + this + "]") + locals filterNot localsSet foreach { l => + log("Local " + l + " is not declared in " + this) + } + } + } /** Merge together blocks that have a single successor which has a * single predecessor. Exception handlers are taken into account (they @@ -295,7 +295,7 @@ trait Members { var start: Int = _ /** Ending PC for this local's visibility range. */ - // var end: Int = _ + var end: Int = _ /** PC-based ranges for this local variable's visibility */ var ranges: List[(Int, Int)] = Nil diff --git a/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala b/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala index 6f7db042e6..0e7c75de50 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala @@ -111,7 +111,7 @@ trait Opcodes { self: ICodes => def producedTypes: List[TypeKind] = Nil /** This method returns the difference of size of the stack when the instruction is used */ - // def difference = produced-consumed + def difference = produced-consumed /** The corresponding position in the source file */ private var _pos: Position = NoPosition @@ -119,7 +119,7 @@ trait Opcodes { self: ICodes => def pos: Position = _pos /** Used by dead code elimination. */ - // var useful: Boolean = false + var useful: Boolean = false def setPos(p: Position): this.type = { _pos = p @@ -133,11 +133,11 @@ trait Opcodes { self: ICodes => object opcodes { - // def mayThrow(i: Instruction): Boolean = i match { - // case LOAD_LOCAL(_) | STORE_LOCAL(_) | CONSTANT(_) | THIS(_) | CZJUMP(_, _, _, _) - // | DROP(_) | DUP(_) | RETURN(_) | LOAD_EXCEPTION(_) | JUMP(_) | CJUMP(_, _, _, _) => false - // case _ => true - // } + def mayThrow(i: Instruction): Boolean = i match { + case LOAD_LOCAL(_) | STORE_LOCAL(_) | CONSTANT(_) | THIS(_) | CZJUMP(_, _, _, _) + | DROP(_) | DUP(_) | RETURN(_) | LOAD_EXCEPTION(_) | JUMP(_) | CJUMP(_, _, _, _) => false + case _ => true + } /** Loads "this" on top of the stack. * Stack: ... @@ -714,7 +714,7 @@ trait Opcodes { self: ICodes => /** Is this a static method call? */ def isStatic: Boolean = false - // def isSuper: Boolean = false + def isSuper: Boolean = false /** Is this an instance method call? */ def hasInstance: Boolean = true @@ -749,7 +749,7 @@ trait Opcodes { self: ICodes => * On JVM, translated to `invokespecial`. */ case class SuperCall(mix: Name) extends InvokeStyle { - // override def isSuper = true + override def isSuper = true override def toString(): String = { "super(" + mix + ")" } } @@ -814,7 +814,7 @@ trait Opcodes { self: ICodes => case class CIL_NEWOBJ(method: Symbol) extends Instruction { override def toString(): String = "CIL_NEWOBJ " + hostClass.fullName + method.fullName - val hostClass: Symbol = method.owner; + var hostClass: Symbol = method.owner; override def consumed = method.tpe.paramTypes.length override def consumedTypes = method.tpe.paramTypes map toTypeKind override def produced = 1 diff --git a/src/compiler/scala/tools/nsc/backend/icode/Primitives.scala b/src/compiler/scala/tools/nsc/backend/icode/Primitives.scala index ebfb4ad591..c8579041ba 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Primitives.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Primitives.scala @@ -84,17 +84,17 @@ trait Primitives { self: ICodes => def print(o: AnyRef): PrimitivePrinter = print(o.toString()) - // def printPrimitive(prim: Primitive) = prim match { - // case Negation(kind) => - // print("!") + def printPrimitive(prim: Primitive) = prim match { + case Negation(kind) => + print("!") - // case Test(op, kind, zero) => - // print(op).print(kind) + case Test(op, kind, zero) => + print(op).print(kind) - // case Comparison(op, kind) => - // print(op).print("(").print(kind) + case Comparison(op, kind) => + print(op).print("(").print(kind) - // } + } } /** This class represents a comparison operation. */ diff --git a/src/compiler/scala/tools/nsc/backend/icode/Repository.scala b/src/compiler/scala/tools/nsc/backend/icode/Repository.scala index c8168cbfa6..e73015c4da 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Repository.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Repository.scala @@ -29,13 +29,13 @@ trait Repository { /** The icode of the given class. If not available, it loads * its bytecode. */ - // def icode(sym: Symbol, force: Boolean): IClass = - // icode(sym) getOrElse { - // log("loading " + sym) - // load(sym) - // assert(available(sym)) - // loaded(sym) - // } + def icode(sym: Symbol, force: Boolean): IClass = + icode(sym) getOrElse { + log("loading " + sym) + load(sym) + assert(available(sym)) + loaded(sym) + } /** Load bytecode for given symbol. */ def load(sym: Symbol): Boolean = { diff --git a/src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala b/src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala index 2df6811fd7..f96dce9f1c 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala @@ -66,7 +66,7 @@ trait TypeKinds { self: ICodes => def isValueType = false def isBoxedType = false final def isRefOrArrayType = isReferenceType || isArrayType - // final def isRefArrayOrBoxType = isRefOrArrayType || isBoxedType + final def isRefArrayOrBoxType = isRefOrArrayType || isBoxedType final def isNothingType = this == NothingReference final def isNullType = this == NullReference final def isInterfaceType = this match { @@ -114,7 +114,7 @@ trait TypeKinds { self: ICodes => } } - // var lubs0 = 0 + var lubs0 = 0 /** * The least upper bound of two typekinds. They have to be either diff --git a/src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala b/src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala index c958f20853..c1bf4304ea 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala @@ -20,7 +20,7 @@ trait TypeStacks { */ type Rep = List[TypeKind] - // object NoTypeStack extends TypeStack(Nil) { } + object NoTypeStack extends TypeStack(Nil) { } class TypeStack(var types: Rep) { if (types.nonEmpty) @@ -74,8 +74,8 @@ trait TypeStacks { * length and each type kind agrees position-wise. Two * types agree if one is a subtype of the other. */ - // def agreesWith(other: TypeStack): Boolean = - // (types corresponds other.types)((t1, t2) => t1 <:< t2 || t2 <:< t1) + def agreesWith(other: TypeStack): Boolean = + (types corresponds other.types)((t1, t2) => t1 <:< t2 || t2 <:< t1) /* This method returns a String representation of the stack */ override def toString() = diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala index 6534cd83f1..53111d0ade 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala @@ -27,10 +27,10 @@ abstract class CopyPropagation { /** Values that can be on the stack. */ abstract class Value { - // def isRecord = false + def isRecord = false } case class Record(cls: Symbol, bindings: mutable.Map[Symbol, Value]) extends Value { - // override def isRecord = true + override def isRecord = true } /** The value of some location in memory. */ case class Deref(l: Location) extends Value @@ -92,14 +92,14 @@ abstract class CopyPropagation { } /* Return the binding for the given field of the given record */ - // def getBinding(r: Record, f: Symbol): Value = { - // assert(r.bindings contains f, "Record " + r + " does not contain a field " + f) - - // r.bindings(f) match { - // case Deref(LocalVar(l)) => getBinding(l) - // case target => target - // } - // } + def getBinding(r: Record, f: Symbol): Value = { + assert(r.bindings contains f, "Record " + r + " does not contain a field " + f) + + r.bindings(f) match { + case Deref(LocalVar(l)) => getBinding(l) + case target => target + } + } /** Return a local which contains the same value as this field, if any. * If the field holds a reference to a local, the returned value is the diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala index c232c3692a..04c3eedbad 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala @@ -37,11 +37,11 @@ trait DataFlowAnalysis[L <: SemiLattice] { /** Reinitialize, but keep the old solutions. Should be used when reanalyzing the * same method, after some code transformation. */ - // def reinit(f: => Unit): Unit = { - // iterations = 0 - // worklist.clear; visited.clear; - // f - // } + def reinit(f: => Unit): Unit = { + iterations = 0 + worklist.clear; visited.clear; + f + } def run(): Unit diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala index 6e7ed9d4c4..15755f31ad 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala @@ -269,34 +269,34 @@ abstract class TypeFlowAnalysis { } // interpret - // class SimulatedStack { - // private var types: List[InferredType] = Nil - // private var depth = 0 - - // /** Remove and return the topmost element on the stack. If the - // * stack is empty, return a reference to a negative index on the - // * stack, meaning it refers to elements pushed by a predecessor block. - // */ - // def pop: InferredType = types match { - // case head :: rest => - // types = rest - // head - // case _ => - // depth -= 1 - // TypeOfStackPos(depth) - // } - - // def pop2: (InferredType, InferredType) = { - // (pop, pop) - // } - - // def push(t: InferredType) { - // depth += 1 - // types = types ::: List(t) - // } - - // def push(k: TypeKind) { push(Const(k)) } - // } + class SimulatedStack { + private var types: List[InferredType] = Nil + private var depth = 0 + + /** Remove and return the topmost element on the stack. If the + * stack is empty, return a reference to a negative index on the + * stack, meaning it refers to elements pushed by a predecessor block. + */ + def pop: InferredType = types match { + case head :: rest => + types = rest + head + case _ => + depth -= 1 + TypeOfStackPos(depth) + } + + def pop2: (InferredType, InferredType) = { + (pop, pop) + } + + def push(t: InferredType) { + depth += 1 + types = types ::: List(t) + } + + def push(k: TypeKind) { push(Const(k)) } + } abstract class InferredType { /** Return the type kind pointed by this inferred type. */ @@ -737,9 +737,9 @@ abstract class TypeFlowAnalysis { private var lastStart = 0L - // def reset() { - // millis = 0L - // } + def reset() { + millis = 0L + } def start() { lastStart = System.currentTimeMillis diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala index 4a46a64dae..8bae80c760 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala @@ -455,7 +455,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { /** basic functionality for class file building */ abstract class JBuilder(bytecodeWriter: BytecodeWriter) { - // val EMPTY_JTYPE_ARRAY = Array.empty[asm.Type] + val EMPTY_JTYPE_ARRAY = Array.empty[asm.Type] val EMPTY_STRING_ARRAY = Array.empty[String] val mdesc_arglessvoid = "()V" @@ -523,7 +523,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { /** Specialized array conversion to prevent calling * java.lang.reflect.Array.newInstance via TraversableOnce.toArray */ - // def mkArray(xs: Traversable[asm.Type]): Array[asm.Type] = { val a = new Array[asm.Type](xs.size); xs.copyToArray(a); a } + def mkArray(xs: Traversable[asm.Type]): Array[asm.Type] = { val a = new Array[asm.Type](xs.size); xs.copyToArray(a); a } def mkArray(xs: Traversable[String]): Array[String] = { val a = new Array[String](xs.size); xs.copyToArray(a); a } // ----------------------------------------------------------------------------------------- @@ -1757,10 +1757,10 @@ abstract class GenASM extends SubComponent with BytecodeWriters { import asm.Opcodes; - // def aconst(cst: AnyRef) { - // if (cst == null) { jmethod.visitInsn(Opcodes.ACONST_NULL) } - // else { jmethod.visitLdcInsn(cst) } - // } + def aconst(cst: AnyRef) { + if (cst == null) { jmethod.visitInsn(Opcodes.ACONST_NULL) } + else { jmethod.visitLdcInsn(cst) } + } final def boolconst(b: Boolean) { iconst(if(b) 1 else 0) } diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala index e258f38284..06f94ef46c 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala @@ -182,15 +182,15 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with val StringBuilderType = new JObjectType(StringBuilderClassName) // TODO use ASMType.getObjectType val toStringType = new JMethodType(JAVA_LANG_STRING, JType.EMPTY_ARRAY) // TODO use ASMType.getMethodType val arrayCloneType = new JMethodType(JAVA_LANG_OBJECT, JType.EMPTY_ARRAY) - // val MethodTypeType = new JObjectType("java.dyn.MethodType") - // val JavaLangClassType = new JObjectType("java.lang.Class") - // val MethodHandleType = new JObjectType("java.dyn.MethodHandle") + val MethodTypeType = new JObjectType("java.dyn.MethodType") + val JavaLangClassType = new JObjectType("java.lang.Class") + val MethodHandleType = new JObjectType("java.dyn.MethodHandle") // Scala attributes val BeanInfoAttr = rootMirror.getRequiredClass("scala.beans.BeanInfo") - // val BeanInfoSkipAttr = rootMirror.getRequiredClass("scala.beans.BeanInfoSkip") - // val BeanDisplayNameAttr = rootMirror.getRequiredClass("scala.beans.BeanDisplayName") - // val BeanDescriptionAttr = rootMirror.getRequiredClass("scala.beans.BeanDescription") + val BeanInfoSkipAttr = rootMirror.getRequiredClass("scala.beans.BeanInfoSkip") + val BeanDisplayNameAttr = rootMirror.getRequiredClass("scala.beans.BeanDisplayName") + val BeanDescriptionAttr = rootMirror.getRequiredClass("scala.beans.BeanDescription") final val ExcludedForwarderFlags = { import Flags._ @@ -264,8 +264,8 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with val fjbgContext = new FJBGContext(49, 0) - // val emitSource = debugLevel >= 1 - // val emitLines = debugLevel >= 2 + val emitSource = debugLevel >= 1 + val emitLines = debugLevel >= 2 val emitVars = debugLevel >= 3 // bug had phase with wrong name; leaving enabled for brief pseudo deprecation @@ -1843,14 +1843,14 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with ////////////////////// local vars /////////////////////// - // def sizeOf(sym: Symbol): Int = sizeOf(toTypeKind(sym.tpe)) + def sizeOf(sym: Symbol): Int = sizeOf(toTypeKind(sym.tpe)) def sizeOf(k: TypeKind): Int = if(k.isWideType) 2 else 1 - // def indexOf(m: IMethod, sym: Symbol): Int = { - // val Some(local) = m lookupLocal sym - // indexOf(local) - // } + def indexOf(m: IMethod, sym: Symbol): Int = { + val Some(local) = m lookupLocal sym + indexOf(local) + } def indexOf(local: Local): Int = { assert(local.index >= 0, "Invalid index for: " + local + "{" + local.## + "}: ") diff --git a/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala b/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala index f7278a7590..2253ae6e15 100644 --- a/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala +++ b/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala @@ -23,7 +23,7 @@ abstract class GenMSIL extends SubComponent { import icodes._ import icodes.opcodes._ - // val x = loaders + val x = loaders /** Create a new phase */ override def newPhase(p: Phase) = new MsilPhase(p) @@ -83,9 +83,9 @@ abstract class GenMSIL extends SubComponent { SYMTAB_DEFAULT_CONSTR => SYMTAB_ATTRIBUTE_EMPTY_CONSTRUCTOR} val EXCEPTION = clrTypes.getType("System.Exception") - // val MBYTE_ARRAY = clrTypes.mkArrayType(MBYTE) + val MBYTE_ARRAY = clrTypes.mkArrayType(MBYTE) - // val ICLONEABLE = clrTypes.getType("System.ICloneable") + val ICLONEABLE = clrTypes.getType("System.ICloneable") val MEMBERWISE_CLONE = MOBJECT.GetMethod("MemberwiseClone", MsilType.EmptyTypes) val MMONITOR = clrTypes.getType("System.Threading.Monitor") @@ -102,8 +102,8 @@ abstract class GenMSIL extends SubComponent { val INT_PTR = clrTypes.getType("System.IntPtr") - // val JOBJECT = definitions.ObjectClass - // val JSTRING = definitions.StringClass + val JOBJECT = definitions.ObjectClass + val JSTRING = definitions.StringClass val SystemConvert = clrTypes.getType("System.Convert") @@ -622,7 +622,7 @@ abstract class GenMSIL extends SubComponent { * - emit `Leave handlerReturnLabel` instead of the Return * - emit code at the end: load the local and return its value */ - val currentHandlers = new mutable.Stack[ExceptionHandler] + var currentHandlers = new mutable.Stack[ExceptionHandler] // The IMethod the Local/Label/Kind below belong to var handlerReturnMethod: IMethod = _ // Stores the result when returning inside an exception block diff --git a/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala b/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala index b36e7a4636..8d6de821bb 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala @@ -189,8 +189,8 @@ abstract class ClosureElimination extends SubComponent { } /** is field 'f' accessible from method 'm'? */ - // def accessible(f: Symbol, m: Symbol): Boolean = - // f.isPublic || (f.isProtected && (f.enclosingPackageClass == m.enclosingPackageClass)) + def accessible(f: Symbol, m: Symbol): Boolean = + f.isPublic || (f.isProtected && (f.enclosingPackageClass == m.enclosingPackageClass)) } /* class ClosureElim */ diff --git a/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala b/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala index eaeba69382..7d741aab60 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala @@ -602,7 +602,7 @@ abstract class Inliners extends SubComponent { override def toString = m.toString val sym = m.symbol - // val name = sym.name + val name = sym.name def owner = sym.owner def paramTypes = sym.info.paramTypes def minimumStack = paramTypes.length + 1 @@ -624,7 +624,7 @@ abstract class Inliners extends SubComponent { def isLarge = length > MAX_INLINE_SIZE def isRecursive = m.recursive def hasHandlers = handlers.nonEmpty || m.bytecodeHasEHs - // def hasClosureParam = paramTypes exists (tp => isByNameParamType(tp) || isFunctionType(tp)) + def hasClosureParam = paramTypes exists (tp => isByNameParamType(tp) || isFunctionType(tp)) def isSynchronized = sym.hasFlag(Flags.SYNCHRONIZED) def hasNonFinalizerHandler = handlers exists { @@ -732,7 +732,7 @@ abstract class Inliners extends SubComponent { */ sealed abstract class InlineSafetyInfo { def isSafe = false - // def isUnsafe = !isSafe + def isUnsafe = !isSafe } case object NeverSafeToInline extends InlineSafetyInfo case object InlineableAtThisCaller extends InlineSafetyInfo { override def isSafe = true } diff --git a/src/compiler/scala/tools/nsc/doc/html/Page.scala b/src/compiler/scala/tools/nsc/doc/html/Page.scala index d502f19e31..62166f7def 100644 --- a/src/compiler/scala/tools/nsc/doc/html/Page.scala +++ b/src/compiler/scala/tools/nsc/doc/html/Page.scala @@ -90,9 +90,9 @@ abstract class Page { /** A relative link from this page to some destination page in the Scaladoc site. * @param destPage The page that the link will point to. */ - // def relativeLinkTo(destPage: HtmlPage): String = { - // relativeLinkTo(destPage.path) - // } + def relativeLinkTo(destPage: HtmlPage): String = { + relativeLinkTo(destPage.path) + } /** A relative link from this page to some destination path. * @param destPath The path that the link will point to. */ diff --git a/src/compiler/scala/tools/nsc/doc/model/Entity.scala b/src/compiler/scala/tools/nsc/doc/model/Entity.scala index 496dfdefcf..6b24073339 100644 --- a/src/compiler/scala/tools/nsc/doc/model/Entity.scala +++ b/src/compiler/scala/tools/nsc/doc/model/Entity.scala @@ -25,7 +25,7 @@ import diagram._ trait Entity { /** Similar to symbols, so we can track entities */ - // def id: Int + def id: Int /** The name of the entity. Note that the name does not qualify this entity uniquely; use its `qualifiedName` * instead. */ @@ -61,7 +61,7 @@ trait Entity { def isType: Boolean /** Indicates whether this entity lives in the terms namespace (objects, packages, methods, values) */ - // def isTerm: Boolean + def isTerm: Boolean } object Entity { @@ -98,7 +98,7 @@ trait TemplateEntity extends Entity { def isDocTemplate: Boolean /** Whether documentation is available for this template. */ - // def isNoDocMemberTemplate: Boolean + def isNoDocMemberTemplate: Boolean /** Whether this template is a case class. */ def isCaseClass: Boolean @@ -175,10 +175,10 @@ trait MemberEntity extends Entity { def isAbstractType: Boolean /** Whether this member is a template. */ - // def isTemplate: Boolean + def isTemplate: Boolean /** Whether this member is implicit. */ - // def isImplicit: Boolean + def isImplicit: Boolean /** Whether this member is abstract. */ def isAbstract: Boolean @@ -388,7 +388,7 @@ trait NonTemplateMemberEntity extends MemberEntity { /** Whether this member is a bridge member. A bridge member does only exist for binary compatibility reasons * and should not appear in ScalaDoc. */ - // def isBridge: Boolean + def isBridge: Boolean } @@ -507,7 +507,7 @@ trait ImplicitConversion { * Note: not all targetTypes have a corresponding template. Examples include conversions resulting in refinement * types. Need to check it's not option! */ - // def targetTemplate: Option[TemplateEntity] + def targetTemplate: Option[TemplateEntity] /** The components of the implicit conversion type parents */ def targetTypeComponents: List[(TemplateEntity, TypeEntity)] diff --git a/src/compiler/scala/tools/nsc/doc/model/IndexModelFactory.scala b/src/compiler/scala/tools/nsc/doc/model/IndexModelFactory.scala index 0f2374a6f4..10e2f23142 100755 --- a/src/compiler/scala/tools/nsc/doc/model/IndexModelFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/model/IndexModelFactory.scala @@ -18,7 +18,7 @@ object IndexModelFactory { object result extends mutable.HashMap[Char,SymbolMap] { /* Owner template ordering */ - // implicit def orderingSet = math.Ordering.String.on { x: MemberEntity => x.name.toLowerCase } + implicit def orderingSet = math.Ordering.String.on { x: MemberEntity => x.name.toLowerCase } /* symbol name ordering */ implicit def orderingMap = math.Ordering.String.on { x: String => x.toLowerCase } diff --git a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala index 739a1b836d..f11f090b4b 100644 --- a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala @@ -43,10 +43,10 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { def modelFinished: Boolean = _modelFinished private var universe: Universe = null - // protected def closestPackage(sym: Symbol) = { - // if (sym.isPackage || sym.isPackageClass) sym - // else sym.enclosingPackage - // } + protected def closestPackage(sym: Symbol) = { + if (sym.isPackage || sym.isPackageClass) sym + else sym.enclosingPackage + } def makeModel: Option[Universe] = { val universe = new Universe { thisUniverse => @@ -77,7 +77,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { /* ============== IMPLEMENTATION PROVIDING ENTITY TYPES ============== */ abstract class EntityImpl(val sym: Symbol, val inTpl: TemplateImpl) extends Entity { - // val id = { ids += 1; ids } + val id = { ids += 1; ids } val name = optimize(sym.nameString) val universe = thisFactory.universe @@ -91,7 +91,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { def annotations = sym.annotations.map(makeAnnotation) def inPackageObject: Boolean = sym.owner.isModuleClass && sym.owner.sourceModule.isPackageObject def isType = sym.name.isTypeName - // def isTerm = sym.name.isTermName + def isTerm = sym.name.isTermName } trait TemplateImpl extends EntityImpl with TemplateEntity { @@ -103,7 +103,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { def isObject = sym.isModule && !sym.isPackage def isCaseClass = sym.isCaseClass def isRootPackage = false - // def isNoDocMemberTemplate = false + def isNoDocMemberTemplate = false def selfType = if (sym.thisSym eq sym) None else Some(makeType(sym.thisSym.typeOfThis, this)) } @@ -178,9 +178,9 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { }) else None - // def inheritedFrom = - // if (inTemplate.sym == this.sym.owner || inTemplate.sym.isPackage) Nil else - // makeTemplate(this.sym.owner) :: (sym.allOverriddenSymbols map { os => makeTemplate(os.owner) }) + def inheritedFrom = + if (inTemplate.sym == this.sym.owner || inTemplate.sym.isPackage) Nil else + makeTemplate(this.sym.owner) :: (sym.allOverriddenSymbols map { os => makeTemplate(os.owner) }) def resultType = { def resultTpe(tpe: Type): Type = tpe match { // similar to finalResultType, except that it leaves singleton types alone case PolyType(_, res) => resultTpe(res) @@ -195,7 +195,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { def isVal = false def isLazyVal = false def isVar = false - // def isImplicit = sym.isImplicit + def isImplicit = sym.isImplicit def isConstructor = false def isAliasType = false def isAbstractType = false @@ -203,7 +203,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { // for the explanation of conversion == null see comment on flags ((!sym.isTrait && ((sym hasFlag Flags.ABSTRACT) || (sym hasFlag Flags.DEFERRED)) && (!isImplicitlyInherited)) || sym.isAbstractClass || sym.isAbstractType) && !sym.isSynthetic - // def isTemplate = false + def isTemplate = false def signature = externalSignature(sym) lazy val signatureCompat = { @@ -257,9 +257,9 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { */ abstract class MemberTemplateImpl(sym: Symbol, inTpl: DocTemplateImpl) extends MemberImpl(sym, inTpl) with TemplateImpl with HigherKindedImpl with MemberTemplateEntity { // no templates cache for this class, each owner gets its own instance - // override def isTemplate = true + override def isTemplate = true def isDocTemplate = false - // override def isNoDocMemberTemplate = true + override def isNoDocMemberTemplate = true lazy val definitionName = optimize(inDefinitionTemplates.head.qualifiedName + "." + name) def valueParams: List[List[ValueParam]] = Nil /** TODO, these are now only computed for DocTemplates */ @@ -380,9 +380,9 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { lazy val memberSyms = sym.info.members.filter(s => membersShouldDocument(s, this)).toList // the inherited templates (classes, traits or objects) - val memberSymsLazy = memberSyms.filter(t => templateShouldDocument(t, this) && !inOriginalOwner(t, this)) + var memberSymsLazy = memberSyms.filter(t => templateShouldDocument(t, this) && !inOriginalOwner(t, this)) // the direct members (methods, values, vars, types and directly contained templates) - val memberSymsEager = memberSyms.filter(!memberSymsLazy.contains(_)) + var memberSymsEager = memberSyms.filter(!memberSymsLazy.contains(_)) // the members generated by the symbols in memberSymsEager val ownMembers = (memberSymsEager.flatMap(makeMember(_, None, this))) @@ -438,7 +438,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { else List() ) - // override def isTemplate = true + override def isTemplate = true override def isDocTemplate = true private[this] lazy val companionSymbol = if (sym.isAliasType || sym.isAbstractType) { @@ -545,7 +545,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { val qualifiedName = conversion.fold(inDefinitionTemplates.head.qualifiedName)(_.conversionQualifiedName) optimize(qualifiedName + "#" + name) } - // def isBridge = sym.isBridge + def isBridge = sym.isBridge def isUseCase = useCaseOf.isDefined override def byConversion: Option[ImplicitConversionImpl] = conversion override def isImplicitlyInherited = { assert(modelFinished); conversion.isDefined } @@ -707,7 +707,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { override def inTemplate = this override def toRoot = this :: Nil override def qualifiedName = "_root_" - // override def inheritedFrom = Nil + override def inheritedFrom = Nil override def isRootPackage = true override lazy val memberSyms = (bSym.info.members ++ EmptyPackage.info.members).toList filter { s => @@ -857,11 +857,11 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { inTpl.members.find(_.sym == aSym) } - // @deprecated("Use `findLinkTarget` instead.", "2.10.0") - // def findTemplate(query: String): Option[DocTemplateImpl] = { - // assert(modelFinished) - // docTemplatesCache.values find { (tpl: DocTemplateImpl) => tpl.qualifiedName == query && !packageDropped(tpl) && !tpl.isObject } - // } + @deprecated("Use `findLinkTarget` instead.", "2.10.0") + def findTemplate(query: String): Option[DocTemplateImpl] = { + assert(modelFinished) + docTemplatesCache.values find { (tpl: DocTemplateImpl) => tpl.qualifiedName == query && !packageDropped(tpl) && !tpl.isObject } + } def findTemplateMaybe(aSym: Symbol): Option[DocTemplateImpl] = { assert(modelFinished) diff --git a/src/compiler/scala/tools/nsc/doc/model/ModelFactoryImplicitSupport.scala b/src/compiler/scala/tools/nsc/doc/model/ModelFactoryImplicitSupport.scala index e9c32b1af0..c1ca8c1448 100644 --- a/src/compiler/scala/tools/nsc/doc/model/ModelFactoryImplicitSupport.scala +++ b/src/compiler/scala/tools/nsc/doc/model/ModelFactoryImplicitSupport.scala @@ -345,14 +345,14 @@ trait ModelFactoryImplicitSupport { makeRootPackage } - // def targetTemplate: Option[TemplateEntity] = toType match { - // // @Vlad: I'm being extra conservative in template creation -- I don't want to create templates for complex types - // // such as refinement types because the template can't represent the type corectly (a template corresponds to a - // // package, class, trait or object) - // case t: TypeRef => Some(makeTemplate(t.sym)) - // case RefinedType(parents, decls) => None - // case _ => error("Scaladoc implicits: Could not create template for: " + toType + " of type " + toType.getClass); None - // } + def targetTemplate: Option[TemplateEntity] = toType match { + // @Vlad: I'm being extra conservative in template creation -- I don't want to create templates for complex types + // such as refinement types because the template can't represent the type corectly (a template corresponds to a + // package, class, trait or object) + case t: TypeRef => Some(makeTemplate(t.sym)) + case RefinedType(parents, decls) => None + case _ => error("Scaladoc implicits: Could not create template for: " + toType + " of type " + toType.getClass); None + } def targetTypeComponents: List[(TemplateEntity, TypeEntity)] = makeParentTypes(toType, None, inTpl) @@ -492,14 +492,14 @@ trait ModelFactoryImplicitSupport { /** * Make implicits explicit - Not used curently */ - // object implicitToExplicit extends TypeMap { - // def apply(tp: Type): Type = mapOver(tp) match { - // case MethodType(params, resultType) => - // MethodType(params.map(param => if (param.isImplicit) param.cloneSymbol.resetFlag(Flags.IMPLICIT) else param), resultType) - // case other => - // other - // } - // } + object implicitToExplicit extends TypeMap { + def apply(tp: Type): Type = mapOver(tp) match { + case MethodType(params, resultType) => + MethodType(params.map(param => if (param.isImplicit) param.cloneSymbol.resetFlag(Flags.IMPLICIT) else param), resultType) + case other => + other + } + } /** * removeImplicitParameters transforms implicit parameters from the view result type into constraints and diff --git a/src/compiler/scala/tools/nsc/doc/model/comment/Comment.scala b/src/compiler/scala/tools/nsc/doc/model/comment/Comment.scala index 4b75f3fd4d..3e172544dd 100644 --- a/src/compiler/scala/tools/nsc/doc/model/comment/Comment.scala +++ b/src/compiler/scala/tools/nsc/doc/model/comment/Comment.scala @@ -103,7 +103,7 @@ abstract class Comment { def example: List[Body] /** The comment as it appears in the source text. */ - // def source: Option[String] + def source: Option[String] /** A description for the primary constructor */ def constructor: Option[Body] diff --git a/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala b/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala index 7897421bd7..9617b15068 100644 --- a/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala @@ -28,10 +28,10 @@ trait CommentFactory { thisFactory: ModelFactory with CommentFactory with Member protected val commentCache = mutable.HashMap.empty[(global.Symbol, TemplateImpl), Comment] - // def addCommentBody(sym: global.Symbol, inTpl: TemplateImpl, docStr: String, docPos: global.Position): global.Symbol = { - // commentCache += (sym, inTpl) -> parse(docStr, docStr, docPos, None) - // sym - // } + def addCommentBody(sym: global.Symbol, inTpl: TemplateImpl, docStr: String, docPos: global.Position): global.Symbol = { + commentCache += (sym, inTpl) -> parse(docStr, docStr, docPos, None) + sym + } def comment(sym: global.Symbol, currentTpl: Option[DocTemplateImpl], inTpl: DocTemplateImpl): Option[Comment] = { val key = (sym, inTpl) @@ -132,7 +132,7 @@ trait CommentFactory { thisFactory: ModelFactory with CommentFactory with Member val note = note0 val example = example0 val constructor = constructor0 - // val source = source0 + val source = source0 val inheritDiagram = inheritDiagram0 val contentDiagram = contentDiagram0 val groupDesc = groupDesc0 @@ -957,19 +957,19 @@ trait CommentFactory { thisFactory: ModelFactory with CommentFactory with Member count } - // final def jumpUntil(chars: String): Int = { - // assert(chars.length > 0) - // var count = 0 - // val c = chars.charAt(0) - // while (!check(chars) && char != endOfText) { - // nextChar() - // while (char != c && char != endOfText) { - // nextChar() - // count += 1 - // } - // } - // count - // } + final def jumpUntil(chars: String): Int = { + assert(chars.length > 0) + var count = 0 + val c = chars.charAt(0) + while (!check(chars) && char != endOfText) { + nextChar() + while (char != c && char != endOfText) { + nextChar() + count += 1 + } + } + count + } final def jumpUntil(pred: => Boolean): Int = { var count = 0 diff --git a/src/compiler/scala/tools/nsc/doc/model/diagram/Diagram.scala b/src/compiler/scala/tools/nsc/doc/model/diagram/Diagram.scala index cb4659a71c..c2aa1f17f3 100644 --- a/src/compiler/scala/tools/nsc/doc/model/diagram/Diagram.scala +++ b/src/compiler/scala/tools/nsc/doc/model/diagram/Diagram.scala @@ -36,12 +36,12 @@ case class InheritanceDiagram(thisNode: ThisNode, override def isInheritanceDiagram = true lazy val depthInfo = new DepthInfo { def maxDepth = 3 - // def nodeDepth(node: Node) = - // if (node == thisNode) 1 - // else if (superClasses.contains(node)) 0 - // else if (subClasses.contains(node)) 2 - // else if (incomingImplicits.contains(node) || outgoingImplicits.contains(node)) 1 - // else -1 + def nodeDepth(node: Node) = + if (node == thisNode) 1 + else if (superClasses.contains(node)) 0 + else if (subClasses.contains(node)) 2 + else if (incomingImplicits.contains(node) || outgoingImplicits.contains(node)) 1 + else -1 } } @@ -49,7 +49,7 @@ trait DepthInfo { /** Gives the maximum depth */ def maxDepth: Int /** Gives the depth of any node in the diagram or -1 if the node is not in the diagram */ - // def nodeDepth(node: Node): Int + def nodeDepth(node: Node): Int } abstract class Node { @@ -142,5 +142,5 @@ class ContentDiagramDepth(pack: ContentDiagram) extends DepthInfo { } val maxDepth = _maxDepth - // def nodeDepth(node: Node) = _nodeDepth.getOrElse(node, -1) -} + def nodeDepth(node: Node) = _nodeDepth.getOrElse(node, -1) +} \ No newline at end of file diff --git a/src/compiler/scala/tools/nsc/interactive/BuildManager.scala b/src/compiler/scala/tools/nsc/interactive/BuildManager.scala index 921d4dc0e1..a3f76994bc 100644 --- a/src/compiler/scala/tools/nsc/interactive/BuildManager.scala +++ b/src/compiler/scala/tools/nsc/interactive/BuildManager.scala @@ -16,7 +16,7 @@ trait BuildManager { def addSourceFiles(files: Set[AbstractFile]) /** Remove the given files from the managed build process. */ - // def removeFiles(files: Set[AbstractFile]) + def removeFiles(files: Set[AbstractFile]) /** The given files have been modified by the user. Recompile * them and their dependent files. diff --git a/src/compiler/scala/tools/nsc/interactive/Global.scala b/src/compiler/scala/tools/nsc/interactive/Global.scala index f71415450c..4dedbcfd3d 100644 --- a/src/compiler/scala/tools/nsc/interactive/Global.scala +++ b/src/compiler/scala/tools/nsc/interactive/Global.scala @@ -395,40 +395,40 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "") if (typerRun != currentTyperRun) demandNewCompilerRun() } - // def debugInfo(source : SourceFile, start : Int, length : Int): String = { - // println("DEBUG INFO "+source+"/"+start+"/"+length) - // val end = start+length - // val pos = rangePos(source, start, start, end) - - // val tree = locateTree(pos) - // val sw = new StringWriter - // val pw = new PrintWriter(sw) - // newTreePrinter(pw).print(tree) - // pw.flush - - // val typed = new Response[Tree] - // askTypeAt(pos, typed) - // val typ = typed.get.left.toOption match { - // case Some(tree) => - // val sw = new StringWriter - // val pw = new PrintWriter(sw) - // newTreePrinter(pw).print(tree) - // pw.flush - // sw.toString - // case None => "" - // } - - // val completionResponse = new Response[List[Member]] - // askTypeCompletion(pos, completionResponse) - // val completion = completionResponse.get.left.toOption match { - // case Some(members) => - // members mkString "\n" - // case None => "" - // } - - // source.content.view.drop(start).take(length).mkString+" : "+source.path+" ("+start+", "+end+ - // ")\n\nlocateTree:\n"+sw.toString+"\n\naskTypeAt:\n"+typ+"\n\ncompletion:\n"+completion - // } + def debugInfo(source : SourceFile, start : Int, length : Int): String = { + println("DEBUG INFO "+source+"/"+start+"/"+length) + val end = start+length + val pos = rangePos(source, start, start, end) + + val tree = locateTree(pos) + val sw = new StringWriter + val pw = new PrintWriter(sw) + newTreePrinter(pw).print(tree) + pw.flush + + val typed = new Response[Tree] + askTypeAt(pos, typed) + val typ = typed.get.left.toOption match { + case Some(tree) => + val sw = new StringWriter + val pw = new PrintWriter(sw) + newTreePrinter(pw).print(tree) + pw.flush + sw.toString + case None => "" + } + + val completionResponse = new Response[List[Member]] + askTypeCompletion(pos, completionResponse) + val completion = completionResponse.get.left.toOption match { + case Some(members) => + members mkString "\n" + case None => "" + } + + source.content.view.drop(start).take(length).mkString+" : "+source.path+" ("+start+", "+end+ + ")\n\nlocateTree:\n"+sw.toString+"\n\naskTypeAt:\n"+typ+"\n\ncompletion:\n"+completion + } // ----------------- The Background Runner Thread ----------------------- diff --git a/src/compiler/scala/tools/nsc/interpreter/ByteCode.scala b/src/compiler/scala/tools/nsc/interpreter/ByteCode.scala index 42dad4c50d..014661e525 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ByteCode.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ByteCode.scala @@ -40,23 +40,23 @@ object ByteCode { /** Attempts to retrieve case parameter names for given class name. */ - // def caseParamNamesForPath(path: String) = - // for { - // module <- DECODER - // method <- decoderMethod("caseParamNames", classOf[String]) - // names <- method.invoke(module, path).asInstanceOf[Option[List[String]]] - // } - // yield names + def caseParamNamesForPath(path: String) = + for { + module <- DECODER + method <- decoderMethod("caseParamNames", classOf[String]) + names <- method.invoke(module, path).asInstanceOf[Option[List[String]]] + } + yield names def aliasesForPackage(pkg: String) = aliasMap flatMap (_(pkg)) /** Attempts to find type aliases in package objects. */ - // def aliasForType(path: String): Option[String] = { - // val (pkg, name) = (path lastIndexOf '.') match { - // case -1 => return None - // case idx => (path take idx, path drop (idx + 1)) - // } - // aliasesForPackage(pkg) flatMap (_ get name) - // } + def aliasForType(path: String): Option[String] = { + val (pkg, name) = (path lastIndexOf '.') match { + case -1 => return None + case idx => (path take idx, path drop (idx + 1)) + } + aliasesForPackage(pkg) flatMap (_ get name) + } } diff --git a/src/compiler/scala/tools/nsc/interpreter/CodeHandlers.scala b/src/compiler/scala/tools/nsc/interpreter/CodeHandlers.scala index a8eeee48b8..1741a82775 100644 --- a/src/compiler/scala/tools/nsc/interpreter/CodeHandlers.scala +++ b/src/compiler/scala/tools/nsc/interpreter/CodeHandlers.scala @@ -1,50 +1,50 @@ -// /* NSC -- new Scala compiler -// * Copyright 2005-2013 LAMP/EPFL -// * @author Paul Phillips -// */ - -// package scala.tools.nsc -// package interpreter - -// import CodeHandlers.NoSuccess -// import scala.util.control.ControlThrowable - -// /** -// * The start of a simpler interface for utilizing the compiler with piecemeal -// * code strings. The "T" here could potentially be a Tree, a Type, a Symbol, -// * a Boolean, or something even more exotic. -// */ -// trait CodeHandlers[T] { -// self => - -// // Expressions are composed of operators and operands. -// def expr(code: String): T - -// // Statements occur as parts of blocks and templates. -// // A statement can be an import, a definition or an expression, or it can be empty. -// // Statements used in the template of a class definition can also be declarations. -// def stmt(code: String): T -// def stmts(code: String): Seq[T] - -// object opt extends CodeHandlers[Option[T]] { -// val handler: PartialFunction[Throwable, Option[T]] = { -// case _: NoSuccess => None -// } -// val handlerSeq: PartialFunction[Throwable, Seq[Option[T]]] = { -// case _: NoSuccess => Nil -// } - -// def expr(code: String) = try Some(self.expr(code)) catch handler -// def stmt(code: String) = try Some(self.stmt(code)) catch handler -// def stmts(code: String) = try (self.stmts(code) map (x => Some(x))) catch handlerSeq -// } -// } - -// object CodeHandlers { -// def incomplete() = throw CodeIncomplete -// def fail(msg: String) = throw new CodeException(msg) - -// trait NoSuccess extends ControlThrowable -// class CodeException(msg: String) extends RuntimeException(msg) with NoSuccess { } -// object CodeIncomplete extends CodeException("CodeIncomplete") -// } +/* NSC -- new Scala compiler + * Copyright 2005-2013 LAMP/EPFL + * @author Paul Phillips + */ + +package scala.tools.nsc +package interpreter + +import CodeHandlers.NoSuccess +import scala.util.control.ControlThrowable + +/** + * The start of a simpler interface for utilizing the compiler with piecemeal + * code strings. The "T" here could potentially be a Tree, a Type, a Symbol, + * a Boolean, or something even more exotic. + */ +trait CodeHandlers[T] { + self => + + // Expressions are composed of operators and operands. + def expr(code: String): T + + // Statements occur as parts of blocks and templates. + // A statement can be an import, a definition or an expression, or it can be empty. + // Statements used in the template of a class definition can also be declarations. + def stmt(code: String): T + def stmts(code: String): Seq[T] + + object opt extends CodeHandlers[Option[T]] { + val handler: PartialFunction[Throwable, Option[T]] = { + case _: NoSuccess => None + } + val handlerSeq: PartialFunction[Throwable, Seq[Option[T]]] = { + case _: NoSuccess => Nil + } + + def expr(code: String) = try Some(self.expr(code)) catch handler + def stmt(code: String) = try Some(self.stmt(code)) catch handler + def stmts(code: String) = try (self.stmts(code) map (x => Some(x))) catch handlerSeq + } +} + +object CodeHandlers { + def incomplete() = throw CodeIncomplete + def fail(msg: String) = throw new CodeException(msg) + + trait NoSuccess extends ControlThrowable + class CodeException(msg: String) extends RuntimeException(msg) with NoSuccess { } + object CodeIncomplete extends CodeException("CodeIncomplete") +} diff --git a/src/compiler/scala/tools/nsc/interpreter/CommandLine.scala b/src/compiler/scala/tools/nsc/interpreter/CommandLine.scala index 0b4ad1a29d..8042f0aee2 100644 --- a/src/compiler/scala/tools/nsc/interpreter/CommandLine.scala +++ b/src/compiler/scala/tools/nsc/interpreter/CommandLine.scala @@ -10,5 +10,5 @@ package interpreter */ class CommandLine(arguments: List[String], error: String => Unit) extends CompilerCommand(arguments, error) { override def cmdName = "scala" - // override lazy val fileEndings = List(".scalaint") + override lazy val fileEndings = List(".scalaint") } diff --git a/src/compiler/scala/tools/nsc/interpreter/Completion.scala b/src/compiler/scala/tools/nsc/interpreter/Completion.scala index bf53fbb04b..1dfccbfbf7 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Completion.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Completion.scala @@ -23,7 +23,7 @@ object NoCompletion extends Completion { } object Completion { - // def empty: Completion = NoCompletion + def empty: Completion = NoCompletion case class Candidates(cursor: Int, candidates: List[String]) { } val NoCandidates = Candidates(-1, Nil) diff --git a/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala b/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala index 5b8a1791e4..3a0b48ef57 100644 --- a/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala +++ b/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala @@ -52,30 +52,30 @@ trait CompletionAware { } } -// object CompletionAware { -// val Empty = new CompletionAware { def completions(verbosity: Int) = Nil } +object CompletionAware { + val Empty = new CompletionAware { def completions(verbosity: Int) = Nil } -// def unapply(that: Any): Option[CompletionAware] = that match { -// case x: CompletionAware => Some((x)) -// case _ => None -// } + def unapply(that: Any): Option[CompletionAware] = that match { + case x: CompletionAware => Some((x)) + case _ => None + } -// /** Create a CompletionAware object from the given functions. -// * The first should generate the list of completions whenever queried, -// * and the second should return Some(CompletionAware) object if -// * subcompletions are possible. -// */ -// def apply(terms: () => List[String], followFunction: String => Option[CompletionAware]): CompletionAware = -// new CompletionAware { -// def completions = terms() -// def completions(verbosity: Int) = completions -// override def follow(id: String) = followFunction(id) -// } + /** Create a CompletionAware object from the given functions. + * The first should generate the list of completions whenever queried, + * and the second should return Some(CompletionAware) object if + * subcompletions are possible. + */ + def apply(terms: () => List[String], followFunction: String => Option[CompletionAware]): CompletionAware = + new CompletionAware { + def completions = terms() + def completions(verbosity: Int) = completions + override def follow(id: String) = followFunction(id) + } -// /** Convenience factories. -// */ -// def apply(terms: () => List[String]): CompletionAware = apply(terms, _ => None) -// def apply(map: scala.collection.Map[String, CompletionAware]): CompletionAware = -// apply(() => map.keys.toList, map.get _) -// } + /** Convenience factories. + */ + def apply(terms: () => List[String]): CompletionAware = apply(terms, _ => None) + def apply(map: scala.collection.Map[String, CompletionAware]): CompletionAware = + apply(() => map.keys.toList, map.get _) +} diff --git a/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala b/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala index cddd7c930c..13880bb8af 100644 --- a/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala +++ b/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala @@ -38,7 +38,7 @@ trait CompletionOutput { def relativize(str: String): String = quietString(str stripPrefix (pkg + ".")) def relativize(tp: Type): String = relativize(tp.normalize.toString) - // def relativize(sym: Symbol): String = relativize(sym.info) + def relativize(sym: Symbol): String = relativize(sym.info) def braceList(tparams: List[String]) = if (tparams.isEmpty) "" else (tparams map relativize).mkString("[", ", ", "]") def parenList(params: List[Any]) = params.mkString("(", ", ", ")") diff --git a/src/compiler/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala b/src/compiler/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala index 0e3a2328a2..b5850d901c 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala @@ -9,15 +9,15 @@ package interpreter import scala.tools.jline.console.{ ConsoleReader, CursorBuffer } trait ConsoleReaderHelper extends ConsoleReader { - // def currentLine = "" + getCursorBuffer.buffer - // def currentPos = getCursorBuffer.cursor + def currentLine = "" + getCursorBuffer.buffer + def currentPos = getCursorBuffer.cursor def terminal = getTerminal() def width = terminal.getWidth() def height = terminal.getHeight() - // def paginate = isPaginationEnabled() - // def paginate_=(value: Boolean) = setPaginationEnabled(value) + def paginate = isPaginationEnabled() + def paginate_=(value: Boolean) = setPaginationEnabled(value) - // def goBack(num: Int): Unit + def goBack(num: Int): Unit def readOneKey(prompt: String): Int def eraseLine(): Unit diff --git a/src/compiler/scala/tools/nsc/interpreter/Delimited.scala b/src/compiler/scala/tools/nsc/interpreter/Delimited.scala index f09c9a9557..80debfacb9 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Delimited.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Delimited.scala @@ -26,7 +26,7 @@ trait Delimited { def delimited: Char => Boolean def escapeChars: List[Char] = List('\\') - // def quoteChars: List[(Char, Char)] = List(('\'', '\''), ('"', '"')) + def quoteChars: List[(Char, Char)] = List(('\'', '\''), ('"', '"')) /** Break String into args based on delimiting function. */ @@ -39,6 +39,6 @@ trait Delimited { def isDelimiterChar(ch: Char) = delimited(ch) def isEscapeChar(ch: Char): Boolean = escapeChars contains ch - // def isQuoteStart(ch: Char): Boolean = quoteChars map (_._1) contains ch - // def isQuoteEnd(ch: Char): Boolean = quoteChars map (_._2) contains ch + def isQuoteStart(ch: Char): Boolean = quoteChars map (_._1) contains ch + def isQuoteEnd(ch: Char): Boolean = quoteChars map (_._2) contains ch } diff --git a/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala b/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala index fbd0d15962..ebd0030802 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala @@ -17,8 +17,7 @@ trait ExprTyper { import syntaxAnalyzer.UnitParser import naming.freshInternalVarName - object codeParser { - val global: repl.global.type = repl.global + object codeParser extends { val global: repl.global.type = repl.global } with CodeHandlers[Tree] { def applyRule[T](code: String, rule: UnitParser => T): T = { reporter.reset() val scanner = newUnitParser(code) @@ -30,10 +29,10 @@ trait ExprTyper { result } - // def defns(code: String) = stmts(code) collect { case x: DefTree => x } - // def expr(code: String) = applyRule(code, _.expr()) + def defns(code: String) = stmts(code) collect { case x: DefTree => x } + def expr(code: String) = applyRule(code, _.expr()) def stmts(code: String) = applyRule(code, _.templateStats()) - // def stmt(code: String) = stmts(code).last // guaranteed nonempty + def stmt(code: String) = stmts(code).last // guaranteed nonempty } /** Parse a line into a sequence of trees. Returns None if the input is incomplete. */ diff --git a/src/compiler/scala/tools/nsc/interpreter/ILoop.scala b/src/compiler/scala/tools/nsc/interpreter/ILoop.scala index 0e3dc3147b..74549ef558 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ILoop.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ILoop.scala @@ -14,7 +14,7 @@ import scala.util.Properties.{ jdkHome, javaVersion, versionString, javaVmName } import scala.tools.util.{ Javap } import util.{ ClassPath, Exceptional, stringFromWriter, stringFromStream } import io.{ File, Directory } -// import scala.reflect.NameTransformer._ +import scala.reflect.NameTransformer._ import util.ScalaClassLoader import ScalaClassLoader._ import scala.tools.util._ @@ -71,12 +71,12 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) intp.reporter printUntruncatedMessage msg } - // def isAsync = !settings.Yreplsync.value + def isAsync = !settings.Yreplsync.value lazy val power = new Power(intp, new StdReplVals(this))(tagOfStdReplVals, classTag[StdReplVals]) def history = in.history /** The context class loader at the time this object was created */ - // protected val originalClassLoader = Thread.currentThread.getContextClassLoader + protected val originalClassLoader = Thread.currentThread.getContextClassLoader // classpath entries added via :cp var addedClasspath: String = "" @@ -131,19 +131,20 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) def helpCommand(line: String): Result = { if (line == "") helpSummary() else uniqueCommand(line) match { - case Some(lc) => echo("\n" + lc.help) + case Some(lc) => echo("\n" + lc.longHelp) case _ => ambiguousError(line) } } private def helpSummary() = { val usageWidth = commands map (_.usageMsg.length) max - val formatStr = "%-" + usageWidth + "s %s" + val formatStr = "%-" + usageWidth + "s %s %s" echo("All commands can be abbreviated, e.g. :he instead of :help.") - // echo("Those marked with a * have more detailed help, e.g. :help imports.\n") + echo("Those marked with a * have more detailed help, e.g. :help imports.\n") commands foreach { cmd => - echo(formatStr.format(cmd.usageMsg, cmd.help)) + val star = if (cmd.hasLongHelp) "*" else " " + echo(formatStr.format(cmd.usageMsg, star, cmd.help)) } } private def ambiguousError(cmd: String): Result = { @@ -193,10 +194,10 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) out println msg out.flush() } - // protected def echoNoNL(msg: String) = { - // out print msg - // out.flush() - // } + protected def echoNoNL(msg: String) = { + out print msg + out.flush() + } /** Search the history */ def searchHistory(_cmdline: String) { @@ -207,8 +208,8 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) echo("%d %s".format(index + offset, line)) } - private val currentPrompt = Properties.shellPromptString - // def setPrompt(prompt: String) = currentPrompt = prompt + private var currentPrompt = Properties.shellPromptString + def setPrompt(prompt: String) = currentPrompt = prompt /** Prompt to print when awaiting input */ def prompt = currentPrompt @@ -683,7 +684,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) def process(settings: Settings): Boolean = savingContextLoader { this.settings = settings createInterpreter() - // var thunks: List[() => Unit] = Nil + var thunks: List[() => Unit] = Nil // sets in to some kind of reader depending on environmental cues in = in0.fold(chooseReader(settings))(r => SimpleReader(r, out, true)) @@ -703,21 +704,21 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) } /** process command-line arguments and do as they request */ - // def process(args: Array[String]): Boolean = { - // val command = new CommandLine(args.toList, echo) - // def neededHelp(): String = - // (if (command.settings.help.value) command.usageMsg + "\n" else "") + - // (if (command.settings.Xhelp.value) command.xusageMsg + "\n" else "") - - // // if they asked for no help and command is valid, we call the real main - // neededHelp() match { - // case "" => command.ok && process(command.settings) - // case help => echoNoNL(help) ; true - // } - // } + def process(args: Array[String]): Boolean = { + val command = new CommandLine(args.toList, echo) + def neededHelp(): String = + (if (command.settings.help.value) command.usageMsg + "\n" else "") + + (if (command.settings.Xhelp.value) command.xusageMsg + "\n" else "") + + // if they asked for no help and command is valid, we call the real main + neededHelp() match { + case "" => command.ok && process(command.settings) + case help => echoNoNL(help) ; true + } + } @deprecated("Use `process` instead", "2.9.0") - def main(settings: Settings): Unit = process(settings) //used by sbt + def main(settings: Settings): Unit = process(settings) } object ILoop { diff --git a/src/compiler/scala/tools/nsc/interpreter/IMain.scala b/src/compiler/scala/tools/nsc/interpreter/IMain.scala index 8ba6573e64..0ef27ac96a 100644 --- a/src/compiler/scala/tools/nsc/interpreter/IMain.scala +++ b/src/compiler/scala/tools/nsc/interpreter/IMain.scala @@ -63,7 +63,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends @deprecated("Use replOutput.dir instead", "2.11.0") def virtualDirectory = replOutput.dir - // Used in a test case. def showDirectory() = replOutput.show(out) private[nsc] var printResults = true // whether to print result lines @@ -83,20 +82,20 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends private var _classLoader: AbstractFileClassLoader = null // active classloader private val _compiler: Global = newCompiler(settings, reporter) // our private compiler - // private val nextReqId = { - // var counter = 0 - // () => { counter += 1 ; counter } - // } + private val nextReqId = { + var counter = 0 + () => { counter += 1 ; counter } + } def compilerClasspath: Seq[URL] = ( if (isInitializeComplete) global.classPath.asURLs else new PathResolver(settings).result.asURLs // the compiler's classpath ) def settings = initialSettings - // def mostRecentLine = prevRequestList match { - // case Nil => "" - // case req :: _ => req.originalLine - // } + def mostRecentLine = prevRequestList match { + case Nil => "" + case req :: _ => req.originalLine + } // Run the code body with the given boolean settings flipped to true. def withoutWarnings[T](body: => T): T = beQuietDuring { val saved = settings.nowarn.value @@ -111,12 +110,12 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends def this(settings: Settings) = this(settings, new NewLinePrintWriter(new ConsoleWriter, true)) def this() = this(new Settings()) - // lazy val repllog: Logger = new Logger { - // val out: JPrintWriter = imain.out - // val isInfo: Boolean = BooleanProp keyExists "scala.repl.info" - // val isDebug: Boolean = BooleanProp keyExists "scala.repl.debug" - // val isTrace: Boolean = BooleanProp keyExists "scala.repl.trace" - // } + lazy val repllog: Logger = new Logger { + val out: JPrintWriter = imain.out + val isInfo: Boolean = BooleanProp keyExists "scala.repl.info" + val isDebug: Boolean = BooleanProp keyExists "scala.repl.debug" + val isTrace: Boolean = BooleanProp keyExists "scala.repl.trace" + } lazy val formatting: Formatting = new Formatting { val prompt = Properties.shellPromptString } @@ -176,7 +175,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends } import global._ - import definitions.{ ObjectClass, termMember, dropNullaryMethod} + import definitions.{ ObjectClass, termMember, typeMember, dropNullaryMethod} lazy val runtimeMirror = ru.runtimeMirror(classLoader) @@ -190,13 +189,13 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends noFatal(runtimeMirror staticModule path) orElse noFatal(rootMirror staticModule path) ) - // def getPathIfDefined(path: String) = ( - // if (path endsWith "$") getModuleIfDefined(path.init) - // else getClassIfDefined(path) - // ) + def getPathIfDefined(path: String) = ( + if (path endsWith "$") getModuleIfDefined(path.init) + else getClassIfDefined(path) + ) implicit class ReplTypeOps(tp: Type) { - // def orElse(other: => Type): Type = if (tp ne NoType) tp else other + def orElse(other: => Type): Type = if (tp ne NoType) tp else other def andAlso(fn: Type => Type): Type = if (tp eq NoType) tp else fn(tp) } @@ -212,7 +211,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends if (replScope containsName name) freshUserTermName() else name } - // def isUserTermName(name: Name) = isUserVarName("" + name) + def isUserTermName(name: Name) = isUserVarName("" + name) def isInternalTermName(name: Name) = isInternalVarName("" + name) } import naming._ @@ -311,11 +310,11 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends abstract class PhaseDependentOps { def shift[T](op: => T): T - // def lookup(name: Name): Symbol = shift(replScope lookup name) + def lookup(name: Name): Symbol = shift(replScope lookup name) def path(name: => Name): String = shift(path(symbolOfName(name))) def path(sym: Symbol): String = backticked(shift(sym.fullName)) - // def name(sym: Symbol): Name = shift(sym.name) - // def info(sym: Symbol): Type = shift(sym.info) + def name(sym: Symbol): Name = shift(sym.name) + def info(sym: Symbol): Type = shift(sym.info) def sig(sym: Symbol): String = shift(sym.defString) } object typerOp extends PhaseDependentOps { @@ -355,7 +354,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends case p => new URLClassLoader(compilerClasspath, p) }) - // def getInterpreterClassLoader() = classLoader + def getInterpreterClassLoader() = classLoader // Set the current Java "context" class loader to this interpreter's class loader def setContextClassLoader() = classLoader.setAsContext() @@ -406,7 +405,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends exitingTyper { req.defines filterNot (s => req.defines contains s.companionSymbol) foreach { newSym => val companion = newSym.name.companionName - // val found = replScope lookup companion + val found = replScope lookup companion replScope lookup companion andAlso { oldSym => replwarn(s"warning: previously defined $oldSym is not a companion to $newSym.") replwarn("Companions must be defined together; you may wish to use :paste mode for this.") @@ -424,18 +423,18 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends printMessage(msg) } - // def isParseable(line: String): Boolean = { - // beSilentDuring { - // try parse(line) match { - // case Some(xs) => xs.nonEmpty // parses as-is - // case None => true // incomplete - // } - // catch { case x: Exception => // crashed the compiler - // replwarn("Exception in isParseable(\"" + line + "\"): " + x) - // false - // } - // } - // } + def isParseable(line: String): Boolean = { + beSilentDuring { + try parse(line) match { + case Some(xs) => xs.nonEmpty // parses as-is + case None => true // incomplete + } + catch { case x: Exception => // crashed the compiler + replwarn("Exception in isParseable(\"" + line + "\"): " + x) + false + } + } + } def compileSourcesKeepingRun(sources: SourceFile*) = { val run = new Run() @@ -654,17 +653,17 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends quietRun("val %s = %s".format(tempName, name)) quietRun("val %s = %s.asInstanceOf[%s]".format(name, tempName, newType)) } - // def quietImport(ids: String*): IR.Result = beQuietDuring(addImports(ids: _*)) - // def addImports(ids: String*): IR.Result = - // if (ids.isEmpty) IR.Success - // else interpret("import " + ids.mkString(", ")) + def quietImport(ids: String*): IR.Result = beQuietDuring(addImports(ids: _*)) + def addImports(ids: String*): IR.Result = + if (ids.isEmpty) IR.Success + else interpret("import " + ids.mkString(", ")) def quietBind(p: NamedParam): IR.Result = beQuietDuring(bind(p)) def bind(p: NamedParam): IR.Result = bind(p.name, p.tpe, p.value) def bind[T: ru.TypeTag : ClassTag](name: String, value: T): IR.Result = bind((name, value)) - // def bindSyntheticValue(x: Any): IR.Result = bindValue(freshInternalVarName(), x) - // def bindValue(x: Any): IR.Result = bindValue(freshUserVarName(), x) - // def bindValue(name: String, x: Any): IR.Result = bind(name, TypeStrings.fromValue(x), x) + def bindSyntheticValue(x: Any): IR.Result = bindValue(freshInternalVarName(), x) + def bindValue(x: Any): IR.Result = bindValue(freshUserVarName(), x) + def bindValue(name: String, x: Any): IR.Result = bind(name, TypeStrings.fromValue(x), x) /** Reset this interpreter, forgetting all user-specified requests. */ def reset() { @@ -720,7 +719,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends def readPath = pathTo(readName) def evalPath = pathTo(evalName) - // def printPath = pathTo(printName) + def printPath = pathTo(printName) def call(name: String, args: Any*): AnyRef = { val m = evalMethod(name) @@ -735,9 +734,9 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends try Right(call(name, args: _*)) catch { case ex: Throwable => Left(ex) } - // def callOpt(name: String, args: Any*): Option[AnyRef] = - // try Some(call(name, args: _*)) - // catch { case ex: Throwable => bindError(ex) ; None } + def callOpt(name: String, args: Any*): Option[AnyRef] = + try Some(call(name, args: _*)) + catch { case ex: Throwable => bindError(ex) ; None } class EvalException(msg: String, cause: Throwable) extends RuntimeException(msg, cause) { } @@ -750,7 +749,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends } lazy val evalClass = load(evalPath) - // lazy val evalValue = callOpt(resultName) + lazy val evalValue = callOpt(resultName) def compile(source: String): Boolean = compileAndSaveRun("", source) @@ -803,10 +802,10 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends class Request(val line: String, val trees: List[Tree]) { def defines = defHandlers flatMap (_.definedSymbols) def imports = importedSymbols - // def references = referencedNames map symbolOfName + def references = referencedNames map symbolOfName def value = Some(handlers.last) filter (h => h.definesValue) map (h => definedSymbols(h.definesTerm.get)) getOrElse NoSymbol - // val reqId = nextReqId() + val reqId = nextReqId() val lineRep = new ReadEvalPrint() private var _originalLine: String = null @@ -818,7 +817,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends def defHandlers = handlers collect { case x: MemberDefHandler => x } /** all (public) names defined by these statements */ - // val definedNames = handlers flatMap (_.definedNames) + val definedNames = handlers flatMap (_.definedNames) /** list of names used by this expression */ val referencedNames: List[Name] = handlers flatMap (_.referencedNames) @@ -838,7 +837,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends exitingTyper(importsCode(referencedNames.toSet)) /** The unmangled symbol name, but supplemented with line info. */ - // def disambiguated(name: Name): String = name + " (in " + lineRep + ")" + def disambiguated(name: Name): String = name + " (in " + lineRep + ")" /** the line of code to compute */ def toCompute = line @@ -932,7 +931,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends /* typeOf lookup with encoding */ def lookupTypeOf(name: Name) = typeOf.getOrElse(name, typeOf(global.encode(name.toString))) - // def simpleNameOfType(name: TypeName) = (compilerTypeOf get name) map (_.typeSymbolDirect.simpleName) + def simpleNameOfType(name: TypeName) = (compilerTypeOf get name) map (_.typeSymbolDirect.simpleName) private def typeMap[T](f: Type => T) = mapFrom[Name, Name, T](termNames ++ typeNames)(x => f(cleanMemberDecl(resultSymbol, x))) @@ -1012,8 +1011,8 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends */ def tryTwice(op: => Symbol): Symbol = exitingTyper(op) orElse exitingFlatten(op) - // def signatureOf(sym: Symbol) = typerOp sig sym - // def symbolOfPath(path: String): Symbol = exitingTyper(getPathIfDefined(path)) + def signatureOf(sym: Symbol) = typerOp sig sym + def symbolOfPath(path: String): Symbol = exitingTyper(getPathIfDefined(path)) def symbolOfIdent(id: String): Symbol = symbolOfTerm(id) orElse symbolOfType(id) def symbolOfType(id: String): Symbol = tryTwice(replScope lookup (id: TypeName)) def symbolOfTerm(id: String): Symbol = tryTwice(replScope lookup (id: TermName)) @@ -1068,7 +1067,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends def definedTerms = onlyTerms(allDefinedNames) filterNot isInternalTermName def definedTypes = onlyTypes(allDefinedNames) - // def definedSymbols = prevRequestList flatMap (_.defines) toSet + def definedSymbols = prevRequestList flatMap (_.defines) toSet def definedSymbolList = prevRequestList flatMap (_.defines) filterNot (s => isInternalTermName(s.name)) // Terms with user-given names (i.e. not res0 and not synthetic) @@ -1076,67 +1075,67 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends /** Translate a repl-defined identifier into a Symbol. */ - // def apply(name: String): Symbol = types(name) orElse terms(name) - // def types(name: String): Symbol = replScope lookup (name: TypeName) orElse getClassIfDefined(name) - // def terms(name: String): Symbol = replScope lookup (name: TermName) orElse getModuleIfDefined(name) - - // def types[T: global.TypeTag] : Symbol = typeOf[T].typeSymbol - // def terms[T: global.TypeTag] : Symbol = typeOf[T].termSymbol - // def apply[T: global.TypeTag] : Symbol = typeOf[T].typeSymbol - - // lazy val DummyInfoSymbol = NoSymbol.newValue("replScopeDummy") - // private lazy val DummyInfo = TypeRef(NoPrefix, DummyInfoSymbol, Nil) - // private def enterDummySymbol(name: Name) = name match { - // case x: TermName => replScope enter (NoSymbol.newValue(x) setInfo DummyInfo) - // case x: TypeName => replScope enter (NoSymbol.newClass(x) setInfo DummyInfo) - // } + def apply(name: String): Symbol = types(name) orElse terms(name) + def types(name: String): Symbol = replScope lookup (name: TypeName) orElse getClassIfDefined(name) + def terms(name: String): Symbol = replScope lookup (name: TermName) orElse getModuleIfDefined(name) + + def types[T: global.TypeTag] : Symbol = typeOf[T].typeSymbol + def terms[T: global.TypeTag] : Symbol = typeOf[T].termSymbol + def apply[T: global.TypeTag] : Symbol = typeOf[T].typeSymbol + + lazy val DummyInfoSymbol = NoSymbol.newValue("replScopeDummy") + private lazy val DummyInfo = TypeRef(NoPrefix, DummyInfoSymbol, Nil) + private def enterDummySymbol(name: Name) = name match { + case x: TermName => replScope enter (NoSymbol.newValue(x) setInfo DummyInfo) + case x: TypeName => replScope enter (NoSymbol.newClass(x) setInfo DummyInfo) + } private var _replScope: Scope = _ private def resetReplScope() { _replScope = newScope } - // def initReplScope() { - // languageWildcardSyms foreach { clazz => - // importableMembers(clazz) foreach { sym => - // updateReplScope(sym, isDefined = false) - // } - // } - // } + def initReplScope() { + languageWildcardSyms foreach { clazz => + importableMembers(clazz) foreach { sym => + updateReplScope(sym, isDefined = false) + } + } + } def replScope = { if (_replScope eq null) _replScope = newScope _replScope } - // def lookupAll(name: String) = (replScope.lookupAll(name: TermName) ++ replScope.lookupAll(name: TypeName)).toList - // def unlinkAll(name: String) = { - // val syms = lookupAll(name) - // syms foreach { sym => - // replScope unlink sym - // } - // enterDummySymbol(name: TermName) - // enterDummySymbol(name: TypeName) - // syms - // } - // def isUnlinked(name: Name) = { - // symbolOfName(name) match { - // case NoSymbol => false - // case sym => sym.info.typeSymbolDirect == DummyInfoSymbol - // } - // } + def lookupAll(name: String) = (replScope.lookupAll(name: TermName) ++ replScope.lookupAll(name: TypeName)).toList + def unlinkAll(name: String) = { + val syms = lookupAll(name) + syms foreach { sym => + replScope unlink sym + } + enterDummySymbol(name: TermName) + enterDummySymbol(name: TypeName) + syms + } + def isUnlinked(name: Name) = { + symbolOfName(name) match { + case NoSymbol => false + case sym => sym.info.typeSymbolDirect == DummyInfoSymbol + } + } private var executingRequest: Request = _ private val prevRequests = mutable.ListBuffer[Request]() private val directlyBoundNames = mutable.Set[Name]() def allHandlers = prevRequestList flatMap (_.handlers) - // def allDefHandlers = allHandlers collect { case x: MemberDefHandler => x } - // def allDefSymbols = allDefHandlers map (_.symbol) filter (_ ne NoSymbol) + def allDefHandlers = allHandlers collect { case x: MemberDefHandler => x } + def allDefSymbols = allDefHandlers map (_.symbol) filter (_ ne NoSymbol) def lastRequest = if (prevRequests.isEmpty) null else prevRequests.last def prevRequestList = prevRequests.toList - // def allSeenTypes = prevRequestList flatMap (_.typeOf.values.toList) distinct - // def allImplicits = allHandlers filter (_.definesImplicit) flatMap (_.definedNames) + def allSeenTypes = prevRequestList flatMap (_.typeOf.values.toList) distinct + def allImplicits = allHandlers filter (_.definesImplicit) flatMap (_.definedNames) def importHandlers = allHandlers collect { case x: ImportHandler => x } def withoutUnwrapping(op: => Unit): Unit = { diff --git a/src/compiler/scala/tools/nsc/interpreter/ISettings.scala b/src/compiler/scala/tools/nsc/interpreter/ISettings.scala index d45146383b..302ba7a8ac 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ISettings.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ISettings.scala @@ -12,12 +12,12 @@ package interpreter * @author Lex Spoon, 2007/3/24 **/ class ISettings(intp: IMain) { - // /** A list of paths where :load should look */ - // var loadPath = List(".") + /** A list of paths where :load should look */ + var loadPath = List(".") - // /** Set this to true to see repl machinery under -Yrich-exceptions. - // */ - // var showInternalStackTraces = false + /** Set this to true to see repl machinery under -Yrich-exceptions. + */ + var showInternalStackTraces = false /** The maximum length of toString to use when printing the result * of an evaluation. 0 means no maximum. If a printout requires diff --git a/src/compiler/scala/tools/nsc/interpreter/Imports.scala b/src/compiler/scala/tools/nsc/interpreter/Imports.scala index 978e220fab..c5048ebfd8 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Imports.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Imports.scala @@ -15,8 +15,8 @@ trait Imports { import definitions.{ ObjectClass, ScalaPackage, JavaLangPackage, PredefModule } import memberHandlers._ - // def isNoImports = settings.noimports.value - // def isNoPredef = settings.nopredef.value + def isNoImports = settings.noimports.value + def isNoPredef = settings.nopredef.value /** Synthetic import handlers for the language defined imports. */ private def makeWildcardImportHandler(sym: Symbol): ImportHandler = { @@ -31,12 +31,12 @@ trait Imports { /** Symbols whose contents are language-defined to be imported. */ def languageWildcardSyms: List[Symbol] = List(JavaLangPackage, ScalaPackage, PredefModule) - // def languageWildcards: List[Type] = languageWildcardSyms map (_.tpe) + def languageWildcards: List[Type] = languageWildcardSyms map (_.tpe) def languageWildcardHandlers = languageWildcardSyms map makeWildcardImportHandler def allImportedNames = importHandlers flatMap (_.importedNames) - // def importedTerms = onlyTerms(allImportedNames) - // def importedTypes = onlyTypes(allImportedNames) + def importedTerms = onlyTerms(allImportedNames) + def importedTypes = onlyTypes(allImportedNames) /** Types which have been wildcard imported, such as: * val x = "abc" ; import x._ // type java.lang.String @@ -52,17 +52,17 @@ trait Imports { def sessionWildcards: List[Type] = { importHandlers filter (_.importsWildcard) map (_.targetType) distinct } - // def wildcardTypes = languageWildcards ++ sessionWildcards + def wildcardTypes = languageWildcards ++ sessionWildcards def languageSymbols = languageWildcardSyms flatMap membersAtPickler def sessionImportedSymbols = importHandlers flatMap (_.importedSymbols) def importedSymbols = languageSymbols ++ sessionImportedSymbols def importedTermSymbols = importedSymbols collect { case x: TermSymbol => x } - // def importedTypeSymbols = importedSymbols collect { case x: TypeSymbol => x } - // def implicitSymbols = importedSymbols filter (_.isImplicit) + def importedTypeSymbols = importedSymbols collect { case x: TypeSymbol => x } + def implicitSymbols = importedSymbols filter (_.isImplicit) - // def importedTermNamed(name: String): Symbol = - // importedTermSymbols find (_.name.toString == name) getOrElse NoSymbol + def importedTermNamed(name: String): Symbol = + importedTermSymbols find (_.name.toString == name) getOrElse NoSymbol /** Tuples of (source, imported symbols) in the order they were imported. */ @@ -105,7 +105,7 @@ trait Imports { */ case class ComputedImports(prepend: String, append: String, access: String) protected def importsCode(wanted0: Set[Name]): ComputedImports = { - val wanted = wanted0 // filterNot isUnlinked + val wanted = wanted0 filterNot isUnlinked /** Narrow down the list of requests from which imports * should be taken. Removes requests which cannot contribute diff --git a/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala b/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala index a5f491fe6f..6513381d77 100644 --- a/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala +++ b/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala @@ -15,22 +15,22 @@ import Properties.isMac trait InteractiveReader { val interactive: Boolean - // def init(): Unit + def init(): Unit def reset(): Unit def history: History def completion: Completion - // def eraseLine(): Unit + def eraseLine(): Unit def redrawLine(): Unit - // def currentLine: String + def currentLine: String def readYesOrNo(prompt: String, alt: => Boolean): Boolean = readOneKey(prompt) match { case 'y' => true case 'n' => false case _ => alt } - // def readAssumingNo(prompt: String) = readYesOrNo(prompt, false) - // def readAssumingYes(prompt: String) = readYesOrNo(prompt, true) + def readAssumingNo(prompt: String) = readYesOrNo(prompt, false) + def readAssumingYes(prompt: String) = readYesOrNo(prompt, true) protected def readOneLine(prompt: String): String protected def readOneKey(prompt: String): Int @@ -50,6 +50,6 @@ object InteractiveReader { def apply(): InteractiveReader = SimpleReader() @deprecated("Use `apply` instead.", "2.9.0") - def createDefault(): InteractiveReader = apply() // used by sbt + def createDefault(): InteractiveReader = apply() } diff --git a/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala index 5325c18710..5ee5e5526d 100644 --- a/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala +++ b/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala @@ -28,9 +28,9 @@ class JLineCompletion(val intp: IMain) extends Completion with CompletionOutput if (isModule) getModuleIfDefined(name) else getModuleIfDefined(name) ) - // def getType(name: String, isModule: Boolean) = getSymbol(name, isModule).tpe - // def typeOf(name: String) = getType(name, false) - // def moduleOf(name: String) = getType(name, true) + def getType(name: String, isModule: Boolean) = getSymbol(name, isModule).tpe + def typeOf(name: String) = getType(name, false) + def moduleOf(name: String) = getType(name, true) trait CompilerCompletion { def tp: Type @@ -47,7 +47,7 @@ class JLineCompletion(val intp: IMain) extends Completion with CompletionOutput def tos(sym: Symbol): String = sym.decodedName def memberNamed(s: String) = exitingTyper(effectiveTp member newTermName(s)) - // def hasMethod(s: String) = memberNamed(s).isMethod + def hasMethod(s: String) = memberNamed(s).isMethod // XXX we'd like to say "filterNot (_.isDeprecated)" but this causes the // compiler to crash for reasons not yet known. @@ -280,8 +280,8 @@ class JLineCompletion(val intp: IMain) extends Completion with CompletionOutput } // generic interface for querying (e.g. interpreter loop, testing) - // def completions(buf: String): List[String] = - // topLevelFor(Parsed.dotted(buf + ".", buf.length + 1)) + def completions(buf: String): List[String] = + topLevelFor(Parsed.dotted(buf + ".", buf.length + 1)) def completer(): ScalaCompleter = new JLineTabCompletion diff --git a/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala b/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala index 7f8beba32b..e033bab03b 100644 --- a/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala +++ b/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala @@ -23,7 +23,7 @@ class JLineReader(_completion: => Completion) extends InteractiveReader { private def term = consoleReader.getTerminal() def reset() = term.reset() - // def init() = term.init() + def init() = term.init() def scalaToJline(tc: ScalaCompleter): Completer = new Completer { def complete(_buf: String, cursor: Int, candidates: JList[CharSequence]): Int = { @@ -36,7 +36,7 @@ class JLineReader(_completion: => Completion) extends InteractiveReader { class JLineConsoleReader extends ConsoleReader with ConsoleReaderHelper { // working around protected/trait/java insufficiencies. - // def goBack(num: Int): Unit = back(num) + def goBack(num: Int): Unit = back(num) def readOneKey(prompt: String) = { this.print(prompt) this.flush() @@ -63,9 +63,9 @@ class JLineReader(_completion: => Completion) extends InteractiveReader { } } - // def currentLine = consoleReader.getCursorBuffer.buffer.toString + def currentLine = consoleReader.getCursorBuffer.buffer.toString def redrawLine() = consoleReader.redrawLineAndFlush() - // def eraseLine() = consoleReader.eraseLine() + def eraseLine() = consoleReader.eraseLine() // Alternate implementation, not sure if/when I need this. // def eraseLine() = while (consoleReader.delete()) { } def readOneLine(prompt: String) = consoleReader readLine prompt diff --git a/src/compiler/scala/tools/nsc/interpreter/Logger.scala b/src/compiler/scala/tools/nsc/interpreter/Logger.scala index df3e90f0e2..aeb25fc688 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Logger.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Logger.scala @@ -12,7 +12,7 @@ trait Logger { def isTrace: Boolean def out: JPrintWriter - // def info(msg: => Any): Unit = if (isInfo) out println msg - // def debug(msg: => Any): Unit = if (isDebug) out println msg - // def trace(msg: => Any): Unit = if (isTrace) out println msg + def info(msg: => Any): Unit = if (isInfo) out println msg + def debug(msg: => Any): Unit = if (isDebug) out println msg + def trace(msg: => Any): Unit = if (isTrace) out println msg } diff --git a/src/compiler/scala/tools/nsc/interpreter/LoopCommands.scala b/src/compiler/scala/tools/nsc/interpreter/LoopCommands.scala index 168e611077..60325ece30 100644 --- a/src/compiler/scala/tools/nsc/interpreter/LoopCommands.scala +++ b/src/compiler/scala/tools/nsc/interpreter/LoopCommands.scala @@ -19,13 +19,13 @@ class ProcessResult(val line: String) { val exitCode = builder ! logger def lines = buffer.toList - // def show() = lines foreach println + def show() = lines foreach println override def toString = "`%s` (%d lines, exit %d)".format(line, buffer.size, exitCode) } -// object ProcessResult { -// implicit def processResultToOutputLines(pr: ProcessResult): List[String] = pr.lines -// def apply(line: String): ProcessResult = new ProcessResult(line) -// } +object ProcessResult { + implicit def processResultToOutputLines(pr: ProcessResult): List[String] = pr.lines + def apply(line: String): ProcessResult = new ProcessResult(line) +} trait LoopCommands { protected def out: JPrintWriter @@ -35,14 +35,14 @@ trait LoopCommands { // a single interpreter command abstract class LoopCommand(val name: String, val help: String) extends (String => Result) { - // private var _longHelp: String = null - // final def defaultHelp = usageMsg + " (no extended help available.)" - // def hasLongHelp = _longHelp != null || longHelp != defaultHelp - // def withLongHelp(text: String): this.type = { _longHelp = text ; this } - // def longHelp = _longHelp match { - // case null => defaultHelp - // case text => text - // } + private var _longHelp: String = null + final def defaultHelp = usageMsg + " (no extended help available.)" + def hasLongHelp = _longHelp != null || longHelp != defaultHelp + def withLongHelp(text: String): this.type = { _longHelp = text ; this } + def longHelp = _longHelp match { + case null => defaultHelp + case text => text + } def usage: String = "" def usageMsg: String = ":" + name + ( if (usage == "") "" else " " + usage @@ -55,10 +55,10 @@ trait LoopCommands { Result(true, None) } - // def onError(msg: String) = { - // out.println("error: " + msg) - // showUsage() - // } + def onError(msg: String) = { + out.println("error: " + msg) + showUsage() + } } object LoopCommand { def nullary(name: String, help: String, f: () => Result): LoopCommand = @@ -68,8 +68,8 @@ trait LoopCommands { if (usage == "") new NullaryCmd(name, help, f) else new LineCmd(name, usage, help, f) - // def varargs(name: String, usage: String, help: String, f: List[String] => Result): LoopCommand = - // new VarArgsCmd(name, usage, help, f) + def varargs(name: String, usage: String, help: String, f: List[String] => Result): LoopCommand = + new VarArgsCmd(name, usage, help, f) } class NullaryCmd(name: String, help: String, f: String => Result) extends LoopCommand(name, help) { diff --git a/src/compiler/scala/tools/nsc/interpreter/MemberHandlers.scala b/src/compiler/scala/tools/nsc/interpreter/MemberHandlers.scala index 6e564f4d17..95482f1e46 100644 --- a/src/compiler/scala/tools/nsc/interpreter/MemberHandlers.scala +++ b/src/compiler/scala/tools/nsc/interpreter/MemberHandlers.scala @@ -81,7 +81,7 @@ trait MemberHandlers { def symbol = if (member.symbol eq null) NoSymbol else member.symbol def definesImplicit = false def definesValue = false - // def isLegalTopLevel = false + def isLegalTopLevel = false def definesTerm = Option.empty[TermName] def definesType = Option.empty[TypeName] @@ -152,7 +152,7 @@ trait MemberHandlers { class ModuleHandler(module: ModuleDef) extends MemberDefHandler(module) { override def definesTerm = Some(name) override def definesValue = true - // override def isLegalTopLevel = true + override def isLegalTopLevel = true override def resultExtractionCode(req: Request) = codegenln("defined module ", name) } @@ -161,7 +161,7 @@ trait MemberHandlers { override def definedSymbols = List(symbol, symbol.companionSymbol) filterNot (_ == NoSymbol) override def definesType = Some(name.toTypeName) override def definesTerm = Some(name.toTermName) filter (_ => mods.isCase) - // override def isLegalTopLevel = true + override def isLegalTopLevel = true override def resultExtractionCode(req: Request) = codegenln("defined %s %s".format(keyword, name)) @@ -182,19 +182,19 @@ trait MemberHandlers { case sym => sym.thisType } private def importableTargetMembers = importableMembers(targetType).toList - // override def isLegalTopLevel = true - - // def createImportForName(name: Name): String = { - // selectors foreach { - // case sel @ ImportSelector(old, _, `name`, _) => return "import %s.{ %s }".format(expr, sel) - // case _ => () - // } - // "import %s.%s".format(expr, name) - // } + override def isLegalTopLevel = true + + def createImportForName(name: Name): String = { + selectors foreach { + case sel @ ImportSelector(old, _, `name`, _) => return "import %s.{ %s }".format(expr, sel) + case _ => () + } + "import %s.%s".format(expr, name) + } // TODO: Need to track these specially to honor Predef masking attempts, // because they must be the leading imports in the code generated for each // line. We can use the same machinery as Contexts now, anyway. - // def isPredefImport = isReferenceToPredef(expr) + def isPredefImport = isReferenceToPredef(expr) // wildcard imports, e.g. import foo._ private def selectorWild = selectors filter (_.name == nme.USCOREkw) diff --git a/src/compiler/scala/tools/nsc/interpreter/NamedParam.scala b/src/compiler/scala/tools/nsc/interpreter/NamedParam.scala index c10ba23691..eff0ef59c5 100644 --- a/src/compiler/scala/tools/nsc/interpreter/NamedParam.scala +++ b/src/compiler/scala/tools/nsc/interpreter/NamedParam.scala @@ -14,14 +14,14 @@ import scala.reflect.{ClassTag, classTag} trait NamedParamCreator { protected def freshName: () => String - // def apply(name: String, tpe: String, value: Any): NamedParam = NamedParamClass(name, tpe, value) + def apply(name: String, tpe: String, value: Any): NamedParam = NamedParamClass(name, tpe, value) def apply[T: ru.TypeTag : ClassTag](name: String, x: T): NamedParam = new Typed[T](name, x) def apply[T: ru.TypeTag : ClassTag](x: T): NamedParam = apply(freshName(), x) def clazz(name: String, x: Any): NamedParam = new Untyped(name, x) - // def clazz(x: Any): NamedParam = clazz(freshName(), x) + def clazz(x: Any): NamedParam = clazz(freshName(), x) - // implicit def namedValue[T: ru.TypeTag : ClassTag](name: String, x: T): NamedParam = apply(name, x) + implicit def namedValue[T: ru.TypeTag : ClassTag](name: String, x: T): NamedParam = apply(name, x) implicit def tuple[T: ru.TypeTag : ClassTag](pair: (String, T)): NamedParam = apply(pair._1, pair._2) } diff --git a/src/compiler/scala/tools/nsc/interpreter/Naming.scala b/src/compiler/scala/tools/nsc/interpreter/Naming.scala index 57b1205fb3..0d03a8669a 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Naming.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Naming.scala @@ -78,7 +78,7 @@ trait Naming { private lazy val userVar = new NameCreator(sessionNames.res) // var name, like res0 private lazy val internalVar = new NameCreator(sessionNames.ires) // internal var name, like $ires0 - // def isLineName(name: String) = (name startsWith sessionNames.line) && (name stripPrefix sessionNames.line forall (_.isDigit)) + def isLineName(name: String) = (name startsWith sessionNames.line) && (name stripPrefix sessionNames.line forall (_.isDigit)) def isUserVarName(name: String) = userVar didGenerate name def isInternalVarName(name: String) = internalVar didGenerate name diff --git a/src/compiler/scala/tools/nsc/interpreter/Parsed.scala b/src/compiler/scala/tools/nsc/interpreter/Parsed.scala index 3d72e4b2a4..24c01e9ae6 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Parsed.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Parsed.scala @@ -17,7 +17,7 @@ class Parsed private ( ) extends Delimited { def isEmpty = args.isEmpty def isUnqualified = args.size == 1 - // def isQualified = args.size > 1 + def isQualified = args.size > 1 def isAtStart = cursor <= 0 private var _verbosity = 0 @@ -31,7 +31,7 @@ class Parsed private ( def bufferTail = new Parsed(buffer drop headLength, cursor - headLength, delimited) withVerbosity verbosity def prev = new Parsed(buffer, cursor - 1, delimited) withVerbosity verbosity - // def next = new Parsed(buffer, cursor + 1, delimited) withVerbosity verbosity + def next = new Parsed(buffer, cursor + 1, delimited) withVerbosity verbosity def currentChar = buffer(cursor) def currentArg = args.last def position = @@ -41,8 +41,8 @@ class Parsed private ( def isFirstDelimiter = !isEmpty && isDelimiterChar(buffer.head) def isLastDelimiter = !isEmpty && isDelimiterChar(buffer.last) - // def firstIfDelimiter = if (isFirstDelimiter) buffer.head.toString else "" - // def lastIfDelimiter = if (isLastDelimiter) buffer.last.toString else "" + def firstIfDelimiter = if (isFirstDelimiter) buffer.head.toString else "" + def lastIfDelimiter = if (isLastDelimiter) buffer.last.toString else "" def isQuoted = false // TODO def isEscaped = !isAtStart && isEscapeChar(currentChar) && !isEscapeChar(prev.currentChar) @@ -56,13 +56,13 @@ object Parsed { private def onull(s: String) = if (s == null) "" else s - // def apply(s: String): Parsed = apply(onull(s), onull(s).length) + def apply(s: String): Parsed = apply(onull(s), onull(s).length) def apply(s: String, cursor: Int): Parsed = apply(onull(s), cursor, DefaultDelimiters) def apply(s: String, cursor: Int, delimited: Char => Boolean): Parsed = new Parsed(onull(s), cursor, delimited) - // def dotted(s: String): Parsed = dotted(onull(s), onull(s).length) + def dotted(s: String): Parsed = dotted(onull(s), onull(s).length) def dotted(s: String, cursor: Int): Parsed = new Parsed(onull(s), cursor, _ == '.') - // def undelimited(s: String, cursor: Int): Parsed = new Parsed(onull(s), cursor, _ => false) + def undelimited(s: String, cursor: Int): Parsed = new Parsed(onull(s), cursor, _ => false) } diff --git a/src/compiler/scala/tools/nsc/interpreter/Phased.scala b/src/compiler/scala/tools/nsc/interpreter/Phased.scala index 3cf448f4c2..e6b780f177 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Phased.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Phased.scala @@ -24,7 +24,7 @@ trait Phased { case NoPhaseName => false case name => active = name ; true } - // def getMulti = multi + def getMulti = multi def setMulti(phases: Seq[PhaseName]): Boolean = { if (phases contains NoPhaseName) false else { @@ -66,16 +66,16 @@ trait Phased { try parseInternal(str) catch { case _: Exception => NoPhaseName } - // def apply[T](body: => T) = immutable.SortedMap[PhaseName, T](atMap(PhaseName.all)(body): _*) + def apply[T](body: => T) = immutable.SortedMap[PhaseName, T](atMap(PhaseName.all)(body): _*) def atCurrent[T](body: => T): T = enteringPhase(get)(body) def multi[T](body: => T): Seq[T] = multi map (ph => at(ph)(body)) - // def all[T](body: => T): Seq[T] = atMulti(PhaseName.all)(body) - // def show[T](body: => T): Seq[T] = { - // val pairs = atMap(PhaseName.all)(body) - // pairs foreach { case (ph, op) => Console.println("%15s -> %s".format(ph, op.toString take 240)) } - // pairs map (_._2) - // } + def all[T](body: => T): Seq[T] = atMulti(PhaseName.all)(body) + def show[T](body: => T): Seq[T] = { + val pairs = atMap(PhaseName.all)(body) + pairs foreach { case (ph, op) => Console.println("%15s -> %s".format(ph, op.toString take 240)) } + pairs map (_._2) + } def at[T](ph: PhaseName)(body: => T): T = { val saved = get @@ -90,10 +90,10 @@ trait Phased { finally setMulti(saved) } - // def showAt[T](phs: Seq[PhaseName])(body: => T): Unit = - // atMap[T](phs)(body) foreach { - // case (ph, op) => Console.println("%15s -> %s".format(ph, op.toString take 240)) - // } + def showAt[T](phs: Seq[PhaseName])(body: => T): Unit = + atMap[T](phs)(body) foreach { + case (ph, op) => Console.println("%15s -> %s".format(ph, op.toString take 240)) + } def atMap[T](phs: Seq[PhaseName])(body: => T): Seq[(PhaseName, T)] = phs zip atMulti(phs)(body) @@ -112,7 +112,7 @@ trait Phased { def apply(id: Int): PhaseName = all find (_.id == id) getOrElse NoPhaseName implicit def apply(s: String): PhaseName = nameMap(s) - // implicit def defaultPhaseName: PhaseName = active + implicit def defaultPhaseName: PhaseName = active } sealed abstract class PhaseName { lazy val id = phase.id @@ -121,7 +121,7 @@ trait Phased { def isEmpty = this eq NoPhaseName // Execute some code during this phase. - // def apply[T](body: => T): T = enteringPhase(phase)(body) + def apply[T](body: => T): T = enteringPhase(phase)(body) } case object Parser extends PhaseName @@ -158,5 +158,5 @@ trait Phased { } implicit def phaseEnumToPhase(name: PhaseName): Phase = name.phase - // implicit def phaseNameToPhase(name: String): Phase = currentRun.phaseNamed(name) + implicit def phaseNameToPhase(name: String): Phase = currentRun.phaseNamed(name) } diff --git a/src/compiler/scala/tools/nsc/interpreter/Power.scala b/src/compiler/scala/tools/nsc/interpreter/Power.scala index 88c20c5096..ab0f1c0033 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Power.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Power.scala @@ -149,17 +149,17 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re // And whatever else there is to do. init.lines foreach (intp interpret _) } - // def valsDescription: String = { - // def to_str(m: Symbol) = "%12s %s".format( - // m.decodedName, "" + elimRefinement(m.accessedOrSelf.tpe) stripPrefix "scala.tools.nsc.") - - // ( rutil.info[ReplValsImpl].membersDeclared - // filter (m => m.isPublic && !m.hasModuleFlag && !m.isConstructor) - // sortBy (_.decodedName) - // map to_str - // mkString ("Name and type of values imported into the repl in power mode.\n\n", "\n", "") - // ) - // } + def valsDescription: String = { + def to_str(m: Symbol) = "%12s %s".format( + m.decodedName, "" + elimRefinement(m.accessedOrSelf.tpe) stripPrefix "scala.tools.nsc.") + + ( rutil.info[ReplValsImpl].membersDeclared + filter (m => m.isPublic && !m.hasModuleFlag && !m.isConstructor) + sortBy (_.decodedName) + map to_str + mkString ("Name and type of values imported into the repl in power mode.\n\n", "\n", "") + ) + } trait LowPriorityInternalInfo { implicit def apply[T: ru.TypeTag : ClassTag] : InternalInfo[T] = new InternalInfo[T](None) @@ -173,13 +173,13 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re * of the conveniences exist on that wrapper. */ trait LowPriorityInternalInfoWrapper { - // implicit def apply[T: ru.TypeTag : ClassTag] : InternalInfoWrapper[T] = new InternalInfoWrapper[T](None) + implicit def apply[T: ru.TypeTag : ClassTag] : InternalInfoWrapper[T] = new InternalInfoWrapper[T](None) } - // object InternalInfoWrapper extends LowPriorityInternalInfoWrapper { + object InternalInfoWrapper extends LowPriorityInternalInfoWrapper { - // } + } class InternalInfoWrapper[T: ru.TypeTag : ClassTag](value: Option[T] = None) { - // def ? : InternalInfo[T] = new InternalInfo[T](value) + def ? : InternalInfo[T] = new InternalInfo[T](value) } /** Todos... @@ -187,7 +187,7 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re * customizable symbol filter (had to hardcode no-spec to reduce noise) */ class InternalInfo[T](value: Option[T] = None)(implicit typeEvidence: ru.TypeTag[T], runtimeClassEvidence: ClassTag[T]) { - // private def newInfo[U: ru.TypeTag : ClassTag](value: U): InternalInfo[U] = new InternalInfo[U](Some(value)) + private def newInfo[U: ru.TypeTag : ClassTag](value: U): InternalInfo[U] = new InternalInfo[U](Some(value)) private def isSpecialized(s: Symbol) = s.name.toString contains "$mc" private def isImplClass(s: Symbol) = s.name.toString endsWith "$class" @@ -200,45 +200,45 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re ) def symbol = compilerSymbolFromTag(tag) def tpe = compilerTypeFromTag(tag) - // def name = symbol.name - // def companion = symbol.companionSymbol - // def info = symbol.info - // def moduleClass = symbol.moduleClass - // def owner = symbol.owner - // def owners = symbol.ownerChain drop 1 - // def signature = symbol.defString - - // def decls = info.decls - // def declsOverride = membersDeclared filter (_.isOverride) - // def declsOriginal = membersDeclared filterNot (_.isOverride) + def name = symbol.name + def companion = symbol.companionSymbol + def info = symbol.info + def moduleClass = symbol.moduleClass + def owner = symbol.owner + def owners = symbol.ownerChain drop 1 + def signature = symbol.defString + + def decls = info.decls + def declsOverride = membersDeclared filter (_.isOverride) + def declsOriginal = membersDeclared filterNot (_.isOverride) def members = membersUnabridged filterNot excludeMember def membersUnabridged = tpe.members.toList - // def membersDeclared = members filterNot excludeMember - // def membersInherited = members filterNot (membersDeclared contains _) - // def memberTypes = members filter (_.name.isTypeName) - // def memberMethods = members filter (_.isMethod) + def membersDeclared = members filterNot excludeMember + def membersInherited = members filterNot (membersDeclared contains _) + def memberTypes = members filter (_.name.isTypeName) + def memberMethods = members filter (_.isMethod) def pkg = symbol.enclosingPackage - // def pkgName = pkg.fullName - // def pkgClass = symbol.enclosingPackageClass - // def pkgMembers = pkg.info.members filterNot excludeMember - // def pkgClasses = pkgMembers filter (s => s.isClass && s.isDefinedInPackage) - // def pkgSymbols = new PackageSlurper(pkgClass).slurp() filterNot excludeMember + def pkgName = pkg.fullName + def pkgClass = symbol.enclosingPackageClass + def pkgMembers = pkg.info.members filterNot excludeMember + def pkgClasses = pkgMembers filter (s => s.isClass && s.isDefinedInPackage) + def pkgSymbols = new PackageSlurper(pkgClass).slurp() filterNot excludeMember def tag = typeEvidence def runtimeClass = runtimeClassEvidence.runtimeClass def shortClass = runtimeClass.getName split "[$.]" last def baseClasses = tpe.baseClasses - // def baseClassDecls = mapFrom(baseClasses)(_.info.decls.toList.sortBy(_.name)) - // def ancestors = baseClasses drop 1 - // def ancestorDeclares(name: String) = ancestors filter (_.info member newTermName(name) ne NoSymbol) - // def baseTypes = tpe.baseTypeSeq.toList + def baseClassDecls = mapFrom(baseClasses)(_.info.decls.toList.sortBy(_.name)) + def ancestors = baseClasses drop 1 + def ancestorDeclares(name: String) = ancestors filter (_.info member newTermName(name) ne NoSymbol) + def baseTypes = tpe.baseTypeSeq.toList - // def <:<[U: ru.TypeTag : ClassTag](other: U) = tpe <:< newInfo(other).tpe - // def lub[U: ru.TypeTag : ClassTag](other: U) = intp.global.lub(List(tpe, newInfo(other).tpe)) - // def glb[U: ru.TypeTag : ClassTag](other: U) = intp.global.glb(List(tpe, newInfo(other).tpe)) + def <:<[U: ru.TypeTag : ClassTag](other: U) = tpe <:< newInfo(other).tpe + def lub[U: ru.TypeTag : ClassTag](other: U) = intp.global.lub(List(tpe, newInfo(other).tpe)) + def glb[U: ru.TypeTag : ClassTag](other: U) = intp.global.glb(List(tpe, newInfo(other).tpe)) override def toString = value match { case Some(x) => "%s (%s)".format(x, shortClass) @@ -264,7 +264,7 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re } object Prettifier extends LowPriorityPrettifier { def stringOf(x: Any): String = scala.runtime.ScalaRunTime.stringOf(x) - // def prettify[T](value: T): TraversableOnce[String] = default[T] prettify value + def prettify[T](value: T): TraversableOnce[String] = default[T] prettify value def default[T] = new Prettifier[T] { def prettify(x: T): TraversableOnce[String] = AnyPrettifier prettify x def show(x: T): Unit = AnyPrettifier show x @@ -274,7 +274,7 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re def show(x: T): Unit def prettify(x: T): TraversableOnce[String] - // def show(xs: TraversableOnce[T]): Unit = prettify(xs) foreach println + def show(xs: TraversableOnce[T]): Unit = prettify(xs) foreach println def prettify(xs: TraversableOnce[T]): TraversableOnce[String] = xs flatMap (x => prettify(x)) } @@ -286,31 +286,31 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re pretty prettify f(value) foreach (StringPrettifier show _) def freq[U](p: T => U) = (value.toSeq groupBy p mapValues (_.size)).toList sortBy (-_._2) map (_.swap) - // def ppfreq[U](p: T => U): Unit = freq(p) foreach { case (count, key) => println("%5d %s".format(count, key)) } + def ppfreq[U](p: T => U): Unit = freq(p) foreach { case (count, key) => println("%5d %s".format(count, key)) } - // def |[U](f: Seq[T] => Seq[U]): Seq[U] = f(value) - // def ^^[U](f: T => U): Seq[U] = value map f - // def ^?[U](pf: PartialFunction[T, U]): Seq[U] = value collect pf + def |[U](f: Seq[T] => Seq[U]): Seq[U] = f(value) + def ^^[U](f: T => U): Seq[U] = value map f + def ^?[U](pf: PartialFunction[T, U]): Seq[U] = value collect pf - // def >>!(implicit ord: Ordering[T]): Unit = pp(_.sorted.distinct) + def >>!(implicit ord: Ordering[T]): Unit = pp(_.sorted.distinct) def >>(implicit ord: Ordering[T]): Unit = pp(_.sorted) def >!(): Unit = pp(_.distinct) def >(): Unit = pp(identity) - // def >#(): Unit = this ># (identity[T] _) - // def >#[U](p: T => U): Unit = this ppfreq p + def >#(): Unit = this ># (identity[T] _) + def >#[U](p: T => U): Unit = this ppfreq p - // def >?(p: T => Boolean): Unit = pp(_ filter p) - // def >?(s: String): Unit = pp(_ filter (_.toString contains s)) - // def >?(r: Regex): Unit = pp(_ filter (_.toString matches fixRegex(r))) + def >?(p: T => Boolean): Unit = pp(_ filter p) + def >?(s: String): Unit = pp(_ filter (_.toString contains s)) + def >?(r: Regex): Unit = pp(_ filter (_.toString matches fixRegex(r))) - // private def fixRegex(r: scala.util.matching.Regex): String = { - // val s = r.pattern.toString - // val prefix = if (s startsWith "^") "" else """^.*?""" - // val suffix = if (s endsWith "$") "" else """.*$""" + private def fixRegex(r: scala.util.matching.Regex): String = { + val s = r.pattern.toString + val prefix = if (s startsWith "^") "" else """^.*?""" + val suffix = if (s endsWith "$") "" else """.*$""" - // prefix + s + suffix - // } + prefix + s + suffix + } } class MultiPrettifierClass[T: Prettifier](val value: Seq[T]) extends PrettifierClass[T]() { } @@ -335,8 +335,8 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re def slurp(): String = io.Streamable.slurp(url) } class RichSymbolList(syms: List[Symbol]) { - // def sigs = syms map (_.defString) - // def infos = syms map (_.info) + def sigs = syms map (_.defString) + def infos = syms map (_.info) } trait Implicits1 { @@ -344,7 +344,7 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re implicit def replPrinting[T](x: T)(implicit pretty: Prettifier[T] = Prettifier.default[T]) = new SinglePrettifierClass[T](x) - // implicit def liftToTypeName(s: String): TypeName = newTypeName(s) + implicit def liftToTypeName(s: String): TypeName = newTypeName(s) } trait Implicits2 extends Implicits1 { class RichSymbol(sym: Symbol) { @@ -370,8 +370,8 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re implicit def replInputStream(in: InputStream)(implicit codec: Codec) = new RichInputStream(in) implicit def replEnhancedURLs(url: URL)(implicit codec: Codec): RichReplURL = new RichReplURL(url)(codec) - // implicit def liftToTermName(s: String): TermName = newTermName(s) - // implicit def replListOfSymbols(xs: List[Symbol]) = new RichSymbolList(xs) + implicit def liftToTermName(s: String): TermName = newTermName(s) + implicit def replListOfSymbols(xs: List[Symbol]) = new RichSymbolList(xs) } trait ReplUtilities { @@ -382,13 +382,13 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re def clazz[T: ru.TypeTag] = ru.typeOf[T].typeSymbol.suchThat(_.isClass) def info[T: ru.TypeTag : ClassTag] = InternalInfo[T] def ?[T: ru.TypeTag : ClassTag] = InternalInfo[T] - // def url(s: String) = { - // try new URL(s) - // catch { case _: MalformedURLException => - // if (Path(s).exists) Path(s).toURL - // else new URL("http://" + s) - // } - // } + def url(s: String) = { + try new URL(s) + catch { case _: MalformedURLException => + if (Path(s).exists) Path(s).toURL + else new URL("http://" + s) + } + } def sanitize(s: String): String = sanitize(s.getBytes()) def sanitize(s: Array[Byte]): String = (s map { case x if x.toChar.isControl => '?' @@ -406,11 +406,11 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re lazy val rutil: ReplUtilities = new ReplUtilities { } lazy val phased: Phased = new { val global: intp.global.type = intp.global } with Phased { } - // def context(code: String) = analyzer.rootContext(unit(code)) - // def source(code: String) = newSourceFile(code) + def context(code: String) = analyzer.rootContext(unit(code)) + def source(code: String) = newSourceFile(code) def unit(code: String) = newCompilationUnit(code) def trees(code: String) = parse(code) getOrElse Nil - // def typeOf(id: String) = intp.typeOfExpression(id) + def typeOf(id: String) = intp.typeOfExpression(id) override def toString = s""" |** Power mode status ** diff --git a/src/compiler/scala/tools/nsc/interpreter/ReplConfig.scala b/src/compiler/scala/tools/nsc/interpreter/ReplConfig.scala index d48ceb4eff..7cd0f436c4 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ReplConfig.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ReplConfig.scala @@ -14,9 +14,9 @@ trait ReplConfig { lazy val replProps = new ReplProps class TapMaker[T](x: T) { - // def tapInfo(msg: => String): T = tap(x => replinfo(parens(x))) + def tapInfo(msg: => String): T = tap(x => replinfo(parens(x))) def tapDebug(msg: => String): T = tap(x => repldbg(parens(x))) - // def tapTrace(msg: => String): T = tap(x => repltrace(parens(x))) + def tapTrace(msg: => String): T = tap(x => repltrace(parens(x))) def tap[U](f: T => U): T = { f(x) x @@ -28,12 +28,12 @@ trait ReplConfig { try Console println msg catch { case x: AssertionError => Console.println("Assertion error printing debugging output: " + x) } - // private[nsc] def repldbgex(ex: Throwable): Unit = { - // if (isReplDebug) { - // echo("Caught/suppressing: " + ex) - // ex.printStackTrace - // } - // } + private[nsc] def repldbgex(ex: Throwable): Unit = { + if (isReplDebug) { + echo("Caught/suppressing: " + ex) + ex.printStackTrace + } + } private[nsc] def repldbg(msg: => String) = if (isReplDebug) echo(msg) private[nsc] def repltrace(msg: => String) = if (isReplTrace) echo(msg) private[nsc] def replinfo(msg: => String) = if (isReplInfo) echo(msg) @@ -45,14 +45,14 @@ trait ReplConfig { repltrace(stackTraceString(unwrap(t))) alt } - // private[nsc] def substituteAndLog[T](alt: => T)(body: => T): T = - // substituteAndLog("" + alt, alt)(body) + private[nsc] def substituteAndLog[T](alt: => T)(body: => T): T = + substituteAndLog("" + alt, alt)(body) private[nsc] def substituteAndLog[T](label: String, alt: => T)(body: => T): T = { try body catch logAndDiscard(label, alt) } - // private[nsc] def squashAndLog(label: String)(body: => Unit): Unit = - // substituteAndLog(label, ())(body) + private[nsc] def squashAndLog(label: String)(body: => Unit): Unit = + substituteAndLog(label, ())(body) def isReplTrace: Boolean = replProps.trace def isReplDebug: Boolean = replProps.debug || isReplTrace diff --git a/src/compiler/scala/tools/nsc/interpreter/ReplProps.scala b/src/compiler/scala/tools/nsc/interpreter/ReplProps.scala index 22c27513d3..bc3e7a10d7 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ReplProps.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ReplProps.scala @@ -13,15 +13,15 @@ class ReplProps { private def bool(name: String) = BooleanProp.keyExists(name) private def int(name: String) = IntProp(name) - // val jlineDebug = bool("scala.tools.jline.internal.Log.debug") - // val jlineTrace = bool("scala.tools.jline.internal.Log.trace") + val jlineDebug = bool("scala.tools.jline.internal.Log.debug") + val jlineTrace = bool("scala.tools.jline.internal.Log.trace") val info = bool("scala.repl.info") val debug = bool("scala.repl.debug") val trace = bool("scala.repl.trace") val power = bool("scala.repl.power") - // val replInitCode = Prop[JFile]("scala.repl.initcode") + val replInitCode = Prop[JFile]("scala.repl.initcode") val replAutorunCode = Prop[JFile]("scala.repl.autoruncode") val powerInitCode = Prop[JFile]("scala.repl.power.initcode") val powerBanner = Prop[JFile]("scala.repl.power.banner") diff --git a/src/compiler/scala/tools/nsc/interpreter/ReplStrings.scala b/src/compiler/scala/tools/nsc/interpreter/ReplStrings.scala index ed035f8a1a..670bbf9bae 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ReplStrings.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ReplStrings.scala @@ -29,5 +29,5 @@ trait ReplStrings { "scala.runtime.ScalaRunTime.replStringOf(%s, %s)".format(x, maxlen) def words(s: String) = s.trim split "\\s+" filterNot (_ == "") toList - // def isQuoted(s: String) = (s.length >= 2) && (s.head == s.last) && ("\"'" contains s.head) + def isQuoted(s: String) = (s.length >= 2) && (s.head == s.last) && ("\"'" contains s.head) } diff --git a/src/compiler/scala/tools/nsc/interpreter/RichClass.scala b/src/compiler/scala/tools/nsc/interpreter/RichClass.scala index 7183db2dfb..4371f7fe05 100644 --- a/src/compiler/scala/tools/nsc/interpreter/RichClass.scala +++ b/src/compiler/scala/tools/nsc/interpreter/RichClass.scala @@ -10,7 +10,7 @@ import scala.reflect.{ ClassTag, classTag } class RichClass[T](val clazz: Class[T]) { def toTag: ClassTag[T] = ClassTag[T](clazz) - // def toTypeString: String = TypeStrings.fromClazz(clazz) + def toTypeString: String = TypeStrings.fromClazz(clazz) // Sadly isAnonymousClass does not return true for scala anonymous // classes because our naming scheme is not doing well against the @@ -20,13 +20,14 @@ class RichClass[T](val clazz: Class[T]) { catch { case _: java.lang.InternalError => false } // good ol' "Malformed class name" ) - def supertags: List[ClassTag[_]] = supers map (_.toTag) + /** It's not easy... to be... me... */ + def supermans: List[ClassTag[_]] = supers map (_.toTag) def superNames: List[String] = supers map (_.getName) def interfaces: List[JClass] = supers filter (_.isInterface) def hasAncestorName(f: String => Boolean) = superNames exists f def hasAncestor(f: JClass => Boolean) = supers exists f - // def hasAncestorInPackage(pkg: String) = hasAncestorName(_ startsWith (pkg + ".")) + def hasAncestorInPackage(pkg: String) = hasAncestorName(_ startsWith (pkg + ".")) def supers: List[JClass] = { def loop(x: JClass): List[JClass] = x.getSuperclass match { diff --git a/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala b/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala index a07f84cc10..bccd8158ec 100644 --- a/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala +++ b/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala @@ -19,11 +19,11 @@ extends InteractiveReader val history = NoHistory val completion = NoCompletion - // def init() = () + def init() = () def reset() = () - // def eraseLine() = () + def eraseLine() = () def redrawLine() = () - // def currentLine = "" + def currentLine = "" def readOneLine(prompt: String): String = { if (interactive) { out.print(prompt) @@ -40,4 +40,4 @@ object SimpleReader { def apply(in: BufferedReader = defaultIn, out: JPrintWriter = defaultOut, interactive: Boolean = true): SimpleReader = new SimpleReader(in, out, interactive) -} +} \ No newline at end of file diff --git a/src/compiler/scala/tools/nsc/interpreter/TypeStrings.scala b/src/compiler/scala/tools/nsc/interpreter/TypeStrings.scala index f9749feabe..9fb79a9d6f 100644 --- a/src/compiler/scala/tools/nsc/interpreter/TypeStrings.scala +++ b/src/compiler/scala/tools/nsc/interpreter/TypeStrings.scala @@ -33,7 +33,7 @@ trait StructuredTypeStrings extends DestructureTypes { val NoGrouping = Grouping("", "", "", false) val ListGrouping = Grouping("(", ", ", ")", false) val ProductGrouping = Grouping("(", ", ", ")", true) - // val ParamGrouping = Grouping("(", ", ", ")", true) + val ParamGrouping = Grouping("(", ", ", ")", true) val BlockGrouping = Grouping(" { ", "; ", "}", false) private def str(level: Int)(body: => String): String = " " * level + body @@ -189,7 +189,7 @@ trait TypeStrings { else enclClass.getName + "." + (name stripPrefix enclPre) ) } - // def scalaName(ct: ClassTag[_]): String = scalaName(ct.runtimeClass) + def scalaName(ct: ClassTag[_]): String = scalaName(ct.runtimeClass) def anyClass(x: Any): JClass = if (x == null) null else x.getClass private def brackets(tps: String*): String = @@ -220,7 +220,7 @@ trait TypeStrings { * practice to rely on toString for correctness) generated the VALID string * representation of the type. */ - // def fromTypedValue[T: ru.TypeTag : ClassTag](x: T): String = fromTag[T] + def fromTypedValue[T: ru.TypeTag : ClassTag](x: T): String = fromTag[T] def fromValue(value: Any): String = if (value == null) "Null" else fromClazz(anyClass(value)) def fromClazz(clazz: JClass): String = scalaName(clazz) + tparamString(clazz) def fromTag[T: ru.TypeTag : ClassTag] : String = scalaName(classTag[T].runtimeClass) + tparamString[T] @@ -241,12 +241,12 @@ trait TypeStrings { } } - // val typeTransforms = List( - // "java.lang." -> "", - // "scala.collection.immutable." -> "immutable.", - // "scala.collection.mutable." -> "mutable.", - // "scala.collection.generic." -> "generic." - // ) + val typeTransforms = List( + "java.lang." -> "", + "scala.collection.immutable." -> "immutable.", + "scala.collection.mutable." -> "mutable.", + "scala.collection.generic." -> "generic." + ) } object TypeStrings extends TypeStrings { } diff --git a/src/compiler/scala/tools/nsc/interpreter/package.scala b/src/compiler/scala/tools/nsc/interpreter/package.scala index e6c9adb296..6a2d69db2c 100644 --- a/src/compiler/scala/tools/nsc/interpreter/package.scala +++ b/src/compiler/scala/tools/nsc/interpreter/package.scala @@ -48,7 +48,7 @@ package object interpreter extends ReplConfig with ReplStrings { private[nsc] implicit def enrichClass[T](clazz: Class[T]) = new RichClass[T](clazz) private[nsc] implicit def enrichAnyRefWithTap[T](x: T) = new TapMaker(x) - // private[nsc] def tracing[T](msg: String)(x: T): T = x.tapTrace(msg) + private[nsc] def tracing[T](msg: String)(x: T): T = x.tapTrace(msg) private[nsc] def debugging[T](msg: String)(x: T) = x.tapDebug(msg) private val ourClassloader = getClass.getClassLoader @@ -68,38 +68,38 @@ package object interpreter extends ReplConfig with ReplStrings { import global.{ reporter => _, _ } import definitions._ - // lazy val tagOfStdReplVals = staticTypeTag[scala.tools.nsc.interpreter.StdReplVals] + lazy val tagOfStdReplVals = staticTypeTag[scala.tools.nsc.interpreter.StdReplVals] protected def echo(msg: String) = { Console.out println msg Console.out.flush() } - // def wrapCommand(line: String): String = { - // def failMsg = "Argument to :wrap must be the name of a method with signature [T](=> T): T" - - // words(line) match { - // case Nil => - // intp.executionWrapper match { - // case "" => "No execution wrapper is set." - // case s => "Current execution wrapper: " + s - // } - // case "clear" :: Nil => - // intp.executionWrapper match { - // case "" => "No execution wrapper is set." - // case s => intp.clearExecutionWrapper() ; "Cleared execution wrapper." - // } - // case wrapper :: Nil => - // intp.typeOfExpression(wrapper) match { - // case PolyType(List(targ), MethodType(List(arg), restpe)) => - // setExecutionWrapper(originalPath(wrapper)) - // "Set wrapper to '" + wrapper + "'" - // case tp => - // failMsg + "\nFound: " - // } - // case _ => failMsg - // } - // } + def wrapCommand(line: String): String = { + def failMsg = "Argument to :wrap must be the name of a method with signature [T](=> T): T" + + words(line) match { + case Nil => + intp.executionWrapper match { + case "" => "No execution wrapper is set." + case s => "Current execution wrapper: " + s + } + case "clear" :: Nil => + intp.executionWrapper match { + case "" => "No execution wrapper is set." + case s => intp.clearExecutionWrapper() ; "Cleared execution wrapper." + } + case wrapper :: Nil => + intp.typeOfExpression(wrapper) match { + case PolyType(List(targ), MethodType(List(arg), restpe)) => + setExecutionWrapper(originalPath(wrapper)) + "Set wrapper to '" + wrapper + "'" + case tp => + failMsg + "\nFound: " + } + case _ => failMsg + } + } def implicitsCommand(line: String): String = { def p(x: Any) = intp.reporter.printMessage("" + x) diff --git a/src/compiler/scala/tools/nsc/interpreter/session/History.scala b/src/compiler/scala/tools/nsc/interpreter/session/History.scala index b727a0494f..daa05b86db 100644 --- a/src/compiler/scala/tools/nsc/interpreter/session/History.scala +++ b/src/compiler/scala/tools/nsc/interpreter/session/History.scala @@ -14,15 +14,15 @@ trait History { def asStrings: List[String] def index: Int def size: Int - // def grep(s: String): List[String] + def grep(s: String): List[String] } object NoHistory extends History { def asStrings = Nil - // def grep(s: String) = Nil + def grep(s: String) = Nil def index = 0 def size = 0 } -// object History { -// def empty: History = NoHistory -// } +object History { + def empty: History = NoHistory +} diff --git a/src/compiler/scala/tools/nsc/interpreter/session/SimpleHistory.scala b/src/compiler/scala/tools/nsc/interpreter/session/SimpleHistory.scala index 06e431fb30..9f4e2b9df3 100644 --- a/src/compiler/scala/tools/nsc/interpreter/session/SimpleHistory.scala +++ b/src/compiler/scala/tools/nsc/interpreter/session/SimpleHistory.scala @@ -55,8 +55,8 @@ class SimpleHistory extends JLineHistory { def moveToEnd(): Unit = setTo(size) // scala legacy interface - // def asList: List[JEntry] = toEntries().toList - // def asJavaList = entries() + def asList: List[JEntry] = toEntries().toList + def asJavaList = entries() def asStrings = buf.toList - // def grep(s: String) = buf.toList filter (_ contains s) + def grep(s: String) = buf.toList filter (_ contains s) } diff --git a/src/compiler/scala/tools/nsc/io/Fileish.scala b/src/compiler/scala/tools/nsc/io/Fileish.scala index 77d12ea022..7b4e385dd8 100644 --- a/src/compiler/scala/tools/nsc/io/Fileish.scala +++ b/src/compiler/scala/tools/nsc/io/Fileish.scala @@ -1,33 +1,33 @@ -// /* NSC -- new Scala compiler -// * Copyright 2005-2013 LAMP/EPFL -// * @author Paul Phillips -// */ +/* NSC -- new Scala compiler + * Copyright 2005-2013 LAMP/EPFL + * @author Paul Phillips + */ -// package scala.tools.nsc -// package io +package scala.tools.nsc +package io -// import java.io.{ InputStream } -// import java.util.jar.JarEntry +import java.io.{ InputStream } +import java.util.jar.JarEntry -// /** A common interface for File-based things and Stream-based things. -// * (In particular, io.File and JarEntry.) -// */ -// class Fileish(val path: Path, val input: () => InputStream) extends Streamable.Chars { -// def inputStream() = input() +/** A common interface for File-based things and Stream-based things. + * (In particular, io.File and JarEntry.) + */ +class Fileish(val path: Path, val input: () => InputStream) extends Streamable.Chars { + def inputStream() = input() -// def parent = path.parent -// def name = path.name -// def isSourceFile = path.hasExtension("java", "scala") + def parent = path.parent + def name = path.name + def isSourceFile = path.hasExtension("java", "scala") -// private lazy val pkgLines = lines() collect { case x if x startsWith "package " => x stripPrefix "package" trim } -// lazy val pkgFromPath = parent.path.replaceAll("""[/\\]""", ".") -// lazy val pkgFromSource = pkgLines map (_ stripSuffix ";") mkString "." + private lazy val pkgLines = lines() collect { case x if x startsWith "package " => x stripPrefix "package" trim } + lazy val pkgFromPath = parent.path.replaceAll("""[/\\]""", ".") + lazy val pkgFromSource = pkgLines map (_ stripSuffix ";") mkString "." -// override def toString = path.path -// } + override def toString = path.path +} -// object Fileish { -// def apply(f: File): Fileish = new Fileish(f, () => f.inputStream()) -// def apply(f: JarEntry, in: () => InputStream): Fileish = new Fileish(Path(f.getName), in) -// def apply(path: String, in: () => InputStream): Fileish = new Fileish(Path(path), in) -// } +object Fileish { + def apply(f: File): Fileish = new Fileish(f, () => f.inputStream()) + def apply(f: JarEntry, in: () => InputStream): Fileish = new Fileish(Path(f.getName), in) + def apply(path: String, in: () => InputStream): Fileish = new Fileish(Path(path), in) +} diff --git a/src/compiler/scala/tools/nsc/io/Jar.scala b/src/compiler/scala/tools/nsc/io/Jar.scala index 6f1c322391..ef2c9b13c0 100644 --- a/src/compiler/scala/tools/nsc/io/Jar.scala +++ b/src/compiler/scala/tools/nsc/io/Jar.scala @@ -36,9 +36,9 @@ class Jar(file: File) extends Iterable[JarEntry] { def this(jfile: JFile) = this(File(jfile)) def this(path: String) = this(File(path)) - // protected def errorFn(msg: String): Unit = Console println msg + protected def errorFn(msg: String): Unit = Console println msg - // lazy val jarFile = new JarFile(file.jfile) + lazy val jarFile = new JarFile(file.jfile) lazy val manifest = withJarInput(s => Option(s.getManifest)) def mainClass = manifest map (f => f(Name.MAIN_CLASS)) @@ -63,12 +63,12 @@ class Jar(file: File) extends Iterable[JarEntry] { Iterator continually in.getNextJarEntry() takeWhile (_ != null) foreach f } override def iterator: Iterator[JarEntry] = this.toList.iterator - // def fileishIterator: Iterator[Fileish] = jarFile.entries.asScala map (x => Fileish(x, () => getEntryStream(x))) + def fileishIterator: Iterator[Fileish] = jarFile.entries.asScala map (x => Fileish(x, () => getEntryStream(x))) - // private def getEntryStream(entry: JarEntry) = jarFile getInputStream entry match { - // case null => errorFn("No such entry: " + entry) ; null - // case x => x - // } + private def getEntryStream(entry: JarEntry) = jarFile getInputStream entry match { + case null => errorFn("No such entry: " + entry) ; null + case x => x + } override def toString = "" + file } @@ -130,7 +130,7 @@ object Jar { m } def apply(manifest: JManifest): WManifest = new WManifest(manifest) - // implicit def unenrichManifest(x: WManifest): JManifest = x.underlying + implicit def unenrichManifest(x: WManifest): JManifest = x.underlying } class WManifest(manifest: JManifest) { for ((k, v) <- initialMainAttrs) @@ -147,12 +147,12 @@ object Jar { } def apply(name: Attributes.Name): String = attrs(name) - // def apply(name: String): String = apply(new Attributes.Name(name)) + def apply(name: String): String = apply(new Attributes.Name(name)) def update(key: Attributes.Name, value: String) = attrs.put(key, value) - // def update(key: String, value: String) = attrs.put(new Attributes.Name(key), value) + def update(key: String, value: String) = attrs.put(new Attributes.Name(key), value) - // def mainClass: String = apply(Name.MAIN_CLASS) - // def mainClass_=(value: String) = update(Name.MAIN_CLASS, value) + def mainClass: String = apply(Name.MAIN_CLASS) + def mainClass_=(value: String) = update(Name.MAIN_CLASS, value) } // See http://download.java.net/jdk7/docs/api/java/nio/file/Path.html diff --git a/src/compiler/scala/tools/nsc/io/MsilFile.scala b/src/compiler/scala/tools/nsc/io/MsilFile.scala index 881af2e87a..1a3a4f5c81 100644 --- a/src/compiler/scala/tools/nsc/io/MsilFile.scala +++ b/src/compiler/scala/tools/nsc/io/MsilFile.scala @@ -15,4 +15,4 @@ import ch.epfl.lamp.compiler.msil.{ Type => MsilType } class MsilFile(val msilType: MsilType) extends VirtualFile(msilType.FullName, msilType.Namespace) { } -// object NoMsilFile extends MsilFile(null) { } +object NoMsilFile extends MsilFile(null) { } diff --git a/src/compiler/scala/tools/nsc/io/Pickler.scala b/src/compiler/scala/tools/nsc/io/Pickler.scala index 3f16784b2d..56ff4a57ee 100644 --- a/src/compiler/scala/tools/nsc/io/Pickler.scala +++ b/src/compiler/scala/tools/nsc/io/Pickler.scala @@ -76,7 +76,7 @@ abstract class Pickler[T] { * @param fromNull an implicit evidence parameter ensuring that the type of values * handled by this pickler contains `null`. */ - // def orNull(implicit fromNull: Null <:< T): Pickler[T] = nullablePickler(this) + def orNull(implicit fromNull: Null <:< T): Pickler[T] = nullablePickler(this) /** A conditional pickler obtained from the current pickler. * @param cond the condition to test to find out whether pickler can handle @@ -93,7 +93,7 @@ abstract class Pickler[T] { object Pickler { - // var picklerDebugMode = false + var picklerDebugMode = false /** A base class representing unpickler result. It has two subclasses: * `UnpickleSucess` for successful unpicklings and `UnpickleFailure` for failures, @@ -176,14 +176,14 @@ object Pickler { /** A converter from binary functions to functions over `~`-pairs */ - // implicit def fromTilde[T1, T2, R](f: (T1, T2) => R): T1 ~ T2 => R = { case x1 ~ x2 => f(x1, x2) } + implicit def fromTilde[T1, T2, R](f: (T1, T2) => R): T1 ~ T2 => R = { case x1 ~ x2 => f(x1, x2) } /** An converter from unctions returning Options over pair to functions returning `~`-pairs * The converted function will raise a `MatchError` where the original function returned * a `None`. This converter is useful for turning `unapply` methods of case classes * into wrapper methods that can be passed as second argument to `wrap`. */ - // implicit def toTilde[T1, T2, S](f: S => Option[(T1, T2)]): S => T1 ~ T2 = { x => (f(x): @unchecked) match { case Some((x1, x2)) => x1 ~ x2 } } + implicit def toTilde[T1, T2, S](f: S => Option[(T1, T2)]): S => T1 ~ T2 = { x => (f(x): @unchecked) match { case Some((x1, x2)) => x1 ~ x2 } } /** Same as `p.labelled(label)`. */ @@ -250,13 +250,13 @@ object Pickler { /** Same as `p.orNull` */ - // def nullablePickler[T](p: Pickler[T])(implicit fromNull: Null <:< T): Pickler[T] = new Pickler[T] { - // def pickle(wr: Writer, x: T) = - // if (x == null) wr.write("null") else p.pickle(wr, x) - // def unpickle(rd: Lexer): Unpickled[T] = - // if (rd.token == NullLit) nextSuccess(rd, fromNull(null)) - // else p.unpickle(rd) - // } + def nullablePickler[T](p: Pickler[T])(implicit fromNull: Null <:< T): Pickler[T] = new Pickler[T] { + def pickle(wr: Writer, x: T) = + if (x == null) wr.write("null") else p.pickle(wr, x) + def unpickle(rd: Lexer): Unpickled[T] = + if (rd.token == NullLit) nextSuccess(rd, fromNull(null)) + else p.unpickle(rd) + } /** A conditional pickler for singleton objects. It represents these * with the object's underlying class as a label. @@ -330,20 +330,20 @@ object Pickler { tokenPickler("integer literal") { case IntLit(s) => s.toLong } /** A pickler for values of type `Double`, represented as floating point literals */ - // implicit val doublePickler: Pickler[Double] = - // tokenPickler("floating point literal") { case FloatLit(s) => s.toDouble } + implicit val doublePickler: Pickler[Double] = + tokenPickler("floating point literal") { case FloatLit(s) => s.toDouble } /** A pickler for values of type `Byte`, represented as integer literals */ - // implicit val bytePickler: Pickler[Byte] = longPickler.wrapped { _.toByte } { _.toLong } + implicit val bytePickler: Pickler[Byte] = longPickler.wrapped { _.toByte } { _.toLong } /** A pickler for values of type `Short`, represented as integer literals */ - // implicit val shortPickler: Pickler[Short] = longPickler.wrapped { _.toShort } { _.toLong } + implicit val shortPickler: Pickler[Short] = longPickler.wrapped { _.toShort } { _.toLong } /** A pickler for values of type `Int`, represented as integer literals */ implicit val intPickler: Pickler[Int] = longPickler.wrapped { _.toInt } { _.toLong } /** A pickler for values of type `Float`, represented as floating point literals */ - // implicit val floatPickler: Pickler[Float] = doublePickler.wrapped { _.toFloat } { _.toLong } + implicit val floatPickler: Pickler[Float] = doublePickler.wrapped { _.toFloat } { _.toLong } /** A conditional pickler for the boolean value `true` */ private val truePickler = @@ -373,15 +373,15 @@ object Pickler { } /** A pickler for values of type `Char`, represented as string literals of length 1 */ - // implicit val charPickler: Pickler[Char] = - // stringPickler - // .wrapped { s => require(s.length == 1, "single character string literal expected, but "+quoted(s)+" found"); s(0) } { _.toString } + implicit val charPickler: Pickler[Char] = + stringPickler + .wrapped { s => require(s.length == 1, "single character string literal expected, but "+quoted(s)+" found"); s(0) } { _.toString } /** A pickler for pairs, represented as `~`-pairs */ - // implicit def tuple2Pickler[T1: Pickler, T2: Pickler]: Pickler[(T1, T2)] = - // (pkl[T1] ~ pkl[T2]) - // .wrapped { case x1 ~ x2 => (x1, x2) } { case (x1, x2) => x1 ~ x2 } - // .labelled ("tuple2") + implicit def tuple2Pickler[T1: Pickler, T2: Pickler]: Pickler[(T1, T2)] = + (pkl[T1] ~ pkl[T2]) + .wrapped { case x1 ~ x2 => (x1, x2) } { case (x1, x2) => x1 ~ x2 } + .labelled ("tuple2") /** A pickler for 3-tuples, represented as `~`-tuples */ implicit def tuple3Pickler[T1, T2, T3](implicit p1: Pickler[T1], p2: Pickler[T2], p3: Pickler[T3]): Pickler[(T1, T2, T3)] = @@ -390,34 +390,34 @@ object Pickler { .labelled ("tuple3") /** A pickler for 4-tuples, represented as `~`-tuples */ - // implicit def tuple4Pickler[T1, T2, T3, T4](implicit p1: Pickler[T1], p2: Pickler[T2], p3: Pickler[T3], p4: Pickler[T4]): Pickler[(T1, T2, T3, T4)] = - // (p1 ~ p2 ~ p3 ~ p4) - // .wrapped { case x1 ~ x2 ~ x3 ~ x4 => (x1, x2, x3, x4) } { case (x1, x2, x3, x4) => x1 ~ x2 ~ x3 ~ x4 } - // .labelled ("tuple4") + implicit def tuple4Pickler[T1, T2, T3, T4](implicit p1: Pickler[T1], p2: Pickler[T2], p3: Pickler[T3], p4: Pickler[T4]): Pickler[(T1, T2, T3, T4)] = + (p1 ~ p2 ~ p3 ~ p4) + .wrapped { case x1 ~ x2 ~ x3 ~ x4 => (x1, x2, x3, x4) } { case (x1, x2, x3, x4) => x1 ~ x2 ~ x3 ~ x4 } + .labelled ("tuple4") /** A conditional pickler for the `scala.None` object */ - // implicit val nonePickler = singletonPickler(None) + implicit val nonePickler = singletonPickler(None) /** A conditional pickler for instances of class `scala.Some` */ - // implicit def somePickler[T: Pickler]: CondPickler[Some[T]] = - // pkl[T] - // .wrapped { Some(_) } { _.get } - // .asClass (classOf[Some[T]]) + implicit def somePickler[T: Pickler]: CondPickler[Some[T]] = + pkl[T] + .wrapped { Some(_) } { _.get } + .asClass (classOf[Some[T]]) /** A pickler for optional values */ - // implicit def optionPickler[T: Pickler]: Pickler[Option[T]] = nonePickler | somePickler[T] + implicit def optionPickler[T: Pickler]: Pickler[Option[T]] = nonePickler | somePickler[T] /** A pickler for list values */ implicit def listPickler[T: Pickler]: Pickler[List[T]] = iterPickler[T] .wrapped { _.toList } { _.iterator } .labelled ("scala.List") /** A pickler for vector values */ - // implicit def vectorPickler[T: Pickler]: Pickler[Vector[T]] = - // iterPickler[T] .wrapped { Vector() ++ _ } { _.iterator } .labelled ("scala.Vector") + implicit def vectorPickler[T: Pickler]: Pickler[Vector[T]] = + iterPickler[T] .wrapped { Vector() ++ _ } { _.iterator } .labelled ("scala.Vector") /** A pickler for array values */ - // implicit def array[T : ClassTag : Pickler]: Pickler[Array[T]] = - // iterPickler[T] .wrapped { _.toArray} { _.iterator } .labelled ("scala.Array") + implicit def array[T : ClassTag : Pickler]: Pickler[Array[T]] = + iterPickler[T] .wrapped { _.toArray} { _.iterator } .labelled ("scala.Array") } /** A subclass of Pickler can indicate whether a particular value can be pickled by instances diff --git a/src/compiler/scala/tools/nsc/io/Socket.scala b/src/compiler/scala/tools/nsc/io/Socket.scala index cb264a671c..e766c1b2fd 100644 --- a/src/compiler/scala/tools/nsc/io/Socket.scala +++ b/src/compiler/scala/tools/nsc/io/Socket.scala @@ -28,13 +28,13 @@ object Socket { private val optHandler = handlerFn[Option[T]](_ => None) private val eitherHandler = handlerFn[Either[Throwable, T]](x => Left(x)) - // def getOrElse[T1 >: T](alt: T1): T1 = opt getOrElse alt + def getOrElse[T1 >: T](alt: T1): T1 = opt getOrElse alt def either: Either[Throwable, T] = try Right(f()) catch eitherHandler def opt: Option[T] = try Some(f()) catch optHandler } - // def newIPv4Server(port: Int = 0) = new Box(() => preferringIPv4(new ServerSocket(0))) - // def newServer(port: Int = 0) = new Box(() => new ServerSocket(0)) + def newIPv4Server(port: Int = 0) = new Box(() => preferringIPv4(new ServerSocket(0))) + def newServer(port: Int = 0) = new Box(() => new ServerSocket(0)) def localhost(port: Int) = apply(InetAddress.getLocalHost(), port) def apply(host: InetAddress, port: Int) = new Box(() => new Socket(new JSocket(host, port))) def apply(host: String, port: Int) = new Box(() => new Socket(new JSocket(host, port))) @@ -62,4 +62,4 @@ class Socket(jsocket: JSocket) extends Streamable.Bytes with Closeable { out.close() } } -} +} \ No newline at end of file diff --git a/src/compiler/scala/tools/nsc/io/SourceReader.scala b/src/compiler/scala/tools/nsc/io/SourceReader.scala index f6759be5eb..af745eb3e8 100644 --- a/src/compiler/scala/tools/nsc/io/SourceReader.scala +++ b/src/compiler/scala/tools/nsc/io/SourceReader.scala @@ -34,7 +34,7 @@ class SourceReader(decoder: CharsetDecoder, reporter: Reporter) { } /** Reads the file with the specified name. */ - // def read(filename: String): Array[Char]= read(new JFile(filename)) + def read(filename: String): Array[Char]= read(new JFile(filename)) /** Reads the specified file. */ def read(file: JFile): Array[Char] = { diff --git a/src/compiler/scala/tools/nsc/io/package.scala b/src/compiler/scala/tools/nsc/io/package.scala index e9fb8a6d98..c29a7c96df 100644 --- a/src/compiler/scala/tools/nsc/io/package.scala +++ b/src/compiler/scala/tools/nsc/io/package.scala @@ -20,14 +20,14 @@ package object io { type Path = scala.reflect.io.Path val Path = scala.reflect.io.Path type PlainFile = scala.reflect.io.PlainFile - // val PlainFile = scala.reflect.io.PlainFile + val PlainFile = scala.reflect.io.PlainFile val Streamable = scala.reflect.io.Streamable type VirtualDirectory = scala.reflect.io.VirtualDirectory type VirtualFile = scala.reflect.io.VirtualFile - // val ZipArchive = scala.reflect.io.ZipArchive + val ZipArchive = scala.reflect.io.ZipArchive type ZipArchive = scala.reflect.io.ZipArchive - // implicit def postfixOps = scala.language.postfixOps // make all postfix ops in this package compile without warning + implicit def postfixOps = scala.language.postfixOps // make all postfix ops in this package compile without warning type JManifest = java.util.jar.Manifest type JFile = java.io.File @@ -38,10 +38,10 @@ package object io { def runnable(body: => Unit): Runnable = new Runnable { override def run() = body } def callable[T](body: => T): Callable[T] = new Callable[T] { override def call() = body } def spawn[T](body: => T): Future[T] = daemonThreadPool submit callable(body) - // def submit(runnable: Runnable) = daemonThreadPool submit runnable + def submit(runnable: Runnable) = daemonThreadPool submit runnable // Create, start, and return a daemon thread - // def daemonize(body: => Unit): Thread = newThread(_ setDaemon true)(body) + def daemonize(body: => Unit): Thread = newThread(_ setDaemon true)(body) def newThread(f: Thread => Unit)(body: => Unit): Thread = { val thread = new Thread(runnable(body)) f(thread) @@ -50,11 +50,11 @@ package object io { } // Set a timer to execute the given code. - // def timer(seconds: Int)(body: => Unit): Timer = { - // val alarm = new Timer(true) // daemon - // val tt = new TimerTask { def run() = body } + def timer(seconds: Int)(body: => Unit): Timer = { + val alarm = new Timer(true) // daemon + val tt = new TimerTask { def run() = body } - // alarm.schedule(tt, seconds * 1000) - // alarm - // } + alarm.schedule(tt, seconds * 1000) + alarm + } } diff --git a/src/compiler/scala/tools/nsc/javac/JavaParsers.scala b/src/compiler/scala/tools/nsc/javac/JavaParsers.scala index 63f08c42ec..2f6c13dd67 100644 --- a/src/compiler/scala/tools/nsc/javac/JavaParsers.scala +++ b/src/compiler/scala/tools/nsc/javac/JavaParsers.scala @@ -35,7 +35,7 @@ trait JavaParsers extends ast.parser.ParsersCommon with JavaScanners { abstract class JavaParser extends ParserCommon { val in: JavaScanner - // protected def posToReport: Int = in.currentPos + protected def posToReport: Int = in.currentPos def freshName(prefix : String): Name protected implicit def i2p(offset : Int) : Position private implicit def p2i(pos : Position): Int = if (pos.isDefined) pos.point else -1 @@ -94,11 +94,11 @@ trait JavaParsers extends ast.parser.ParsersCommon with JavaScanners { if (skipIt) skip() } - // def warning(msg: String) : Unit = warning(in.currentPos, msg) + def warning(msg: String) : Unit = warning(in.currentPos, msg) def errorTypeTree = TypeTree().setType(ErrorType) setPos in.currentPos - // def errorTermTree = Literal(Constant(null)) setPos in.currentPos - // def errorPatternTree = blankExpr setPos in.currentPos + def errorTermTree = Literal(Constant(null)) setPos in.currentPos + def errorPatternTree = blankExpr setPos in.currentPos // --------- tree building ----------------------------- diff --git a/src/compiler/scala/tools/nsc/javac/JavaScanners.scala b/src/compiler/scala/tools/nsc/javac/JavaScanners.scala index 95a22f847b..e230585a8b 100644 --- a/src/compiler/scala/tools/nsc/javac/JavaScanners.scala +++ b/src/compiler/scala/tools/nsc/javac/JavaScanners.scala @@ -57,14 +57,14 @@ trait JavaScanners extends ast.parser.ScannersCommon { /** ... */ abstract class AbstractJavaScanner extends AbstractJavaTokenData { - // implicit def p2g(pos: Position): ScanPosition + implicit def p2g(pos: Position): ScanPosition implicit def g2p(pos: ScanPosition): Position /** the last error position */ - // var errpos: ScanPosition - // var lastPos: ScanPosition - // def skipToken: ScanPosition + var errpos: ScanPosition + var lastPos: ScanPosition + def skipToken: ScanPosition def nextToken(): Unit def next: AbstractJavaTokenData def intVal(negated: Boolean): Long @@ -73,7 +73,7 @@ trait JavaScanners extends ast.parser.ScannersCommon { def floatVal: Double = floatVal(false) //def token2string(token : Int) : String = configuration.token2string(token) /** return recent scala doc, if any */ - // def flushDoc: DocComment + def flushDoc: DocComment def currentPos: Position } @@ -227,16 +227,16 @@ trait JavaScanners extends ast.parser.ScannersCommon { abstract class JavaScanner extends AbstractJavaScanner with JavaTokenData with Cloneable with ScannerCommon { override def intVal = super.intVal// todo: needed? override def floatVal = super.floatVal - // override var errpos: Int = NoPos + override var errpos: Int = NoPos def currentPos: Position = g2p(pos - 1) var in: JavaCharArrayReader = _ - // def dup: JavaScanner = { - // val dup = clone().asInstanceOf[JavaScanner] - // dup.in = in.dup - // dup - // } + def dup: JavaScanner = { + val dup = clone().asInstanceOf[JavaScanner] + dup.in = in.dup + dup + } /** character buffer for literals */ @@ -256,11 +256,11 @@ trait JavaScanners extends ast.parser.ScannersCommon { */ var docBuffer: StringBuilder = null - // def flushDoc: DocComment = { - // val ret = if (docBuffer != null) DocComment(docBuffer.toString, NoPosition) else null - // docBuffer = null - // ret - // } + def flushDoc: DocComment = { + val ret = if (docBuffer != null) DocComment(docBuffer.toString, NoPosition) else null + docBuffer = null + ret + } /** add the given character to the documentation buffer */ @@ -279,10 +279,10 @@ trait JavaScanners extends ast.parser.ScannersCommon { /** read next token and return last position */ - // def skipToken: Int = { - // val p = pos; nextToken - // p - 1 - // } + def skipToken: Int = { + val p = pos; nextToken + p - 1 + } def nextToken() { if (next.token == EMPTY) { @@ -868,7 +868,7 @@ trait JavaScanners extends ast.parser.ScannersCommon { def syntaxError(pos: Int, msg: String) { error(pos, msg) token = ERROR - // errpos = pos + errpos = pos } /** generate an error at the current token position @@ -879,7 +879,7 @@ trait JavaScanners extends ast.parser.ScannersCommon { def incompleteInputError(msg: String) { incompleteInputError(pos, msg) token = EOF - // errpos = pos + errpos = pos } override def toString() = token match { @@ -918,11 +918,11 @@ trait JavaScanners extends ast.parser.ScannersCommon { class JavaUnitScanner(unit: CompilationUnit) extends JavaScanner { in = new JavaCharArrayReader(unit.source.content, !settings.nouescape.value, syntaxError) init - // def warning(pos: Int, msg: String) = unit.warning(pos, msg) + def warning(pos: Int, msg: String) = unit.warning(pos, msg) def error (pos: Int, msg: String) = unit. error(pos, msg) def incompleteInputError(pos: Int, msg: String) = unit.incompleteInputError(pos, msg) def deprecationWarning(pos: Int, msg: String) = unit.deprecationWarning(pos, msg) - // implicit def p2g(pos: Position): Int = if (pos.isDefined) pos.point else -1 + implicit def p2g(pos: Position): Int = if (pos.isDefined) pos.point else -1 implicit def g2p(pos: Int): Position = new OffsetPosition(unit.source, pos) } } diff --git a/src/compiler/scala/tools/nsc/javac/JavaTokens.scala b/src/compiler/scala/tools/nsc/javac/JavaTokens.scala index 90f73ec44a..a562de291d 100644 --- a/src/compiler/scala/tools/nsc/javac/JavaTokens.scala +++ b/src/compiler/scala/tools/nsc/javac/JavaTokens.scala @@ -13,8 +13,8 @@ object JavaTokens extends ast.parser.Tokens { /** identifiers */ final val IDENTIFIER = 10 - // def isIdentifier(code : Int) = - // code == IDENTIFIER + def isIdentifier(code : Int) = + code == IDENTIFIER /** keywords */ final val ABSTRACT = 20 @@ -68,8 +68,8 @@ object JavaTokens extends ast.parser.Tokens { final val VOLATILE = 68 final val WHILE = 69 - // def isKeyword(code : Int) = - // code >= ABSTRACT && code <= WHILE + def isKeyword(code : Int) = + code >= ABSTRACT && code <= WHILE /** special symbols */ final val COMMA = 70 @@ -115,8 +115,8 @@ object JavaTokens extends ast.parser.Tokens { final val GTGTEQ = 113 final val GTGTGTEQ = 114 - // def isSymbol(code : Int) = - // code >= COMMA && code <= GTGTGTEQ + def isSymbol(code : Int) = + code >= COMMA && code <= GTGTGTEQ /** parenthesis */ final val LPAREN = 115 diff --git a/src/compiler/scala/tools/nsc/matching/MatchSupport.scala b/src/compiler/scala/tools/nsc/matching/MatchSupport.scala index 07a79a174b..5ce1aabcd8 100644 --- a/src/compiler/scala/tools/nsc/matching/MatchSupport.scala +++ b/src/compiler/scala/tools/nsc/matching/MatchSupport.scala @@ -22,8 +22,8 @@ trait MatchSupport extends ast.TreeDSL { self: ParallelMatching => def impossible: Nothing = abort("this never happens") - // def treeCollect[T](tree: Tree, pf: PartialFunction[Tree, T]): List[T] = - // tree filter (pf isDefinedAt _) map (x => pf(x)) + def treeCollect[T](tree: Tree, pf: PartialFunction[Tree, T]): List[T] = + tree filter (pf isDefinedAt _) map (x => pf(x)) object Types { import definitions._ @@ -36,24 +36,24 @@ trait MatchSupport extends ast.TreeDSL { self: ParallelMatching => // These tests for final classes can inspect the typeSymbol private def is(s: Symbol) = tpe.typeSymbol eq s - // def isByte = is(ByteClass) - // def isShort = is(ShortClass) + def isByte = is(ByteClass) + def isShort = is(ShortClass) def isInt = is(IntClass) - // def isChar = is(CharClass) - // def isBoolean = is(BooleanClass) + def isChar = is(CharClass) + def isBoolean = is(BooleanClass) def isNothing = is(NothingClass) - // def isArray = is(ArrayClass) + def isArray = is(ArrayClass) } } object Debug { - // def typeToString(t: Type): String = t match { - // case NoType => "x" - // case x => x.toString - // } - // def symbolToString(s: Symbol): String = s match { - // case x => x.toString - // } + def typeToString(t: Type): String = t match { + case NoType => "x" + case x => x.toString + } + def symbolToString(s: Symbol): String = s match { + case x => x.toString + } def treeToString(t: Tree): String = treeInfo.unbind(t) match { case EmptyTree => "?" case WILD() => "_" @@ -66,10 +66,10 @@ trait MatchSupport extends ast.TreeDSL { self: ParallelMatching => // Formatting for some error messages private val NPAD = 15 def pad(s: String): String = "%%%ds" format (NPAD-1) format s - // def pad(s: Any): String = pad(s match { - // case x: Tree => treeToString(x) - // case x => x.toString - // }) + def pad(s: Any): String = pad(s match { + case x: Tree => treeToString(x) + case x => x.toString + }) // pretty print for debugging def pp(x: Any): String = pp(x, false) @@ -117,7 +117,7 @@ trait MatchSupport extends ast.TreeDSL { self: ParallelMatching => else x } - // def indent(s: Any) = s.toString() split "\n" map (" " + _) mkString "\n" + def indent(s: Any) = s.toString() split "\n" map (" " + _) mkString "\n" def indentAll(s: Seq[Any]) = s map (" " + _.toString() + "\n") mkString } diff --git a/src/compiler/scala/tools/nsc/matching/Matrix.scala b/src/compiler/scala/tools/nsc/matching/Matrix.scala index 44387b59fb..d2f5a98411 100644 --- a/src/compiler/scala/tools/nsc/matching/Matrix.scala +++ b/src/compiler/scala/tools/nsc/matching/Matrix.scala @@ -140,7 +140,7 @@ trait Matrix extends MatrixAdditions { cases: List[CaseDef], default: Tree ) { - // def tvars = roots map (_.lhs) + def tvars = roots map (_.lhs) def valDefs = roots map (_.valDef) override def toString() = "MatrixInit(roots = %s, %d cases)".format(pp(roots), cases.size) } @@ -153,25 +153,25 @@ trait Matrix extends MatrixAdditions { def apply(xs: List[PatternVar]) = new PatternVarGroup(xs) // XXX - transitional - // def fromBindings(vlist: List[Binding], freeVars: List[Symbol] = Nil) = { - // def vmap(v: Symbol): Option[Binding] = vlist find (_.pvar eq v) - // val info = - // if (freeVars.isEmpty) vlist - // else (freeVars map vmap).flatten - - // val xs = - // for (Binding(lhs, rhs) <- info) yield - // new PatternVar(lhs, Ident(rhs) setType lhs.tpe, !(rhs hasFlag NO_EXHAUSTIVE)) - - // new PatternVarGroup(xs) - // } + def fromBindings(vlist: List[Binding], freeVars: List[Symbol] = Nil) = { + def vmap(v: Symbol): Option[Binding] = vlist find (_.pvar eq v) + val info = + if (freeVars.isEmpty) vlist + else (freeVars map vmap).flatten + + val xs = + for (Binding(lhs, rhs) <- info) yield + new PatternVar(lhs, Ident(rhs) setType lhs.tpe, !(rhs hasFlag NO_EXHAUSTIVE)) + + new PatternVarGroup(xs) + } } val emptyPatternVarGroup = PatternVarGroup() class PatternVarGroup(val pvs: List[PatternVar]) { def syms = pvs map (_.sym) def valDefs = pvs map (_.valDef) - // def idents = pvs map (_.ident) + def idents = pvs map (_.ident) def extractIndex(index: Int): (PatternVar, PatternVarGroup) = { val (t, ts) = self.extractIndex(pvs, index) @@ -180,16 +180,16 @@ trait Matrix extends MatrixAdditions { def isEmpty = pvs.isEmpty def size = pvs.size - // def head = pvs.head - // def ::(t: PatternVar) = PatternVarGroup(t :: pvs) + def head = pvs.head + def ::(t: PatternVar) = PatternVarGroup(t :: pvs) def :::(ts: List[PatternVar]) = PatternVarGroup(ts ::: pvs) - // def ++(other: PatternVarGroup) = PatternVarGroup(pvs ::: other.pvs) + def ++(other: PatternVarGroup) = PatternVarGroup(pvs ::: other.pvs) def apply(i: Int) = pvs(i) def zipWithIndex = pvs.zipWithIndex def indices = pvs.indices - // def map[T](f: PatternVar => T) = pvs map f - // def filter(p: PatternVar => Boolean) = PatternVarGroup(pvs filter p) + def map[T](f: PatternVar => T) = pvs map f + def filter(p: PatternVar => Boolean) = PatternVarGroup(pvs filter p) override def toString() = pp(pvs) } @@ -237,12 +237,12 @@ trait Matrix extends MatrixAdditions { tracing("create")(new PatternVar(lhs, rhs, checked)) } - // def createLazy(tpe: Type, f: Symbol => Tree, checked: Boolean) = { - // val lhs = newVar(owner.pos, tpe, Flags.LAZY :: flags(checked)) - // val rhs = f(lhs) + def createLazy(tpe: Type, f: Symbol => Tree, checked: Boolean) = { + val lhs = newVar(owner.pos, tpe, Flags.LAZY :: flags(checked)) + val rhs = f(lhs) - // tracing("createLazy")(new PatternVar(lhs, rhs, checked)) - // } + tracing("createLazy")(new PatternVar(lhs, rhs, checked)) + } private def newVar( pos: Position, diff --git a/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala b/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala index b5e25f3809..ea4d9cd3f4 100644 --- a/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala +++ b/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala @@ -126,7 +126,7 @@ trait ParallelMatching extends ast.TreeDSL // for propagating "unchecked" to synthetic vars def isChecked = !(sym hasFlag NO_EXHAUSTIVE) - // def flags: List[Long] = List(NO_EXHAUSTIVE) filter (sym hasFlag _) + def flags: List[Long] = List(NO_EXHAUSTIVE) filter (sym hasFlag _) // this is probably where this actually belongs def createVar(tpe: Type, f: Symbol => Tree) = context.createVar(tpe, f, isChecked) @@ -170,7 +170,7 @@ trait ParallelMatching extends ast.TreeDSL case class PatternMatch(scrut: Scrutinee, ps: List[Pattern]) { def head = ps.head def tail = ps.tail - // def size = ps.length + def size = ps.length def headType = head.necessaryType private val dummyCount = if (head.isCaseClass) headType.typeSymbol.caseFieldAccessors.length else 0 @@ -576,7 +576,7 @@ trait ParallelMatching extends ast.TreeDSL (_ys.toList, _ns.toList) } - // val moreSpecific = yeses map (_.moreSpecific) + val moreSpecific = yeses map (_.moreSpecific) val subsumed = yeses map (x => (x.bx, x.subsumed)) val remaining = noes map (x => (x.bx, x.remaining)) diff --git a/src/compiler/scala/tools/nsc/matching/PatternBindings.scala b/src/compiler/scala/tools/nsc/matching/PatternBindings.scala index 1aad24c2d6..3ff5ce83bb 100644 --- a/src/compiler/scala/tools/nsc/matching/PatternBindings.scala +++ b/src/compiler/scala/tools/nsc/matching/PatternBindings.scala @@ -61,7 +61,7 @@ trait PatternBindings extends ast.TreeDSL // This is for traversing the pattern tree - pattern types which might have // bound variables beneath them return a list of said patterns for flatMapping. - // def subpatternsForVars: List[Pattern] = Nil + def subpatternsForVars: List[Pattern] = Nil // The outermost Bind(x1, Bind(x2, ...)) surrounding the tree. private var _boundTree: Tree = tree diff --git a/src/compiler/scala/tools/nsc/matching/Patterns.scala b/src/compiler/scala/tools/nsc/matching/Patterns.scala index 9cb91afb5b..e92c43f1fd 100644 --- a/src/compiler/scala/tools/nsc/matching/Patterns.scala +++ b/src/compiler/scala/tools/nsc/matching/Patterns.scala @@ -33,7 +33,7 @@ trait Patterns extends ast.TreeDSL { def NoPattern = WildcardPattern() // The constant null pattern - // def NullPattern = LiteralPattern(NULL) + def NullPattern = LiteralPattern(NULL) // The Nil pattern def NilPattern = Pattern(gen.mkNil) @@ -60,7 +60,7 @@ trait Patterns extends ast.TreeDSL { override def covers(sym: Symbol) = newMatchesPattern(sym, tpt.tpe) override def sufficientType = tpt.tpe - // override def subpatternsForVars: List[Pattern] = List(Pattern(expr)) + override def subpatternsForVars: List[Pattern] = List(Pattern(expr)) override def simplify(pv: PatternVar) = Pattern(expr) match { case ExtractorPattern(ua) if pv.sym.tpe <:< tpt.tpe => this rebindTo expr case _ => this @@ -140,10 +140,10 @@ trait Patterns extends ast.TreeDSL { require(fn.isType && this.isCaseClass, "tree: " + tree + " fn: " + fn) def name = tpe.typeSymbol.name def cleanName = tpe.typeSymbol.decodedName - // def hasPrefix = tpe.prefix.prefixString != "" - // def prefixedName = - // if (hasPrefix) "%s.%s".format(tpe.prefix.prefixString, cleanName) - // else cleanName + def hasPrefix = tpe.prefix.prefixString != "" + def prefixedName = + if (hasPrefix) "%s.%s".format(tpe.prefix.prefixString, cleanName) + else cleanName private def isColonColon = cleanName == "::" @@ -222,15 +222,15 @@ trait Patterns extends ast.TreeDSL { // 8.1.8 (b) (literal ArrayValues) case class SequencePattern(tree: ArrayValue) extends Pattern with SequenceLikePattern { - lazy val ArrayValue(_, elems) = tree + lazy val ArrayValue(elemtpt, elems) = tree - // override def subpatternsForVars: List[Pattern] = elemPatterns + override def subpatternsForVars: List[Pattern] = elemPatterns override def description = "Seq(%s)".format(elemPatterns mkString ", ") } // 8.1.8 (c) case class StarPattern(tree: Star) extends Pattern { - // lazy val Star(_) = tree + lazy val Star(elem) = tree override def description = "_*" } // XXX temporary? @@ -389,10 +389,10 @@ trait Patterns extends ast.TreeDSL { // fn.tpe.finalResultType.typeSymbol == SomeClass override def necessaryType = arg.tpe - // override def subpatternsForVars = args match { - // case List(ArrayValue(elemtpe, elems)) => toPats(elems) - // case _ => toPats(args) - // } + override def subpatternsForVars = args match { + case List(ArrayValue(elemtpe, elems)) => toPats(elems) + case _ => toPats(args) + } def resTypes = analyzer.unapplyTypeList(unfn.symbol, unfn.tpe, args.length) def resTypesString = resTypes match { @@ -403,13 +403,13 @@ trait Patterns extends ast.TreeDSL { sealed trait ApplyPattern extends Pattern { lazy val Apply(fn, args) = tree - // override def subpatternsForVars: List[Pattern] = toPats(args) + override def subpatternsForVars: List[Pattern] = toPats(args) - // override def dummies = - // if (!this.isCaseClass) Nil - // else emptyPatterns(sufficientType.typeSymbol.caseFieldAccessors.size) + override def dummies = + if (!this.isCaseClass) Nil + else emptyPatterns(sufficientType.typeSymbol.caseFieldAccessors.size) - // def isConstructorPattern = fn.isType + def isConstructorPattern = fn.isType override def covers(sym: Symbol) = newMatchesPattern(sym, fn.tpe) } @@ -420,7 +420,7 @@ trait Patterns extends ast.TreeDSL { def simplify(pv: PatternVar): Pattern = this // the right number of dummies for this pattern - // def dummies: List[Pattern] = Nil + def dummies: List[Pattern] = Nil // Is this a default pattern (untyped "_" or an EmptyTree inserted by the matcher) def isDefault = false @@ -454,10 +454,10 @@ trait Patterns extends ast.TreeDSL { def hasStar = false - // def setType(tpe: Type): this.type = { - // tree setType tpe - // this - // } + def setType(tpe: Type): this.type = { + tree setType tpe + this + } def equalsCheck = tracing("equalsCheck")( @@ -475,7 +475,7 @@ trait Patterns extends ast.TreeDSL { final override def toString = description - // def toTypeString() = "%s <: x <: %s".format(necessaryType, sufficientType) + def toTypeString() = "%s <: x <: %s".format(necessaryType, sufficientType) def kindString = "" } diff --git a/src/compiler/scala/tools/nsc/settings/AbsSettings.scala b/src/compiler/scala/tools/nsc/settings/AbsSettings.scala index 7b77613e2a..e965370713 100644 --- a/src/compiler/scala/tools/nsc/settings/AbsSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/AbsSettings.scala @@ -47,7 +47,7 @@ trait AbsSettings extends scala.reflect.internal.settings.AbsSettings { } }) - // implicit lazy val SettingOrdering: Ordering[Setting] = Ordering.ordered + implicit lazy val SettingOrdering: Ordering[Setting] = Ordering.ordered trait AbsSetting extends Ordered[Setting] with AbsSettingValue { def name: String @@ -84,12 +84,12 @@ trait AbsSettings extends scala.reflect.internal.settings.AbsSettings { } /** If the appearance of the setting should halt argument processing. */ - // private var isTerminatorSetting = false - // def shouldStopProcessing = isTerminatorSetting - // def stopProcessing(): this.type = { - // isTerminatorSetting = true - // this - // } + private var isTerminatorSetting = false + def shouldStopProcessing = isTerminatorSetting + def stopProcessing(): this.type = { + isTerminatorSetting = true + this + } /** Issue error and return */ def errorAndValue[T](msg: String, x: T): T = { errorFn(msg) ; x } @@ -111,7 +111,7 @@ trait AbsSettings extends scala.reflect.internal.settings.AbsSettings { /** Attempt to set from a properties file style property value. * Currently used by Eclipse SDT only. */ - def tryToSetFromPropertyValue(s: String): Unit = tryToSet(s :: Nil) // used in ide? + def tryToSetFromPropertyValue(s: String): Unit = tryToSet(s :: Nil) /** These categorizations are so the help output shows -X and -P among * the standard options and -Y among the advanced options. diff --git a/src/compiler/scala/tools/nsc/settings/AdvancedScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/AdvancedScalaSettings.scala index 49b89392b9..0bec113743 100644 --- a/src/compiler/scala/tools/nsc/settings/AdvancedScalaSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/AdvancedScalaSettings.scala @@ -1,77 +1,77 @@ -// /* NSC -- new Scala compiler -// * Copyright 2005-2013 LAMP/EPFL -// * @author Paul Phillips -// */ +/* NSC -- new Scala compiler + * Copyright 2005-2013 LAMP/EPFL + * @author Paul Phillips + */ -// package scala.tools.nsc -// package settings +package scala.tools.nsc +package settings -// trait AdvancedScalaSettings { -// self: AbsScalaSettings => +trait AdvancedScalaSettings { + self: AbsScalaSettings => -// abstract class X extends SettingGroup("-X") { -// val assemextdirs: StringSetting -// val assemname: StringSetting -// val assempath: StringSetting -// val checkinit: BooleanSetting -// val disableassertions: BooleanSetting -// val elidebelow: IntSetting -// val experimental: BooleanSetting -// val future: BooleanSetting -// val generatephasegraph: StringSetting -// val logimplicits: BooleanSetting -// val mainClass: StringSetting -// val migration: BooleanSetting -// val noforwarders: BooleanSetting -// val nojline: BooleanSetting -// val nouescape: BooleanSetting -// val plugin: MultiStringSetting -// val plugindisable: MultiStringSetting -// val pluginlist: BooleanSetting -// val pluginrequire: MultiStringSetting -// val pluginsdir: StringSetting -// val print: PhasesSetting -// val printicode: BooleanSetting -// val printpos: BooleanSetting -// val printtypes: BooleanSetting -// val prompt: BooleanSetting -// val resident: BooleanSetting -// val script: StringSetting -// val showclass: StringSetting -// val showobject: StringSetting -// val showphases: BooleanSetting -// val sourcedir: StringSetting -// val sourcereader: StringSetting -// } -// // def Xexperimental = X.experimental -// // def Xmigration28 = X.migration -// // def Xnojline = X.nojline -// // def Xprint = X.print -// // def Xprintpos = X.printpos -// // def Xshowcls = X.showclass -// // def Xshowobj = X.showobject -// // def assemextdirs = X.assemextdirs -// // def assemname = X.assemname -// // def assemrefs = X.assempath -// // def checkInit = X.checkinit -// // def disable = X.plugindisable -// // def elideLevel = X.elidelevel -// // def future = X.future -// // def genPhaseGraph = X.generatephasegraph -// // def logimplicits = X.logimplicits -// // def noForwarders = X.noforwarders -// // def noassertions = X.disableassertions -// // def nouescape = X.nouescape -// // def plugin = X.plugin -// // def pluginsDir = X.pluginsdir -// // def printtypes = X.printtypes -// // def prompt = X.prompt -// // def require = X.require -// // def resident = X.resident -// // def script = X.script -// // def showPhases = X.showphases -// // def showPlugins = X.pluginlist -// // def sourceReader = X.sourcereader -// // def sourcedir = X.sourcedir -// // def writeICode = X.printicode -// } + abstract class X extends SettingGroup("-X") { + val assemextdirs: StringSetting + val assemname: StringSetting + val assempath: StringSetting + val checkinit: BooleanSetting + val disableassertions: BooleanSetting + val elidebelow: IntSetting + val experimental: BooleanSetting + val future: BooleanSetting + val generatephasegraph: StringSetting + val logimplicits: BooleanSetting + val mainClass: StringSetting + val migration: BooleanSetting + val noforwarders: BooleanSetting + val nojline: BooleanSetting + val nouescape: BooleanSetting + val plugin: MultiStringSetting + val plugindisable: MultiStringSetting + val pluginlist: BooleanSetting + val pluginrequire: MultiStringSetting + val pluginsdir: StringSetting + val print: PhasesSetting + val printicode: BooleanSetting + val printpos: BooleanSetting + val printtypes: BooleanSetting + val prompt: BooleanSetting + val resident: BooleanSetting + val script: StringSetting + val showclass: StringSetting + val showobject: StringSetting + val showphases: BooleanSetting + val sourcedir: StringSetting + val sourcereader: StringSetting + } + // def Xexperimental = X.experimental + // def Xmigration28 = X.migration + // def Xnojline = X.nojline + // def Xprint = X.print + // def Xprintpos = X.printpos + // def Xshowcls = X.showclass + // def Xshowobj = X.showobject + // def assemextdirs = X.assemextdirs + // def assemname = X.assemname + // def assemrefs = X.assempath + // def checkInit = X.checkinit + // def disable = X.plugindisable + // def elideLevel = X.elidelevel + // def future = X.future + // def genPhaseGraph = X.generatephasegraph + // def logimplicits = X.logimplicits + // def noForwarders = X.noforwarders + // def noassertions = X.disableassertions + // def nouescape = X.nouescape + // def plugin = X.plugin + // def pluginsDir = X.pluginsdir + // def printtypes = X.printtypes + // def prompt = X.prompt + // def require = X.require + // def resident = X.resident + // def script = X.script + // def showPhases = X.showphases + // def showPlugins = X.pluginlist + // def sourceReader = X.sourcereader + // def sourcedir = X.sourcedir + // def writeICode = X.printicode +} \ No newline at end of file diff --git a/src/compiler/scala/tools/nsc/settings/MutableSettings.scala b/src/compiler/scala/tools/nsc/settings/MutableSettings.scala index 748c6069f0..4f4f0544da 100644 --- a/src/compiler/scala/tools/nsc/settings/MutableSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/MutableSettings.scala @@ -176,7 +176,7 @@ class MutableSettings(val errorFn: String => Unit) * The class loader defining `T` should provide resources `app.class.path` * and `boot.class.path`. These resources should contain the application * and boot classpaths in the same form as would be passed on the command line.*/ - def embeddedDefaults[T: ClassTag]: Unit = // called from sbt and repl + def embeddedDefaults[T: ClassTag]: Unit = embeddedDefaults(classTag[T].runtimeClass.getClassLoader) /** Initializes these settings for embedded use by a class from the given class loader. @@ -239,7 +239,7 @@ class MutableSettings(val errorFn: String => Unit) /** Add a destination directory for sources found under srcdir. * Both directories should exits. */ - def add(srcDir: String, outDir: String): Unit = // used in ide? + def add(srcDir: String, outDir: String): Unit = add(checkDir(AbstractFile.getDirectory(srcDir), srcDir), checkDir(AbstractFile.getDirectory(outDir), outDir)) @@ -434,7 +434,7 @@ class MutableSettings(val errorFn: String => Unit) def tryToSet(args: List[String]) = { value = true ; Some(args) } def unparse: List[String] = if (value) List(name) else Nil - override def tryToSetFromPropertyValue(s : String) { // used from ide + override def tryToSetFromPropertyValue(s : String) { value = s.equalsIgnoreCase("true") } } @@ -527,7 +527,7 @@ class MutableSettings(val errorFn: String => Unit) Some(rest) } override def tryToSetColon(args: List[String]) = tryToSet(args) - override def tryToSetFromPropertyValue(s: String) = tryToSet(s.trim.split(',').toList) // used from ide + override def tryToSetFromPropertyValue(s: String) = tryToSet(s.trim.split(',').toList) def unparse: List[String] = value map (name + ":" + _) withHelpSyntax(name + ":<" + arg + ">") @@ -561,7 +561,7 @@ class MutableSettings(val errorFn: String => Unit) } def unparse: List[String] = if (value == default) Nil else List(name + ":" + value) - override def tryToSetFromPropertyValue(s: String) = tryToSetColon(s::Nil) // used from ide + override def tryToSetFromPropertyValue(s: String) = tryToSetColon(s::Nil) withHelpSyntax(name + ":<" + helpArg + ">") } diff --git a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala index 5074efbd01..8dce48ee9a 100644 --- a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala @@ -52,14 +52,14 @@ trait ScalaSettings extends AbsScalaSettings val jvmargs = PrefixSetting("-J", "-J", "Pass directly to the runtime system.") val defines = PrefixSetting("-Dproperty=value", "-D", "Pass -Dproperty=value directly to the runtime system.") - /*val toolcp =*/ PathSetting("-toolcp", "Add to the runner classpath.", "") + val toolcp = PathSetting("-toolcp", "Add to the runner classpath.", "") val nobootcp = BooleanSetting("-nobootcp", "Do not use the boot classpath for the scala jars.") /** * Standard settings */ // argfiles is only for the help message - /*val argfiles = */ BooleanSetting ("@", "A text file containing compiler arguments (options and source files)") + val argfiles = BooleanSetting ("@", "A text file containing compiler arguments (options and source files)") val classpath = PathSetting ("-classpath", "Specify where to find user class files.", defaultClasspath) withAbbreviation "-cp" val d = OutputSetting (outputDirs, ".") val nospecialization = BooleanSetting ("-no-specialization", "Ignore @specialize annotations.") @@ -114,7 +114,7 @@ trait ScalaSettings extends AbsScalaSettings /** Compatibility stubs for options whose value name did * not previously match the option name. */ - // def XO = optimise + def XO = optimise def debuginfo = g def dependenciesFile = dependencyfile def nowarnings = nowarn @@ -180,12 +180,12 @@ trait ScalaSettings extends AbsScalaSettings val exposeEmptyPackage = BooleanSetting("-Yexpose-empty-package", "Internal only: expose the empty package.").internalOnly() - // def stop = stopAfter + def stop = stopAfter /** Area-specific debug output. */ val Ybuildmanagerdebug = BooleanSetting("-Ybuild-manager-debug", "Generate debug information for the Refined Build Manager compiler.") - // val Ycompletion = BooleanSetting("-Ycompletion-debug", "Trace all tab completion activity.") + val Ycompletion = BooleanSetting("-Ycompletion-debug", "Trace all tab completion activity.") val Ydocdebug = BooleanSetting("-Ydoc-debug", "Trace all scaladoc activity.") val Yidedebug = BooleanSetting("-Yide-debug", "Generate, validate and output trees using the interactive compiler.") val Yinferdebug = BooleanSetting("-Yinfer-debug", "Trace type inference and implicit search.") diff --git a/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala index 53d3557c67..e866ad6ae0 100644 --- a/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala @@ -52,5 +52,5 @@ trait StandardScalaSettings { /** These are @ and -Dkey=val style settings, which don't * nicely map to identifiers. */ - // val argfiles: BooleanSetting // exists only to echo help message, should be done differently + val argfiles: BooleanSetting // exists only to echo help message, should be done differently } diff --git a/src/compiler/scala/tools/nsc/settings/Warnings.scala b/src/compiler/scala/tools/nsc/settings/Warnings.scala index d678fc60a8..d6d77278ab 100644 --- a/src/compiler/scala/tools/nsc/settings/Warnings.scala +++ b/src/compiler/scala/tools/nsc/settings/Warnings.scala @@ -39,13 +39,9 @@ trait Warnings { BooleanSetting("-Xlint", "Enable recommended additional warnings.") withPostSetHook (_ => lintWarnings foreach (_.value = true)) ) - - /*val warnEverything = */ ( + val warnEverything = ( BooleanSetting("-Ywarn-all", "Enable all -Y warnings.") - withPostSetHook { _ => - lint.value = true - allWarnings foreach (_.value = true) - } + withPostSetHook (_ => lintWarnings foreach (_.value = true)) ) // Individual warnings. @@ -61,7 +57,7 @@ trait Warnings { val warnInferAny = BooleanSetting ("-Ywarn-infer-any", "Warn when a type argument is inferred to be `Any`.") // Backward compatibility. - def Xwarnfatal = fatalWarnings // used by sbt - // def Xchecknull = warnSelectNullable - // def Ywarndeadcode = warnDeadCode + def Xwarnfatal = fatalWarnings + def Xchecknull = warnSelectNullable + def Ywarndeadcode = warnDeadCode } diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/AbstractFileReader.scala b/src/compiler/scala/tools/nsc/symtab/classfile/AbstractFileReader.scala index 2d44d1e5f1..427b5bf887 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/AbstractFileReader.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/AbstractFileReader.scala @@ -31,8 +31,8 @@ class AbstractFileReader(val file: AbstractFile) { /** return byte at offset 'pos' */ - // @throws(classOf[IndexOutOfBoundsException]) - // def byteAt(pos: Int): Byte = buf(pos) + @throws(classOf[IndexOutOfBoundsException]) + def byteAt(pos: Int): Byte = buf(pos) /** read a byte */ @@ -45,10 +45,10 @@ class AbstractFileReader(val file: AbstractFile) { /** read some bytes */ - // def nextBytes(len: Int): Array[Byte] = { - // bp += len - // buf.slice(bp - len, bp) - // } + def nextBytes(len: Int): Array[Byte] = { + bp += len + buf.slice(bp - len, bp) + } /** read a character */ diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala index 50a455b33f..67f6c3ec5d 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala @@ -1172,16 +1172,16 @@ abstract class ClassfileParser { /** Return the Symbol of the top level class enclosing `name`, * or 'name's symbol if no entry found for `name`. */ - // def topLevelClass(name: Name): Symbol = { - // val tlName = if (isDefinedAt(name)) { - // var entry = this(name) - // while (isDefinedAt(entry.outerName)) - // entry = this(entry.outerName) - // entry.outerName - // } else - // name - // classNameToSymbol(tlName) - // } + def topLevelClass(name: Name): Symbol = { + val tlName = if (isDefinedAt(name)) { + var entry = this(name) + while (isDefinedAt(entry.outerName)) + entry = this(entry.outerName) + entry.outerName + } else + name + classNameToSymbol(tlName) + } /** Return the class symbol for `externalName`. It looks it up in its outer class. * Forces all outer class symbols to be completed. diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala index b5459ec773..b7511377cc 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala @@ -632,9 +632,9 @@ abstract class ICodeReader extends ClassfileParser { else instanceCode class LinearCode { - val instrs: ListBuffer[(Int, Instruction)] = new ListBuffer - val jmpTargets: mutable.Set[Int] = perRunCaches.newSet[Int]() - val locals: mutable.Map[Int, List[(Local, TypeKind)]] = perRunCaches.newMap() + var instrs: ListBuffer[(Int, Instruction)] = new ListBuffer + var jmpTargets: mutable.Set[Int] = perRunCaches.newSet[Int]() + var locals: mutable.Map[Int, List[(Local, TypeKind)]] = perRunCaches.newMap() var containsDUPX = false var containsNEW = false diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala index 324d62b662..941604b154 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala @@ -1002,110 +1002,110 @@ abstract class Pickler extends SubComponent { } /** Print entry for diagnostics */ - // def printEntryAtIndex(idx: Int) = printEntry(entries(idx)) - // def printEntry(entry: AnyRef) { - // def printRef(ref: AnyRef) { - // print(index(ref)+ - // (if (ref.isInstanceOf[Name]) "("+ref+") " else " ")) - // } - // def printRefs(refs: List[AnyRef]) { refs foreach printRef } - // def printSymInfo(sym: Symbol) { - // printRef(sym.name) - // printRef(localizedOwner(sym)) - // print(flagsToString(sym.flags & PickledFlags)+" ") - // if (sym.hasAccessBoundary) printRef(sym.privateWithin) - // printRef(sym.info) - // } - // def printBody(entry: AnyRef) = entry match { - // case name: Name => - // print((if (name.isTermName) "TERMname " else "TYPEname ")+name) - // case NoSymbol => - // print("NONEsym") - // case sym: Symbol if !isLocal(sym) => - // if (sym.isModuleClass) { - // print("EXTMODCLASSref "); printRef(sym.name.toTermName) - // } else { - // print("EXTref "); printRef(sym.name) - // } - // if (!sym.owner.isRoot) printRef(sym.owner) - // case sym: ClassSymbol => - // print("CLASSsym ") - // printSymInfo(sym) - // if (sym.thisSym.tpe != sym.tpe) printRef(sym.typeOfThis) - // case sym: TypeSymbol => - // print(if (sym.isAbstractType) "TYPEsym " else "ALIASsym ") - // printSymInfo(sym) - // case sym: TermSymbol => - // print(if (sym.isModule) "MODULEsym " else "VALsym ") - // printSymInfo(sym) - // if (sym.alias != NoSymbol) printRef(sym.alias) - // case NoType => - // print("NOtpe") - // case NoPrefix => - // print("NOPREFIXtpe") - // case ThisType(sym) => - // print("THIStpe "); printRef(sym) - // case SingleType(pre, sym) => - // print("SINGLEtpe "); printRef(pre); printRef(sym); - // case ConstantType(value) => - // print("CONSTANTtpe "); printRef(value); - // case TypeRef(pre, sym, args) => - // print("TYPEREFtpe "); printRef(pre); printRef(sym); printRefs(args); - // case TypeBounds(lo, hi) => - // print("TYPEBOUNDStpe "); printRef(lo); printRef(hi); - // case tp @ RefinedType(parents, decls) => - // print("REFINEDtpe "); printRef(tp.typeSymbol); printRefs(parents); - // case ClassInfoType(parents, decls, clazz) => - // print("CLASSINFOtpe "); printRef(clazz); printRefs(parents); - // case mt @ MethodType(formals, restpe) => - // print("METHODtpe"); printRef(restpe); printRefs(formals) - // case PolyType(tparams, restpe) => - // print("POLYtpe "); printRef(restpe); printRefs(tparams); - // case ExistentialType(tparams, restpe) => - // print("EXISTENTIALtpe "); printRef(restpe); printRefs(tparams); - // print("||| "+entry) - // case c @ Constant(_) => - // print("LITERAL ") - // if (c.tag == BooleanTag) print("Boolean "+(if (c.booleanValue) 1 else 0)) - // else if (c.tag == ByteTag) print("Byte "+c.longValue) - // else if (c.tag == ShortTag) print("Short "+c.longValue) - // else if (c.tag == CharTag) print("Char "+c.longValue) - // else if (c.tag == IntTag) print("Int "+c.longValue) - // else if (c.tag == LongTag) print("Long "+c.longValue) - // else if (c.tag == FloatTag) print("Float "+c.floatValue) - // else if (c.tag == DoubleTag) print("Double "+c.doubleValue) - // else if (c.tag == StringTag) { print("String "); printRef(newTermName(c.stringValue)) } - // else if (c.tag == ClazzTag) { print("Class "); printRef(c.typeValue) } - // else if (c.tag == EnumTag) { print("Enum "); printRef(c.symbolValue) } - // case AnnotatedType(annots, tp, selfsym) => - // if (settings.selfInAnnots.value) { - // print("ANNOTATEDWSELFtpe ") - // printRef(tp) - // printRef(selfsym) - // printRefs(annots) - // } else { - // print("ANNOTATEDtpe ") - // printRef(tp) - // printRefs(annots) - // } - // case (target: Symbol, AnnotationInfo(atp, args, Nil)) => - // print("SYMANNOT ") - // printRef(target) - // printRef(atp) - // for (c <- args) printRef(c) - // case (target: Symbol, children: List[_]) => - // print("CHILDREN ") - // printRef(target) - // for (c <- children) printRef(c.asInstanceOf[Symbol]) - // case AnnotationInfo(atp, args, Nil) => - // print("ANNOTINFO") - // printRef(atp) - // for (c <- args) printRef(c) - // case _ => - // throw new FatalError("bad entry: " + entry + " " + entry.getClass) - // } - // printBody(entry); println() - // } + def printEntryAtIndex(idx: Int) = printEntry(entries(idx)) + def printEntry(entry: AnyRef) { + def printRef(ref: AnyRef) { + print(index(ref)+ + (if (ref.isInstanceOf[Name]) "("+ref+") " else " ")) + } + def printRefs(refs: List[AnyRef]) { refs foreach printRef } + def printSymInfo(sym: Symbol) { + printRef(sym.name) + printRef(localizedOwner(sym)) + print(flagsToString(sym.flags & PickledFlags)+" ") + if (sym.hasAccessBoundary) printRef(sym.privateWithin) + printRef(sym.info) + } + def printBody(entry: AnyRef) = entry match { + case name: Name => + print((if (name.isTermName) "TERMname " else "TYPEname ")+name) + case NoSymbol => + print("NONEsym") + case sym: Symbol if !isLocal(sym) => + if (sym.isModuleClass) { + print("EXTMODCLASSref "); printRef(sym.name.toTermName) + } else { + print("EXTref "); printRef(sym.name) + } + if (!sym.owner.isRoot) printRef(sym.owner) + case sym: ClassSymbol => + print("CLASSsym ") + printSymInfo(sym) + if (sym.thisSym.tpe != sym.tpe) printRef(sym.typeOfThis) + case sym: TypeSymbol => + print(if (sym.isAbstractType) "TYPEsym " else "ALIASsym ") + printSymInfo(sym) + case sym: TermSymbol => + print(if (sym.isModule) "MODULEsym " else "VALsym ") + printSymInfo(sym) + if (sym.alias != NoSymbol) printRef(sym.alias) + case NoType => + print("NOtpe") + case NoPrefix => + print("NOPREFIXtpe") + case ThisType(sym) => + print("THIStpe "); printRef(sym) + case SingleType(pre, sym) => + print("SINGLEtpe "); printRef(pre); printRef(sym); + case ConstantType(value) => + print("CONSTANTtpe "); printRef(value); + case TypeRef(pre, sym, args) => + print("TYPEREFtpe "); printRef(pre); printRef(sym); printRefs(args); + case TypeBounds(lo, hi) => + print("TYPEBOUNDStpe "); printRef(lo); printRef(hi); + case tp @ RefinedType(parents, decls) => + print("REFINEDtpe "); printRef(tp.typeSymbol); printRefs(parents); + case ClassInfoType(parents, decls, clazz) => + print("CLASSINFOtpe "); printRef(clazz); printRefs(parents); + case mt @ MethodType(formals, restpe) => + print("METHODtpe"); printRef(restpe); printRefs(formals) + case PolyType(tparams, restpe) => + print("POLYtpe "); printRef(restpe); printRefs(tparams); + case ExistentialType(tparams, restpe) => + print("EXISTENTIALtpe "); printRef(restpe); printRefs(tparams); + print("||| "+entry) + case c @ Constant(_) => + print("LITERAL ") + if (c.tag == BooleanTag) print("Boolean "+(if (c.booleanValue) 1 else 0)) + else if (c.tag == ByteTag) print("Byte "+c.longValue) + else if (c.tag == ShortTag) print("Short "+c.longValue) + else if (c.tag == CharTag) print("Char "+c.longValue) + else if (c.tag == IntTag) print("Int "+c.longValue) + else if (c.tag == LongTag) print("Long "+c.longValue) + else if (c.tag == FloatTag) print("Float "+c.floatValue) + else if (c.tag == DoubleTag) print("Double "+c.doubleValue) + else if (c.tag == StringTag) { print("String "); printRef(newTermName(c.stringValue)) } + else if (c.tag == ClazzTag) { print("Class "); printRef(c.typeValue) } + else if (c.tag == EnumTag) { print("Enum "); printRef(c.symbolValue) } + case AnnotatedType(annots, tp, selfsym) => + if (settings.selfInAnnots.value) { + print("ANNOTATEDWSELFtpe ") + printRef(tp) + printRef(selfsym) + printRefs(annots) + } else { + print("ANNOTATEDtpe ") + printRef(tp) + printRefs(annots) + } + case (target: Symbol, AnnotationInfo(atp, args, Nil)) => + print("SYMANNOT ") + printRef(target) + printRef(atp) + for (c <- args) printRef(c) + case (target: Symbol, children: List[_]) => + print("CHILDREN ") + printRef(target) + for (c <- children) printRef(c.asInstanceOf[Symbol]) + case AnnotationInfo(atp, args, Nil) => + print("ANNOTINFO") + printRef(atp) + for (c <- args) printRef(c) + case _ => + throw new FatalError("bad entry: " + entry + " " + entry.getClass) + } + printBody(entry); println() + } /** Write byte array */ def writeArray() { diff --git a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala index 0fe72c992e..78fb725041 100644 --- a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala +++ b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala @@ -187,9 +187,9 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { /** Returns the generic class that was specialized to 'sClass', or * 'sClass' itself if sClass is not a specialized subclass. */ - // def genericClass(sClass: Symbol): Symbol = - // if (sClass.isSpecialized) sClass.superClass - // else sClass + def genericClass(sClass: Symbol): Symbol = + if (sClass.isSpecialized) sClass.superClass + else sClass case class Overload(sym: Symbol, env: TypeEnv) { override def toString = "specialized overload " + sym + " in " + env @@ -223,7 +223,7 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { */ def degenerate = false - // def isAccessor = false + def isAccessor = false } /** Symbol is a special overloaded method of 'original', in the environment env. */ @@ -248,7 +248,7 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { /** Symbol is a specialized accessor for the `target` field. */ case class SpecializedAccessor(target: Symbol) extends SpecializedInfo { - // override def isAccessor = true + override def isAccessor = true } /** Symbol is a specialized method whose body should be the target's method body. */ @@ -288,8 +288,8 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { def specializedParams(sym: Symbol): List[Symbol] = sym.info.typeParams filter (_.isSpecialized) - // def splitParams(tps: List[Symbol]) = - // tps partition (_.isSpecialized) + def splitParams(tps: List[Symbol]) = + tps partition (_.isSpecialized) /** Given an original class symbol and a list of types its type parameters are instantiated at * returns a list of type parameters that should remain in the TypeRef when instantiating a @@ -1185,7 +1185,7 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { * * A conflicting type environment could still be satisfiable. */ - // def conflicting(env: TypeEnv) = !nonConflicting(env) + def conflicting(env: TypeEnv) = !nonConflicting(env) def nonConflicting(env: TypeEnv) = env forall { case (tvar, tpe) => (subst(env, tvar.info.bounds.lo) <:< tpe) && (tpe <:< subst(env, tvar.info.bounds.hi)) } @@ -1866,10 +1866,10 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { } } - // def printSpecStats() { - // println(" concreteSpecMembers: %7d".format(concreteSpecMethods.size)) - // println(" overloads: %7d".format(overloads.size)) - // println(" typeEnv: %7d".format(typeEnv.size)) - // println(" info: %7d".format(info.size)) - // } + def printSpecStats() { + println(" concreteSpecMembers: %7d".format(concreteSpecMethods.size)) + println(" overloads: %7d".format(overloads.size)) + println(" typeEnv: %7d".format(typeEnv.size)) + println(" info: %7d".format(info.size)) + } } diff --git a/src/compiler/scala/tools/nsc/transform/TailCalls.scala b/src/compiler/scala/tools/nsc/transform/TailCalls.scala index 798e604be4..2e0cc3bd98 100644 --- a/src/compiler/scala/tools/nsc/transform/TailCalls.scala +++ b/src/compiler/scala/tools/nsc/transform/TailCalls.scala @@ -147,7 +147,7 @@ abstract class TailCalls extends Transform { } def enclosingType = method.enclClass.typeOfThis - // def methodTypeParams = method.tpe.typeParams + def methodTypeParams = method.tpe.typeParams def isEligible = method.isEffectivelyFinal // @tailrec annotation indicates mandatory transformation def isMandatory = method.hasAnnotation(TailrecClass) && !forMSIL diff --git a/src/compiler/scala/tools/nsc/transform/TypingTransformers.scala b/src/compiler/scala/tools/nsc/transform/TypingTransformers.scala index f0414b8639..b7da0e0087 100644 --- a/src/compiler/scala/tools/nsc/transform/TypingTransformers.scala +++ b/src/compiler/scala/tools/nsc/transform/TypingTransformers.scala @@ -21,7 +21,7 @@ trait TypingTransformers { else analyzer.newTyper(analyzer.rootContext(unit, EmptyTree, true)) protected var curTree: Tree = _ - // protected def typedPos(pos: Position)(tree: Tree) = localTyper typed { atPos(pos)(tree) } + protected def typedPos(pos: Position)(tree: Tree) = localTyper typed { atPos(pos)(tree) } override final def atOwner[A](owner: Symbol)(trans: => A): A = atOwner(curTree, owner)(trans) diff --git a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala index 9ea1ff4263..a8d7de6362 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala @@ -219,7 +219,7 @@ trait Contexts { self: Analyzer => current } - // def logError(err: AbsTypeError) = buffer += err + def logError(err: AbsTypeError) = buffer += err def withImplicitsEnabled[T](op: => T): T = { val saved = implicitsEnabled @@ -313,13 +313,13 @@ trait Contexts { self: Analyzer => } // TODO: remove? Doesn't seem to be used - // def make(unit: CompilationUnit): Context = { - // val c = make(unit, EmptyTree, owner, scope, imports) - // c.setReportErrors() - // c.implicitsEnabled = true - // c.macrosEnabled = true - // c - // } + def make(unit: CompilationUnit): Context = { + val c = make(unit, EmptyTree, owner, scope, imports) + c.setReportErrors() + c.implicitsEnabled = true + c.macrosEnabled = true + c + } def makeNewImport(sym: Symbol): Context = makeNewImport(gen.mkWildcardImport(sym)) @@ -491,14 +491,14 @@ trait Contexts { self: Analyzer => /** Return closest enclosing context that defines a superclass of `clazz`, or a * companion module of a superclass of `clazz`, or NoContext if none exists */ - // def enclosingSuperClassContext(clazz: Symbol): Context = { - // var c = this.enclClass - // while (c != NoContext && - // !clazz.isNonBottomSubClass(c.owner) && - // !(c.owner.isModuleClass && clazz.isNonBottomSubClass(c.owner.companionClass))) - // c = c.outer.enclClass - // c - // } + def enclosingSuperClassContext(clazz: Symbol): Context = { + var c = this.enclClass + while (c != NoContext && + !clazz.isNonBottomSubClass(c.owner) && + !(c.owner.isModuleClass && clazz.isNonBottomSubClass(c.owner.companionClass))) + c = c.outer.enclClass + c + } /** Return the closest enclosing context that defines a subclass of `clazz` * or a companion object thereof, or `NoContext` if no such context exists. diff --git a/src/compiler/scala/tools/nsc/typechecker/DestructureTypes.scala b/src/compiler/scala/tools/nsc/typechecker/DestructureTypes.scala index 856043bca9..79cd46e018 100644 --- a/src/compiler/scala/tools/nsc/typechecker/DestructureTypes.scala +++ b/src/compiler/scala/tools/nsc/typechecker/DestructureTypes.scala @@ -64,15 +64,15 @@ trait DestructureTypes { }, tree.productPrefix ) - // def wrapSymbol(label: String, sym: Symbol): Node = { - // if (sym eq NoSymbol) wrapEmpty - // else atom(label, sym) - // } - // def wrapInfo(sym: Symbol) = sym.info match { - // case TypeBounds(lo, hi) => typeBounds(lo, hi) - // case PolyType(tparams, restpe) => polyFunction(tparams, restpe) - // case _ => wrapEmpty - // } + def wrapSymbol(label: String, sym: Symbol): Node = { + if (sym eq NoSymbol) wrapEmpty + else atom(label, sym) + } + def wrapInfo(sym: Symbol) = sym.info match { + case TypeBounds(lo, hi) => typeBounds(lo, hi) + case PolyType(tparams, restpe) => polyFunction(tparams, restpe) + case _ => wrapEmpty + } def wrapSymbolInfo(sym: Symbol): Node = { if ((sym eq NoSymbol) || openSymbols(sym)) wrapEmpty else { @@ -95,7 +95,7 @@ trait DestructureTypes { def constant(label: String, const: Constant): Node = atom(label, const) def scope(decls: Scope): Node = node("decls", scopeMemberList(decls.toList)) - // def const[T](named: (String, T)): Node = constant(named._1, Constant(named._2)) + def const[T](named: (String, T)): Node = constant(named._1, Constant(named._2)) def resultType(restpe: Type): Node = this("resultType", restpe) def typeParams(tps: List[Symbol]): Node = node("typeParams", symbolList(tps)) diff --git a/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala b/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala index e5e52e91c3..7d58155eb2 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala @@ -19,10 +19,10 @@ abstract class Duplicators extends Analyzer { import global._ import definitions.{ AnyRefClass, AnyValClass } - // def retyped(context: Context, tree: Tree): Tree = { - // resetClassOwners - // (newBodyDuplicator(context)).typed(tree) - // } + def retyped(context: Context, tree: Tree): Tree = { + resetClassOwners + (newBodyDuplicator(context)).typed(tree) + } /** Retype the given tree in the given context. Use this method when retyping * a method in a different class. The typer will replace references to the this of @@ -42,8 +42,8 @@ abstract class Duplicators extends Analyzer { protected def newBodyDuplicator(context: Context) = new BodyDuplicator(context) - // def retypedMethod(context: Context, tree: Tree, oldThis: Symbol, newThis: Symbol): Tree = - // (newBodyDuplicator(context)).retypedMethod(tree.asInstanceOf[DefDef], oldThis, newThis) + def retypedMethod(context: Context, tree: Tree, oldThis: Symbol, newThis: Symbol): Tree = + (newBodyDuplicator(context)).retypedMethod(tree.asInstanceOf[DefDef], oldThis, newThis) /** Return the special typer for duplicate method bodies. */ override def newTyper(context: Context): Typer = @@ -186,19 +186,19 @@ abstract class Duplicators extends Analyzer { stats.foreach(invalidate(_, owner)) } - // def retypedMethod(ddef: DefDef, oldThis: Symbol, newThis: Symbol): Tree = { - // oldClassOwner = oldThis - // newClassOwner = newThis - // invalidateAll(ddef.tparams) - // mforeach(ddef.vparamss) { vdef => - // invalidate(vdef) - // vdef.tpe = null - // } - // ddef.symbol = NoSymbol - // enterSym(context, ddef) - // debuglog("remapping this of " + oldClassOwner + " to " + newClassOwner) - // typed(ddef) - // } + def retypedMethod(ddef: DefDef, oldThis: Symbol, newThis: Symbol): Tree = { + oldClassOwner = oldThis + newClassOwner = newThis + invalidateAll(ddef.tparams) + mforeach(ddef.vparamss) { vdef => + invalidate(vdef) + vdef.tpe = null + } + ddef.symbol = NoSymbol + enterSym(context, ddef) + debuglog("remapping this of " + oldClassOwner + " to " + newClassOwner) + typed(ddef) + } /** Optionally cast this tree into some other type, if required. * Unless overridden, just returns the tree. diff --git a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala index c17586335c..576a21fe31 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala @@ -233,10 +233,10 @@ trait Implicits { object HasMember { private val hasMemberCache = perRunCaches.newMap[Name, Type]() def apply(name: Name): Type = hasMemberCache.getOrElseUpdate(name, memberWildcardType(name, WildcardType)) - // def unapply(pt: Type): Option[Name] = pt match { - // case RefinedType(List(WildcardType), Scope(sym)) if sym.tpe == WildcardType => Some(sym.name) - // case _ => None - // } + def unapply(pt: Type): Option[Name] = pt match { + case RefinedType(List(WildcardType), Scope(sym)) if sym.tpe == WildcardType => Some(sym.name) + case _ => None + } } /** An extractor for types of the form ? { name: (? >: argtpe <: Any*)restp } @@ -1493,9 +1493,9 @@ object ImplicitsStats { val subtypeImpl = Statistics.newSubCounter(" of which in implicit", subtypeCount) val findMemberImpl = Statistics.newSubCounter(" of which in implicit", findMemberCount) val subtypeAppInfos = Statistics.newSubCounter(" of which in app impl", subtypeCount) - // val subtypeImprovCount = Statistics.newSubCounter(" of which in improves", subtypeCount) + val subtypeImprovCount = Statistics.newSubCounter(" of which in improves", subtypeCount) val implicitSearchCount = Statistics.newCounter ("#implicit searches", "typer") - // val triedImplicits = Statistics.newSubCounter(" #tried", implicitSearchCount) + val triedImplicits = Statistics.newSubCounter(" #tried", implicitSearchCount) val plausiblyCompatibleImplicits = Statistics.newSubCounter(" #plausibly compatible", implicitSearchCount) val matchingImplicits = Statistics.newSubCounter(" #matching", implicitSearchCount) diff --git a/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala b/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala index bd37f055b7..6aafd32237 100644 --- a/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala +++ b/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala @@ -29,43 +29,43 @@ trait MethodSynthesis { if (sym.isLazy) ValDef(sym, body) else DefDef(sym, body) - // def applyTypeInternal(tags: List[TT[_]]): Type = { - // val symbols = tags map compilerSymbolFromTag - // val container :: args = symbols - // val tparams = container.typeConstructor.typeParams + def applyTypeInternal(tags: List[TT[_]]): Type = { + val symbols = tags map compilerSymbolFromTag + val container :: args = symbols + val tparams = container.typeConstructor.typeParams - // // Conservative at present - if manifests were more usable this could do a lot more. - // // [Eugene to Paul] all right, they are now. what do you have in mind? - // require(symbols forall (_ ne NoSymbol), "Must find all tags: " + symbols) - // require(container.owner.isPackageClass, "Container must be a top-level class in a package: " + container) - // require(tparams.size == args.size, "Arguments must match type constructor arity: " + tparams + ", " + args) + // Conservative at present - if manifests were more usable this could do a lot more. + // [Eugene to Paul] all right, they are now. what do you have in mind? + require(symbols forall (_ ne NoSymbol), "Must find all tags: " + symbols) + require(container.owner.isPackageClass, "Container must be a top-level class in a package: " + container) + require(tparams.size == args.size, "Arguments must match type constructor arity: " + tparams + ", " + args) - // appliedType(container, args map (_.tpe): _*) - // } + appliedType(container, args map (_.tpe): _*) + } - // def companionType[T](implicit ct: CT[T]) = - // rootMirror.getRequiredModule(ct.runtimeClass.getName).tpe + def companionType[T](implicit ct: CT[T]) = + rootMirror.getRequiredModule(ct.runtimeClass.getName).tpe // Use these like `applyType[List, Int]` or `applyType[Map, Int, String]` - // def applyType[CC](implicit t1: TT[CC]): Type = - // applyTypeInternal(List(t1)) + def applyType[CC](implicit t1: TT[CC]): Type = + applyTypeInternal(List(t1)) - // def applyType[CC[X1], X1](implicit t1: TT[CC[_]], t2: TT[X1]): Type = - // applyTypeInternal(List(t1, t2)) + def applyType[CC[X1], X1](implicit t1: TT[CC[_]], t2: TT[X1]): Type = + applyTypeInternal(List(t1, t2)) - // def applyType[CC[X1, X2], X1, X2](implicit t1: TT[CC[_,_]], t2: TT[X1], t3: TT[X2]): Type = - // applyTypeInternal(List(t1, t2, t3)) + def applyType[CC[X1, X2], X1, X2](implicit t1: TT[CC[_,_]], t2: TT[X1], t3: TT[X2]): Type = + applyTypeInternal(List(t1, t2, t3)) - // def applyType[CC[X1, X2, X3], X1, X2, X3](implicit t1: TT[CC[_,_,_]], t2: TT[X1], t3: TT[X2], t4: TT[X3]): Type = - // applyTypeInternal(List(t1, t2, t3, t4)) + def applyType[CC[X1, X2, X3], X1, X2, X3](implicit t1: TT[CC[_,_,_]], t2: TT[X1], t3: TT[X2], t4: TT[X3]): Type = + applyTypeInternal(List(t1, t2, t3, t4)) - // def newMethodType[F](owner: Symbol)(implicit t: TT[F]): Type = { - // val fnSymbol = compilerSymbolFromTag(t) - // val formals = compilerTypeFromTag(t).typeArguments - // assert(fnSymbol isSubClass FunctionClass(formals.size - 1), (owner, t)) - // val params = owner newSyntheticValueParams formals - // MethodType(params, formals.last) - // } + def newMethodType[F](owner: Symbol)(implicit t: TT[F]): Type = { + val fnSymbol = compilerSymbolFromTag(t) + val formals = compilerTypeFromTag(t).typeArguments + assert(fnSymbol isSubClass FunctionClass(formals.size - 1), (owner, t)) + val params = owner newSyntheticValueParams formals + MethodType(params, formals.last) + } /** The annotations amongst those found on the original symbol which * should be propagated to this kind of accessor. @@ -118,8 +118,8 @@ trait MethodSynthesis { finishMethod(clazz.info.decls enter m, f) } - // private def cloneInternal(original: Symbol, f: Symbol => Tree): Tree = - // cloneInternal(original, f, original.name) + private def cloneInternal(original: Symbol, f: Symbol => Tree): Tree = + cloneInternal(original, f, original.name) def clazzMember(name: Name) = clazz.info nonPrivateMember name def typeInClazz(sym: Symbol) = clazz.thisType memberType sym @@ -128,11 +128,11 @@ trait MethodSynthesis { * the same type as `name` in clazz, and returns the tree to be * added to the template. */ - // def overrideMethod(name: Name)(f: Symbol => Tree): Tree = - // overrideMethod(clazzMember(name))(f) + def overrideMethod(name: Name)(f: Symbol => Tree): Tree = + overrideMethod(clazzMember(name))(f) - // def overrideMethod(original: Symbol)(f: Symbol => Tree): Tree = - // cloneInternal(original, sym => f(sym setFlag OVERRIDE)) + def overrideMethod(original: Symbol)(f: Symbol => Tree): Tree = + cloneInternal(original, sym => f(sym setFlag OVERRIDE)) def deriveMethod(original: Symbol, nameFn: Name => Name)(f: Symbol => Tree): Tree = cloneInternal(original, f, nameFn(original.name)) @@ -311,7 +311,7 @@ trait MethodSynthesis { // Final methods to make the rest easier to reason about. final def mods = tree.mods final def basisSym = tree.symbol - // final def derivedFlags: Long = basisSym.flags & flagsMask | flagsExtra + final def derivedFlags: Long = basisSym.flags & flagsMask | flagsExtra } trait DerivedFromClassDef extends DerivedFromMemberDef { diff --git a/src/compiler/scala/tools/nsc/typechecker/Namers.scala b/src/compiler/scala/tools/nsc/typechecker/Namers.scala index 407749f833..28bed0f1bf 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Namers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Namers.scala @@ -1388,11 +1388,11 @@ trait Namers extends MethodSynthesis { tpe } - // def ensureParent(clazz: Symbol, parent: Symbol) = { - // val info0 = clazz.info - // val info1 = includeParent(info0, parent) - // if (info0 ne info1) clazz setInfo info1 - // } + def ensureParent(clazz: Symbol, parent: Symbol) = { + val info0 = clazz.info + val info1 = includeParent(info0, parent) + if (info0 ne info1) clazz setInfo info1 + } class LogTransitions[S](onEnter: S => String, onExit: S => String) { val enabled = settings.debug.value @@ -1585,12 +1585,12 @@ trait Namers extends MethodSynthesis { } } - // @deprecated("Use underlyingSymbol instead", "2.10.0") - // def underlying(member: Symbol): Symbol = underlyingSymbol(member) - // @deprecated("Use `companionSymbolOf` instead", "2.10.0") - // def companionClassOf(module: Symbol, ctx: Context): Symbol = companionSymbolOf(module, ctx) - // @deprecated("Use `companionSymbolOf` instead", "2.10.0") - // def companionModuleOf(clazz: Symbol, ctx: Context): Symbol = companionSymbolOf(clazz, ctx) + @deprecated("Use underlyingSymbol instead", "2.10.0") + def underlying(member: Symbol): Symbol = underlyingSymbol(member) + @deprecated("Use `companionSymbolOf` instead", "2.10.0") + def companionClassOf(module: Symbol, ctx: Context): Symbol = companionSymbolOf(module, ctx) + @deprecated("Use `companionSymbolOf` instead", "2.10.0") + def companionModuleOf(clazz: Symbol, ctx: Context): Symbol = companionSymbolOf(clazz, ctx) /** The companion class or companion module of `original`. * Calling .companionModule does not work for classes defined inside methods. diff --git a/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala b/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala index 1588380bca..252a738755 100644 --- a/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala +++ b/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala @@ -41,7 +41,7 @@ trait NamesDefaults { self: Analyzer => blockTyper: Typer ) { } - // val noApplyInfo = NamedApplyInfo(None, Nil, Nil, null) + val noApplyInfo = NamedApplyInfo(None, Nil, Nil, null) def nameOf(arg: Tree) = arg match { case AssignOrNamedArg(Ident(name), rhs) => Some(name) diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala index 27e539abbf..7cb420d2dc 100644 --- a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala +++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala @@ -551,50 +551,50 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL // NOTE: it's an apply, not a select, since in general an extractor call may have multiple argument lists (including an implicit one) // that we need to preserve, so we supply the scrutinee as Ident(nme.SELECTOR_DUMMY), // and replace that dummy by a reference to the actual binder in translateExtractorPattern - // def fromCaseClassUnapply(fun: Tree, args: List[Tree]): Option[ExtractorCall] = { - // // TODO: can we rework the typer so we don't have to do all this twice? - // // undo rewrite performed in (5) of adapt - // val orig = fun match {case tpt: TypeTree => tpt.original case _ => fun} - // val origSym = orig.symbol - // val extractor = unapplyMember(origSym.filter(sym => reallyExists(unapplyMember(sym.tpe))).tpe) - - // if((fun.tpe eq null) || fun.tpe.isError || (extractor eq NoSymbol)) { - // None - // } else { - // // this is a tricky balance: pos/t602.scala, pos/sudoku.scala, run/virtpatmat_alts.scala must all be happy - // // bypass typing at own risk: val extractorCall = Select(orig, extractor) setType caseClassApplyToUnapplyTp(fun.tpe) - // // can't always infer type arguments (pos/t602): - // /* case class Span[K <: Ordered[K]](low: Option[K]) { - // override def equals(x: Any): Boolean = x match { - // case Span((low0 @ _)) if low0 equals low => true - // } - // }*/ - // // so... leave undetermined type params floating around if we have to - // // (if we don't infer types, uninstantiated type params show up later: pos/sudoku.scala) - // // (see also run/virtpatmat_alts.scala) - // val savedUndets = context.undetparams - // val extractorCall = try { - // context.undetparams = Nil - // silent(_.typed(Apply(Select(orig, extractor), List(Ident(nme.SELECTOR_DUMMY) setType fun.tpe.finalResultType)), EXPRmode, WildcardType), reportAmbiguousErrors = false) match { - // case SilentResultValue(extractorCall) => extractorCall // if !extractorCall.containsError() - // case _ => - // // this fails to resolve overloading properly... - // // Apply(typedOperator(Select(orig, extractor)), List(Ident(nme.SELECTOR_DUMMY))) // no need to set the type of the dummy arg, it will be replaced anyway - - // // patmatDebug("funtpe after = "+ fun.tpe.finalResultType) - // // patmatDebug("orig: "+(orig, orig.tpe)) - // val tgt = typed(orig, EXPRmode | QUALmode | POLYmode, HasMember(extractor.name)) // can't specify fun.tpe.finalResultType as the type for the extractor's arg, - // // as it may have been inferred incorrectly (see t602, where it's com.mosol.sl.Span[Any], instead of com.mosol.sl.Span[?K]) - // // patmatDebug("tgt = "+ (tgt, tgt.tpe)) - // val oper = typed(Select(tgt, extractor.name), EXPRmode | FUNmode | POLYmode | TAPPmode, WildcardType) - // // patmatDebug("oper: "+ (oper, oper.tpe)) - // Apply(oper, List(Ident(nme.SELECTOR_DUMMY))) // no need to set the type of the dummy arg, it will be replaced anyway - // } - // } finally context.undetparams = savedUndets - - // Some(this(extractorCall, args)) // TODO: simplify spliceApply? - // } - // } + def fromCaseClassUnapply(fun: Tree, args: List[Tree]): Option[ExtractorCall] = { + // TODO: can we rework the typer so we don't have to do all this twice? + // undo rewrite performed in (5) of adapt + val orig = fun match {case tpt: TypeTree => tpt.original case _ => fun} + val origSym = orig.symbol + val extractor = unapplyMember(origSym.filter(sym => reallyExists(unapplyMember(sym.tpe))).tpe) + + if((fun.tpe eq null) || fun.tpe.isError || (extractor eq NoSymbol)) { + None + } else { + // this is a tricky balance: pos/t602.scala, pos/sudoku.scala, run/virtpatmat_alts.scala must all be happy + // bypass typing at own risk: val extractorCall = Select(orig, extractor) setType caseClassApplyToUnapplyTp(fun.tpe) + // can't always infer type arguments (pos/t602): + /* case class Span[K <: Ordered[K]](low: Option[K]) { + override def equals(x: Any): Boolean = x match { + case Span((low0 @ _)) if low0 equals low => true + } + }*/ + // so... leave undetermined type params floating around if we have to + // (if we don't infer types, uninstantiated type params show up later: pos/sudoku.scala) + // (see also run/virtpatmat_alts.scala) + val savedUndets = context.undetparams + val extractorCall = try { + context.undetparams = Nil + silent(_.typed(Apply(Select(orig, extractor), List(Ident(nme.SELECTOR_DUMMY) setType fun.tpe.finalResultType)), EXPRmode, WildcardType), reportAmbiguousErrors = false) match { + case SilentResultValue(extractorCall) => extractorCall // if !extractorCall.containsError() + case _ => + // this fails to resolve overloading properly... + // Apply(typedOperator(Select(orig, extractor)), List(Ident(nme.SELECTOR_DUMMY))) // no need to set the type of the dummy arg, it will be replaced anyway + + // patmatDebug("funtpe after = "+ fun.tpe.finalResultType) + // patmatDebug("orig: "+(orig, orig.tpe)) + val tgt = typed(orig, EXPRmode | QUALmode | POLYmode, HasMember(extractor.name)) // can't specify fun.tpe.finalResultType as the type for the extractor's arg, + // as it may have been inferred incorrectly (see t602, where it's com.mosol.sl.Span[Any], instead of com.mosol.sl.Span[?K]) + // patmatDebug("tgt = "+ (tgt, tgt.tpe)) + val oper = typed(Select(tgt, extractor.name), EXPRmode | FUNmode | POLYmode | TAPPmode, WildcardType) + // patmatDebug("oper: "+ (oper, oper.tpe)) + Apply(oper, List(Ident(nme.SELECTOR_DUMMY))) // no need to set the type of the dummy arg, it will be replaced anyway + } + } finally context.undetparams = savedUndets + + Some(this(extractorCall, args)) // TODO: simplify spliceApply? + } + } } abstract class ExtractorCall(val args: List[Tree]) { @@ -1413,10 +1413,10 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL // local / context-free def _asInstanceOf(b: Symbol, tp: Type): Tree - // def _asInstanceOf(t: Tree, tp: Type): Tree + def _asInstanceOf(t: Tree, tp: Type): Tree def _equals(checker: Tree, binder: Symbol): Tree def _isInstanceOf(b: Symbol, tp: Type): Tree - // def and(a: Tree, b: Tree): Tree + def and(a: Tree, b: Tree): Tree def drop(tgt: Tree)(n: Int): Tree def index(tgt: Tree)(i: Int): Tree def mkZero(tp: Type): Tree @@ -1458,12 +1458,12 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL abstract class CommonCodegen extends AbsCodegen { import CODE._ def fun(arg: Symbol, body: Tree): Tree = Function(List(ValDef(arg)), body) - // def genTypeApply(tfun: Tree, args: Type*): Tree = if(args contains NoType) tfun else TypeApply(tfun, args.toList map TypeTree) + def genTypeApply(tfun: Tree, args: Type*): Tree = if(args contains NoType) tfun else TypeApply(tfun, args.toList map TypeTree) def tupleSel(binder: Symbol)(i: Int): Tree = (REF(binder) DOT nme.productAccessorName(i)) // make tree that accesses the i'th component of the tuple referenced by binder def index(tgt: Tree)(i: Int): Tree = tgt APPLY (LIT(i)) def drop(tgt: Tree)(n: Int): Tree = (tgt DOT vpmName.drop) (LIT(n)) def _equals(checker: Tree, binder: Symbol): Tree = checker MEMBER_== REF(binder) // NOTE: checker must be the target of the ==, that's the patmat semantics for ya - // def and(a: Tree, b: Tree): Tree = a AND b + def and(a: Tree, b: Tree): Tree = a AND b // drop annotations generated by CPS plugin etc, since its annotationchecker rejects T @cps[U] <: Any // let's assume for now annotations don't affect casts, drop them there, and bring them back using the outer Typed tree @@ -1471,7 +1471,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL Typed(gen.mkAsInstanceOf(t, tp.withoutAnnotations, true, false), TypeTree() setType tp) // the force is needed mainly to deal with the GADT typing hack (we can't detect it otherwise as tp nor pt need contain an abstract type, we're just casting wildly) - // def _asInstanceOf(t: Tree, tp: Type): Tree = if (t.tpe != NoType && t.isTyped && typesConform(t.tpe, tp)) t else mkCast(t, tp) + def _asInstanceOf(t: Tree, tp: Type): Tree = if (t.tpe != NoType && t.isTyped && typesConform(t.tpe, tp)) t else mkCast(t, tp) def _asInstanceOf(b: Symbol, tp: Type): Tree = if (typesConform(b.info, tp)) REF(b) else mkCast(REF(b), tp) def _isInstanceOf(b: Symbol, tp: Type): Tree = gen.mkIsInstanceOf(REF(b), tp.withoutAnnotations, true, false) // if (typesConform(b.info, tpX)) { patmatDebug("warning: emitted spurious isInstanceOf: "+(b, tp)); TRUE } @@ -2879,7 +2879,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL v +"(="+ v.path +": "+ v.staticTpCheckable +") "+ assignment }.mkString("\n") - // def modelString(model: Model) = varAssignmentString(modelToVarAssignment(model)) + def modelString(model: Model) = varAssignmentString(modelToVarAssignment(model)) // return constructor call when the model is a true counter example // (the variables don't take into account type information derived from other variables, @@ -3538,7 +3538,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL // for the catch-cases in a try/catch private object typeSwitchMaker extends SwitchMaker { val unchecked = false - // def switchableTpe(tp: Type) = true + def switchableTpe(tp: Type) = true val alternativesSupported = false // TODO: needs either back-end support of flattening of alternatives during typers val canJump = false diff --git a/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala b/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala index f1e6e48ccc..710adf5a9c 100644 --- a/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala @@ -142,13 +142,13 @@ abstract class TreeCheckers extends Analyzer { currentRun.units foreach (x => wrap(x)(check(x))) } - // def printingTypings[T](body: => T): T = { - // val saved = global.printTypings - // global.printTypings = true - // val result = body - // global.printTypings = saved - // result - // } + def printingTypings[T](body: => T): T = { + val saved = global.printTypings + global.printTypings = true + val result = body + global.printTypings = saved + result + } def runWithUnit[T](unit: CompilationUnit)(body: => Unit): Unit = { val unit0 = currentUnit currentRun.currentUnit = unit diff --git a/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala index ebeb8ef2c8..4f5291507e 100644 --- a/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala +++ b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala @@ -41,9 +41,9 @@ trait TypeDiagnostics { * nicer if Symbols, Types, and Trees all implemented some common interface * in which isErroneous and similar would be placed. */ - // def noErroneousTypes(tps: Type*) = tps forall (x => !x.isErroneous) - // def noErroneousSyms(syms: Symbol*) = syms forall (x => !x.isErroneous) - // def noErroneousTrees(trees: Tree*) = trees forall (x => !x.isErroneous) + def noErroneousTypes(tps: Type*) = tps forall (x => !x.isErroneous) + def noErroneousSyms(syms: Symbol*) = syms forall (x => !x.isErroneous) + def noErroneousTrees(trees: Tree*) = trees forall (x => !x.isErroneous) /** For errors which are artifacts of the implementation: such messages * indicate that the restriction may be lifted in the future. @@ -294,7 +294,7 @@ trait TypeDiagnostics { // distinguished from the other types in the same error message private val savedName = sym.name def restoreName() = sym.name = savedName - // def isAltered = sym.name != savedName + def isAltered = sym.name != savedName def modifyName(f: String => String) = sym setName newTypeName(f(sym.name.toString)) /** Prepend java.lang, scala., or Predef. if this type originated @@ -478,10 +478,10 @@ trait TypeDiagnostics { } super.traverse(t) } - // def isUnused(t: Tree): Boolean = ( - // if (t.symbol.isTerm) isUnusedTerm(t.symbol) - // else isUnusedType(t.symbol) - // ) + def isUnused(t: Tree): Boolean = ( + if (t.symbol.isTerm) isUnusedTerm(t.symbol) + else isUnusedType(t.symbol) + ) def isUnusedType(m: Symbol): Boolean = ( m.isType && !m.isTypeParameterOrSkolem // would be nice to improve this diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 0a295febf3..0a0ab53852 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -394,8 +394,8 @@ trait Typers extends Modes with Adaptations with Tags { * @param tree ... * @return ... */ - // def locals[T <: Tree](scope: Scope, pt: Type, tree: T): T = - // check(NoSymbol, scope, pt, tree) + def locals[T <: Tree](scope: Scope, pt: Type, tree: T): T = + check(NoSymbol, scope, pt, tree) private def check[T <: Tree](owner: Symbol, scope: Scope, pt: Type, tree: T): T = { this.owner = owner @@ -5343,7 +5343,7 @@ trait Typers extends Modes with Adaptations with Tags { def typedHigherKindedType(tree: Tree, mode: Int): Tree = typed(tree, HKmode, WildcardType) - // def typedHigherKindedType(tree: Tree): Tree = typedHigherKindedType(tree, NOmode) + def typedHigherKindedType(tree: Tree): Tree = typedHigherKindedType(tree, NOmode) /** Types a type constructor tree used in a new or supertype */ def typedTypeConstructor(tree: Tree, mode: Int): Tree = { @@ -5431,16 +5431,16 @@ trait Typers extends Modes with Adaptations with Tags { object TypersStats { import scala.reflect.internal.TypesStats._ - // import scala.reflect.internal.BaseTypeSeqsStats._ + import scala.reflect.internal.BaseTypeSeqsStats._ val typedIdentCount = Statistics.newCounter("#typechecked identifiers") val typedSelectCount = Statistics.newCounter("#typechecked selections") val typedApplyCount = Statistics.newCounter("#typechecked applications") val rawTypeFailed = Statistics.newSubCounter (" of which in failed", rawTypeCount) val subtypeFailed = Statistics.newSubCounter(" of which in failed", subtypeCount) val findMemberFailed = Statistics.newSubCounter(" of which in failed", findMemberCount) - // val compoundBaseTypeSeqCount = Statistics.newSubCounter(" of which for compound types", baseTypeSeqCount) - // val typerefBaseTypeSeqCount = Statistics.newSubCounter(" of which for typerefs", baseTypeSeqCount) - // val singletonBaseTypeSeqCount = Statistics.newSubCounter(" of which for singletons", baseTypeSeqCount) + val compoundBaseTypeSeqCount = Statistics.newSubCounter(" of which for compound types", baseTypeSeqCount) + val typerefBaseTypeSeqCount = Statistics.newSubCounter(" of which for typerefs", baseTypeSeqCount) + val singletonBaseTypeSeqCount = Statistics.newSubCounter(" of which for singletons", baseTypeSeqCount) val failedSilentNanos = Statistics.newSubTimer("time spent in failed", typerNanos) val failedApplyNanos = Statistics.newSubTimer(" failed apply", typerNanos) val failedOpEqNanos = Statistics.newSubTimer(" failed op=", typerNanos) diff --git a/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala b/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala index 094b32673c..bf44b65406 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala @@ -51,11 +51,11 @@ trait Unapplies extends ast.TreeDSL * for n == 1, Some[T0] * else Some[Product[Ti]] */ - // def unapplyReturnTypeExpected(argsLength: Int) = argsLength match { - // case 0 => BooleanClass.tpe - // case 1 => optionType(WildcardType) - // case n => optionType(productType((List fill n)(WildcardType))) - // } + def unapplyReturnTypeExpected(argsLength: Int) = argsLength match { + case 0 => BooleanClass.tpe + case 1 => optionType(WildcardType) + case n => optionType(productType((List fill n)(WildcardType))) + } /** returns unapply or unapplySeq if available */ def unapplyMember(tp: Type): Symbol = (tp member nme.unapply) match { diff --git a/src/compiler/scala/tools/nsc/util/ClassPath.scala b/src/compiler/scala/tools/nsc/util/ClassPath.scala index f82c504eb4..0c49b9b8e7 100644 --- a/src/compiler/scala/tools/nsc/util/ClassPath.scala +++ b/src/compiler/scala/tools/nsc/util/ClassPath.scala @@ -50,20 +50,20 @@ object ClassPath { def map(cp: String, f: String => String): String = join(split(cp) map f: _*) /** Split the classpath, filter according to predicate, and reassemble. */ - // def filter(cp: String, p: String => Boolean): String = join(split(cp) filter p: _*) + def filter(cp: String, p: String => Boolean): String = join(split(cp) filter p: _*) /** Split the classpath and map them into Paths */ - // def toPaths(cp: String): List[Path] = split(cp) map (x => Path(x).toAbsolute) + def toPaths(cp: String): List[Path] = split(cp) map (x => Path(x).toAbsolute) /** Make all classpath components absolute. */ - // def makeAbsolute(cp: String): String = fromPaths(toPaths(cp): _*) + def makeAbsolute(cp: String): String = fromPaths(toPaths(cp): _*) /** Join the paths as a classpath */ - // def fromPaths(paths: Path*): String = join(paths map (_.path): _*) - // def fromURLs(urls: URL*): String = fromPaths(urls map (x => Path(x.getPath)) : _*) + def fromPaths(paths: Path*): String = join(paths map (_.path): _*) + def fromURLs(urls: URL*): String = fromPaths(urls map (x => Path(x.getPath)) : _*) /** Split the classpath and map them into URLs */ - // def toURLs(cp: String): List[URL] = toPaths(cp) map (_.toURL) + def toURLs(cp: String): List[URL] = toPaths(cp) map (_.toURL) /** Expand path and possibly expanding stars */ def expandPath(path: String, expandStar: Boolean = true): List[String] = @@ -124,12 +124,12 @@ object ClassPath { for (dir <- expandPath(path, false) ; name <- expandDir(dir) ; entry <- Option(AbstractFile getDirectory name)) yield newClassPath(entry) - // def classesAtAllURLS(path: String): List[ClassPath[T]] = - // (path split " ").toList flatMap classesAtURL + def classesAtAllURLS(path: String): List[ClassPath[T]] = + (path split " ").toList flatMap classesAtURL - // def classesAtURL(spec: String) = - // for (url <- specToURL(spec).toList ; location <- Option(AbstractFile getURL url)) yield - // newClassPath(location) + def classesAtURL(spec: String) = + for (url <- specToURL(spec).toList ; location <- Option(AbstractFile getURL url)) yield + newClassPath(location) def classesInExpandedPath(path: String): IndexedSeq[ClassPath[T]] = classesInPathImpl(path, true).toIndexedSeq @@ -400,14 +400,14 @@ class JavaClassPath( context: JavaContext) extends MergedClassPath[AbstractFile](containers, context) { } -// object JavaClassPath { -// def fromURLs(urls: Seq[URL], context: JavaContext): JavaClassPath = { -// val containers = { -// for (url <- urls ; f = AbstractFile getURL url ; if f != null) yield -// new DirectoryClassPath(f, context) -// } -// new JavaClassPath(containers.toIndexedSeq, context) -// } -// def fromURLs(urls: Seq[URL]): JavaClassPath = -// fromURLs(urls, ClassPath.DefaultJavaContext) -// } +object JavaClassPath { + def fromURLs(urls: Seq[URL], context: JavaContext): JavaClassPath = { + val containers = { + for (url <- urls ; f = AbstractFile getURL url ; if f != null) yield + new DirectoryClassPath(f, context) + } + new JavaClassPath(containers.toIndexedSeq, context) + } + def fromURLs(urls: Seq[URL]): JavaClassPath = + fromURLs(urls, ClassPath.DefaultJavaContext) +} diff --git a/src/compiler/scala/tools/nsc/util/CommandLineParser.scala b/src/compiler/scala/tools/nsc/util/CommandLineParser.scala index 2baab177b8..81c1b1d37a 100644 --- a/src/compiler/scala/tools/nsc/util/CommandLineParser.scala +++ b/src/compiler/scala/tools/nsc/util/CommandLineParser.scala @@ -21,7 +21,7 @@ import scala.collection.mutable.ListBuffer trait ParserUtil extends Parsers { protected implicit class ParserPlus[+T](underlying: Parser[T]) { def !~>[U](p: => Parser[U]): Parser[U] = (underlying ~! p) ^^ { case a~b => b } - // def <~![U](p: => Parser[U]): Parser[T] = (underlying ~! p) ^^ { case a~b => a } + def <~![U](p: => Parser[U]): Parser[T] = (underlying ~! p) ^^ { case a~b => a } } } @@ -37,7 +37,7 @@ case class CommandLine( def withUnaryArgs(xs: List[String]) = copy(unaryArguments = xs) def withBinaryArgs(xs: List[String]) = copy(binaryArguments = xs) - // def originalArgs = args + def originalArgs = args def assumeBinary = true def enforceArity = true def onlyKnownOptions = false @@ -105,7 +105,7 @@ case class CommandLine( def isSet(arg: String) = args contains arg def get(arg: String) = argMap get arg - // def getOrElse(arg: String, orElse: => String) = if (isSet(arg)) apply(arg) else orElse + def getOrElse(arg: String, orElse: => String) = if (isSet(arg)) apply(arg) else orElse def apply(arg: String) = argMap(arg) override def toString() = "CommandLine(\n%s)\n" format (args map (" " + _ + "\n") mkString) @@ -115,7 +115,7 @@ object CommandLineParser extends RegexParsers with ParserUtil { override def skipWhitespace = false def elemExcept(xs: Elem*): Parser[Elem] = elem("elemExcept", x => x != EofCh && !(xs contains x)) - // def elemOf(xs: Elem*): Parser[Elem] = elem("elemOf", xs contains _) + def elemOf(xs: Elem*): Parser[Elem] = elem("elemOf", xs contains _) def escaped(ch: Char): Parser[String] = "\\" + ch def mkQuoted(ch: Char): Parser[String] = ( elem(ch) !~> rep(escaped(ch) | elemExcept(ch)) <~ ch ^^ (_.mkString) diff --git a/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala b/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala index a056a97a7c..b7ed7903bc 100644 --- a/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala +++ b/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala @@ -17,43 +17,46 @@ class JavaCharArrayReader(buf: IndexedSeq[Char], start: Int, /* startline: int, /** produce a duplicate of this char array reader which starts reading * at current position, independent of what happens to original reader */ - // def dup: JavaCharArrayReader = clone().asInstanceOf[JavaCharArrayReader] + def dup: JavaCharArrayReader = clone().asInstanceOf[JavaCharArrayReader] /** layout constant */ - // val tabinc = 8 + val tabinc = 8 /** the line and column position of the current character */ var ch: Char = _ var bp = start - // var oldBp = -1 - // var oldCh: Char = _ + var oldBp = -1 + var oldCh: Char = _ //private var cline: Int = _ //private var ccol: Int = _ def cpos = bp var isUnicode: Boolean = _ - // var lastLineStartPos: Int = 0 - // var lineStartPos: Int = 0 - // var lastBlankLinePos: Int = 0 + var lastLineStartPos: Int = 0 + var lineStartPos: Int = 0 + var lastBlankLinePos: Int = 0 - // private var onlyBlankChars = false + private var onlyBlankChars = false //private var nextline = startline //private var nextcol = startcol private def markNewLine() { - // lastLineStartPos = lineStartPos - // if (onlyBlankChars) lastBlankLinePos = lineStartPos - // lineStartPos = bp - // onlyBlankChars = true + lastLineStartPos = lineStartPos + if (onlyBlankChars) lastBlankLinePos = lineStartPos + lineStartPos = bp + onlyBlankChars = true //nextline += 1 //nextcol = 1 } - def hasNext = bp < buf.length + def hasNext: Boolean = if (bp < buf.length) true + else { + false + } - // def last: Char = if (bp > start + 2) buf(bp - 2) else ' ' // XML literals + def last: Char = if (bp > start + 2) buf(bp - 2) else ' ' // XML literals def next(): Char = { //cline = nextline @@ -63,8 +66,8 @@ class JavaCharArrayReader(buf: IndexedSeq[Char], start: Int, /* startline: int, ch = SU return SU // there is an endless stream of SU's at the end } - // oldBp = bp - // oldCh = ch + oldBp = bp + oldCh = ch ch = buf(bp) isUnicode = false bp = bp + 1 @@ -101,19 +104,19 @@ class JavaCharArrayReader(buf: IndexedSeq[Char], start: Int, /* startline: int, isUnicode = true } case _ => - // if (ch > ' ') onlyBlankChars = false + if (ch > ' ') onlyBlankChars = false // nextcol += 1 } ch } - // def rewind() { - // if (oldBp == -1) throw new IllegalArgumentException - // bp = oldBp - // ch = oldCh - // oldBp = -1 - // oldCh = 'x' - // } + def rewind() { + if (oldBp == -1) throw new IllegalArgumentException + bp = oldBp + ch = oldCh + oldBp = -1 + oldCh = 'x' + } def copy: JavaCharArrayReader = new JavaCharArrayReader(buf, bp, /* nextcol, nextline, */ decodeUni, error) diff --git a/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala b/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala index f09787ec4f..a2994966fd 100644 --- a/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala +++ b/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala @@ -46,8 +46,8 @@ trait ScalaClassLoader extends JClassLoader { def create(path: String): AnyRef = tryToInitializeClass[AnyRef](path) map (_.newInstance()) orNull - // def constructorsOf[T <: AnyRef : ClassTag]: List[Constructor[T]] = - // classTag[T].runtimeClass.getConstructors.toList map (_.asInstanceOf[Constructor[T]]) + def constructorsOf[T <: AnyRef : ClassTag]: List[Constructor[T]] = + classTag[T].runtimeClass.getConstructors.toList map (_.asInstanceOf[Constructor[T]]) /** The actual bytes for a class file, or an empty array if it can't be found. */ def classBytes(className: String): Array[Byte] = classAsStream(className) match { @@ -75,10 +75,10 @@ trait ScalaClassLoader extends JClassLoader { /** A list comprised of this classloader followed by all its * (non-null) parent classloaders, if any. */ - // def loaderChain: List[ScalaClassLoader] = this :: (getParent match { - // case null => Nil - // case p => p.loaderChain - // }) + def loaderChain: List[ScalaClassLoader] = this :: (getParent match { + case null => Nil + case p => p.loaderChain + }) } /** Methods for obtaining various classloaders. @@ -99,35 +99,35 @@ object ScalaClassLoader { } def contextLoader = apply(Thread.currentThread.getContextClassLoader) def appLoader = apply(JClassLoader.getSystemClassLoader) - // def extLoader = apply(appLoader.getParent) - // def bootLoader = apply(null) - // def contextChain = loaderChain(contextLoader) + def extLoader = apply(appLoader.getParent) + def bootLoader = apply(null) + def contextChain = loaderChain(contextLoader) - // def pathToErasure[T: ClassTag] = pathToClass(classTag[T].runtimeClass) - // def pathToClass(clazz: Class[_]) = clazz.getName.replace('.', JFile.separatorChar) + ".class" - // def locate[T: ClassTag] = contextLoader getResource pathToErasure[T] + def pathToErasure[T: ClassTag] = pathToClass(classTag[T].runtimeClass) + def pathToClass(clazz: Class[_]) = clazz.getName.replace('.', JFile.separatorChar) + ".class" + def locate[T: ClassTag] = contextLoader getResource pathToErasure[T] /** Tries to guess the classpath by type matching the context classloader * and its parents, looking for any classloaders which will reveal their * classpath elements as urls. It it can't find any, creates a classpath * from the supplied string. */ - // def guessClassPathString(default: String = ""): String = { - // val classpathURLs = contextChain flatMap { - // case x: HasClassPath => x.classPathURLs - // case x: JURLClassLoader => x.getURLs.toSeq - // case _ => Nil - // } - // if (classpathURLs.isEmpty) default - // else JavaClassPath.fromURLs(classpathURLs).asClasspathString - // } - - // def loaderChain(head: JClassLoader) = { - // def loop(cl: JClassLoader): List[JClassLoader] = - // if (cl == null) Nil else cl :: loop(cl.getParent) - - // loop(head) - // } + def guessClassPathString(default: String = ""): String = { + val classpathURLs = contextChain flatMap { + case x: HasClassPath => x.classPathURLs + case x: JURLClassLoader => x.getURLs.toSeq + case _ => Nil + } + if (classpathURLs.isEmpty) default + else JavaClassPath.fromURLs(classpathURLs).asClasspathString + } + + def loaderChain(head: JClassLoader) = { + def loop(cl: JClassLoader): List[JClassLoader] = + if (cl == null) Nil else cl :: loop(cl.getParent) + + loop(head) + } def setContext(cl: JClassLoader) = Thread.currentThread.setContextClassLoader(cl) def savingContextLoader[T](body: => T): T = { @@ -143,14 +143,14 @@ object ScalaClassLoader { private var classloaderURLs: Seq[URL] = urls def classPathURLs: Seq[URL] = classloaderURLs - // def classPath: ClassPath[_] = JavaClassPath fromURLs classPathURLs + def classPath: ClassPath[_] = JavaClassPath fromURLs classPathURLs /** Override to widen to public */ override def addURL(url: URL) = { classloaderURLs :+= url super.addURL(url) } - // def toLongString = urls.mkString("URLClassLoader(\n ", "\n ", "\n)\n") + def toLongString = urls.mkString("URLClassLoader(\n ", "\n ", "\n)\n") } def fromURLs(urls: Seq[URL], parent: ClassLoader = null): URLClassLoader = @@ -161,7 +161,7 @@ object ScalaClassLoader { fromURLs(urls) tryToLoadClass name isDefined /** Finding what jar a clazz or instance came from */ - // def origin(x: Any): Option[URL] = originOfClass(x.getClass) + def origin(x: Any): Option[URL] = originOfClass(x.getClass) def originOfClass(x: Class[_]): Option[URL] = Option(x.getProtectionDomain.getCodeSource) flatMap (x => Option(x.getLocation)) } diff --git a/src/compiler/scala/tools/nsc/util/SimpleTracer.scala b/src/compiler/scala/tools/nsc/util/SimpleTracer.scala index a3b92aa2df..b103ae9cb0 100644 --- a/src/compiler/scala/tools/nsc/util/SimpleTracer.scala +++ b/src/compiler/scala/tools/nsc/util/SimpleTracer.scala @@ -14,6 +14,6 @@ class SimpleTracer(out: PrintStream, enabled: Boolean = true) { if (enabled) out.println(msg+value) value } - // def withOutput(out: PrintStream) = new SimpleTracer(out, enabled) + def withOutput(out: PrintStream) = new SimpleTracer(out, enabled) def when(enabled: Boolean): SimpleTracer = new SimpleTracer(out, enabled) } diff --git a/src/compiler/scala/tools/nsc/util/package.scala b/src/compiler/scala/tools/nsc/util/package.scala index b40d3094f3..e9dcaa8e16 100644 --- a/src/compiler/scala/tools/nsc/util/package.scala +++ b/src/compiler/scala/tools/nsc/util/package.scala @@ -18,15 +18,15 @@ package object util { type HashSet[T >: Null <: AnyRef] = scala.reflect.internal.util.HashSet[T] val HashSet = scala.reflect.internal.util.HashSet - // def onull[T](value: T, orElse: => T): T = if (value == null) orElse else value + def onull[T](value: T, orElse: => T): T = if (value == null) orElse else value /** Apply a function and return the passed value */ def returning[T](x: T)(f: T => Unit): T = { f(x) ; x } /** Frequency counter */ - // def freq[T](xs: Traversable[T]): Map[T, Int] = xs groupBy identity mapValues (_.size) + def freq[T](xs: Traversable[T]): Map[T, Int] = xs groupBy identity mapValues (_.size) - // def freqrank[T](xs: Traversable[(T, Int)]): List[(Int, T)] = xs.toList map (_.swap) sortBy (-_._1) + def freqrank[T](xs: Traversable[(T, Int)]): List[(Int, T)] = xs.toList map (_.swap) sortBy (-_._1) /** Execute code and then wait for all non-daemon Threads * created and begun during its execution to complete. @@ -57,14 +57,14 @@ package object util { /** Given a function and a block of code, evaluates code block, * calls function with milliseconds elapsed, and returns block result. */ - // def millisElapsedTo[T](f: Long => Unit)(body: => T): T = { - // val start = System.currentTimeMillis - // val result = body - // val end = System.currentTimeMillis + def millisElapsedTo[T](f: Long => Unit)(body: => T): T = { + val start = System.currentTimeMillis + val result = body + val end = System.currentTimeMillis - // f(end - start) - // result - // } + f(end - start) + result + } /** Generate a string using a routine that wants to write on a stream. */ def stringFromWriter(writer: PrintWriter => Unit): String = { @@ -96,7 +96,7 @@ package object util { } lazy val trace = new SimpleTracer(System.out) - // lazy val errtrace = new SimpleTracer(System.err) + lazy val errtrace = new SimpleTracer(System.err) @deprecated("Moved to scala.reflect.internal.util.StringOps", "2.10.0") val StringOps = scala.reflect.internal.util.StringOps diff --git a/src/compiler/scala/tools/reflect/ToolBoxFactory.scala b/src/compiler/scala/tools/reflect/ToolBoxFactory.scala index 4fc3fede16..f0c88eadea 100644 --- a/src/compiler/scala/tools/reflect/ToolBoxFactory.scala +++ b/src/compiler/scala/tools/reflect/ToolBoxFactory.scala @@ -392,8 +392,8 @@ abstract class ToolBoxFactory[U <: JavaUniverse](val u: U) { factorySelf => uttree } - // def showAttributed(tree: u.Tree, printTypes: Boolean = true, printIds: Boolean = true, printKinds: Boolean = false): String = - // compiler.showAttributed(importer.importTree(tree), printTypes, printIds, printKinds) + def showAttributed(tree: u.Tree, printTypes: Boolean = true, printIds: Boolean = true, printKinds: Boolean = false): String = + compiler.showAttributed(importer.importTree(tree), printTypes, printIds, printKinds) def parse(code: String): u.Tree = { if (compiler.settings.verbose.value) println("parsing "+code) diff --git a/src/compiler/scala/tools/util/Javap.scala b/src/compiler/scala/tools/util/Javap.scala index b80c65caa6..4d94581cc1 100644 --- a/src/compiler/scala/tools/util/Javap.scala +++ b/src/compiler/scala/tools/util/Javap.scala @@ -107,8 +107,8 @@ object Javap { type FakeEnvironment = AnyRef type FakePrinter = AnyRef - // def apply(path: String): Unit = apply(Seq(path)) - // def apply(args: Seq[String]): Unit = new JavapClass() apply args foreach (_.show()) + def apply(path: String): Unit = apply(Seq(path)) + def apply(args: Seq[String]): Unit = new JavapClass() apply args foreach (_.show()) sealed trait JpResult { type ResultType diff --git a/src/compiler/scala/tools/util/PathResolver.scala b/src/compiler/scala/tools/util/PathResolver.scala index c88a8e13c4..6b0821edf3 100644 --- a/src/compiler/scala/tools/util/PathResolver.scala +++ b/src/compiler/scala/tools/util/PathResolver.scala @@ -22,11 +22,11 @@ object PathResolver { // security exceptions. import AccessControl._ - // def firstNonEmpty(xs: String*) = xs find (_ != "") getOrElse "" + def firstNonEmpty(xs: String*) = xs find (_ != "") getOrElse "" /** Map all classpath elements to absolute paths and reconstruct the classpath. */ - // def makeAbsolute(cp: String) = ClassPath.map(cp, x => Path(x).toAbsolute.path) + def makeAbsolute(cp: String) = ClassPath.map(cp, x => Path(x).toAbsolute.path) /** pretty print class path */ def ppcp(s: String) = split(s) match { @@ -45,7 +45,7 @@ object PathResolver { /** Environment variables which java pays attention to so it * seems we do as well. */ - // def classPathEnv = envOrElse("CLASSPATH", "") + def classPathEnv = envOrElse("CLASSPATH", "") def sourcePathEnv = envOrElse("SOURCEPATH", "") def javaBootClassPath = propOrElse("sun.boot.class.path", searchForBootClasspath) @@ -85,7 +85,7 @@ object PathResolver { def scalaHome = Environment.scalaHome def scalaHomeDir = Directory(scalaHome) - // def scalaHomeExists = scalaHomeDir.isDirectory + def scalaHomeExists = scalaHomeDir.isDirectory def scalaLibDir = Directory(scalaHomeDir / "lib") def scalaClassesDir = Directory(scalaHomeDir / "classes") @@ -135,7 +135,7 @@ object PathResolver { ) } - def fromPathString(path: String, context: JavaContext = DefaultJavaContext): JavaClassPath = { // called from scalap + def fromPathString(path: String, context: JavaContext = DefaultJavaContext): JavaClassPath = { val s = new Settings() s.classpath.value = path new PathResolver(s, context) result @@ -160,7 +160,7 @@ object PathResolver { } } } -import PathResolver.{ Defaults, Environment, ppcp } +import PathResolver.{ Defaults, Environment, firstNonEmpty, ppcp } class PathResolver(settings: Settings, context: JavaContext) { def this(settings: Settings) = this(settings, if (settings.inline.value) new JavaContext else DefaultJavaContext) -- cgit v1.2.3