From 120879e2f5a10beaa94ef9e886e67a1c092fded0 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Sat, 10 Nov 2012 15:52:25 -0700 Subject: Deal with possibly spurious warning in Macros. --- src/compiler/scala/tools/nsc/typechecker/Macros.scala | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src/compiler/scala/tools') diff --git a/src/compiler/scala/tools/nsc/typechecker/Macros.scala b/src/compiler/scala/tools/nsc/typechecker/Macros.scala index 09f3fefeba..4b534b0d2e 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Macros.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Macros.scala @@ -720,16 +720,15 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces { /** Does the same as `macroExpand`, but without typechecking the expansion * Meant for internal use within the macro infrastructure, don't use it elsewhere. */ - private def macroExpand1(typer: Typer, expandee: Tree): MacroExpansionResult = + private def macroExpand1(typer: Typer, expandee: Tree): MacroExpansionResult = { // verbose printing might cause recursive macro expansions, so I'm shutting it down here withInfoLevel(nodePrinters.InfoLevel.Quiet) { if (expandee.symbol.isErroneous || (expandee exists (_.isErroneous))) { val reason = if (expandee.symbol.isErroneous) "not found or incompatible macro implementation" else "erroneous arguments" macroTraceVerbose("cancelled macro expansion because of %s: ".format(reason))(expandee) - return Cancel(typer.infer.setError(expandee)) + Cancel(typer.infer.setError(expandee)) } - - try { + else try { val runtime = macroRuntime(expandee.symbol) if (runtime != null) macroExpandWithRuntime(typer, expandee, runtime) else macroExpandWithoutRuntime(typer, expandee) @@ -737,6 +736,7 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces { case typer.TyperErrorGen.MacroExpansionException => Failure(expandee) } } + } /** Expands a macro when a runtime (i.e. the macro implementation) can be successfully loaded * Meant for internal use within the macro infrastructure, don't use it elsewhere. -- cgit v1.2.3 From 345f937b3441f248ac9156484758fa17b1a78941 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Sun, 11 Nov 2012 17:34:16 -0800 Subject: applyOrElse is a synthetic method. --- src/compiler/scala/tools/nsc/transform/UnCurry.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/compiler/scala/tools') diff --git a/src/compiler/scala/tools/nsc/transform/UnCurry.scala b/src/compiler/scala/tools/nsc/transform/UnCurry.scala index 84803d0b6b..a3340bcc16 100644 --- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala +++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala @@ -336,7 +336,7 @@ abstract class UnCurry extends InfoTransform // def applyOrElse[A1 <: A, B1 >: B](x: A1, default: A1 => B1): B1 = val applyOrElseMethodDef = { - val methSym = anonClass.newMethod(nme.applyOrElse, fun.pos, newFlags = FINAL | OVERRIDE) + val methSym = anonClass.newMethod(nme.applyOrElse, fun.pos, newFlags = FINAL | OVERRIDE | SYNTHETIC) val List(argtpe) = formals val A1 = methSym newTypeParameter(newTypeName("A1")) setInfo TypeBounds.upper(argtpe) -- cgit v1.2.3 From 645c2676dd6699ac24a57dfe750386bbdb827ee8 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Mon, 12 Nov 2012 23:21:47 -0800 Subject: Commenting out unused members. I want to get this commit into the history because the tests pass here, which demonstrates that every commented out method is not only unnecessary internally but has zero test coverage. Since I know (based on the occasional source code comment, or more often based on knowing something about other source bases) that some of these can't be removed without breaking other things, I want to at least record a snapshot of the identities of all these unused and untested methods. This commit will be reverted; then there will be another commit which removes the subset of these methods which I believe to be removable. The remainder are in great need of tests which exercise the interfaces upon which other repositories depend. --- 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 +- .../scala/util/continuations/ControlContext.scala | 4 +- .../library/scala/util/continuations/package.scala | 6 +- src/detach/plugin/scala/tools/detach/Detach.scala | 2 +- src/partest/scala/tools/partest/CompilerTest.scala | 3 +- src/partest/scala/tools/partest/SecurityTest.scala | 22 +- src/partest/scala/tools/partest/TestUtil.scala | 14 +- .../partest/instrumented/Instrumentation.scala | 1 + .../tools/partest/nest/ConsoleFileManager.scala | 20 +- .../scala/tools/partest/nest/ConsoleRunner.scala | 2 +- .../scala/tools/partest/nest/FileManager.scala | 8 +- src/partest/scala/tools/partest/nest/NestUI.scala | 20 +- .../tools/partest/nest/ReflectiveRunner.scala | 9 +- .../scala/tools/partest/nest/RunnerManager.scala | 8 +- .../scala/tools/partest/nest/RunnerUtils.scala | 46 ++-- src/partest/scala/tools/partest/package.scala | 8 +- .../scala/tools/partest/utils/PrintMgr.scala | 104 ++++----- .../scala/reflect/internal/AnnotationInfos.scala | 11 +- .../scala/reflect/internal/BuildUtils.scala | 2 - .../reflect/internal/ClassfileConstants.scala | 12 +- .../scala/reflect/internal/Definitions.scala | 137 ++++++------ .../reflect/internal/ExistentialsAndSkolems.scala | 1 - src/reflect/scala/reflect/internal/Importers.scala | 2 +- src/reflect/scala/reflect/internal/Names.scala | 64 +++--- src/reflect/scala/reflect/internal/Printers.scala | 4 +- src/reflect/scala/reflect/internal/Scopes.scala | 2 +- src/reflect/scala/reflect/internal/StdNames.scala | 242 ++++++++++----------- .../scala/reflect/internal/SymbolTable.scala | 3 +- src/reflect/scala/reflect/internal/Symbols.scala | 125 ++++++----- src/reflect/scala/reflect/internal/TreeGen.scala | 12 +- src/reflect/scala/reflect/internal/TreeInfo.scala | 58 ++--- src/reflect/scala/reflect/internal/Trees.scala | 2 +- .../scala/reflect/internal/TypeDebugging.scala | 4 +- src/reflect/scala/reflect/internal/Types.scala | 196 ++++++++--------- .../reflect/internal/pickling/PickleBuffer.scala | 2 +- .../reflect/internal/pickling/PickleFormat.scala | 2 +- .../reflect/internal/pickling/UnPickler.scala | 14 +- .../scala/reflect/internal/util/Collections.scala | 54 ++--- .../scala/reflect/internal/util/HashSet.scala | 4 +- .../scala/reflect/internal/util/Origins.scala | 2 - .../scala/reflect/internal/util/Position.scala | 2 +- .../scala/reflect/internal/util/SourceFile.scala | 9 +- .../scala/reflect/internal/util/StringOps.scala | 46 ++-- .../scala/reflect/internal/util/TableDef.scala | 8 +- .../internal/util/TraceSymbolActivity.scala | 4 +- .../scala/reflect/internal/util/WeakHashSet.scala | 3 - src/reflect/scala/reflect/io/AbstractFile.scala | 12 +- src/reflect/scala/reflect/io/Directory.scala | 17 +- src/reflect/scala/reflect/io/File.scala | 104 ++++----- src/reflect/scala/reflect/io/Path.scala | 34 +-- src/reflect/scala/reflect/io/PlainFile.scala | 12 +- src/reflect/scala/reflect/io/Streamable.scala | 10 +- .../scala/reflect/io/VirtualDirectory.scala | 5 +- src/reflect/scala/reflect/io/VirtualFile.scala | 4 +- src/reflect/scala/reflect/io/ZipArchive.scala | 10 +- src/reflect/scala/reflect/macros/TreeBuilder.scala | 1 - .../scala/reflect/runtime/JavaMirrors.scala | 19 +- .../scala/reflect/runtime/JavaUniverse.scala | 5 +- .../reflect/runtime/SynchronizedSymbols.scala | 4 +- src/reflect/scala/reflect/runtime/package.scala | 2 +- 193 files changed, 2581 insertions(+), 2662 deletions(-) (limited to 'src/compiler/scala/tools') diff --git a/src/compiler/scala/reflect/reify/Errors.scala b/src/compiler/scala/reflect/reify/Errors.scala index a72233274e..9e59b40236 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 6554947f88..d0f8ae76e2 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) - tpe != null && (tpe exists isTough) - } + // 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) + // } 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 92d951c3a1..cccf080dbf 100644 --- a/src/compiler/scala/reflect/reify/phases/Metalevels.scala +++ b/src/compiler/scala/reflect/reify/phases/Metalevels.scala @@ -1,6 +1,8 @@ package scala.reflect.reify package phases +import scala.collection.{ mutable } + trait Metalevels { self: Reifier => @@ -101,7 +103,7 @@ trait Metalevels { */ val metalevels = new Transformer { var insideSplice = false - var inlineableBindings = scala.collection.mutable.Map[TermName, Tree]() + val inlineableBindings = 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 99118c4f2e..6e34d64847 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 fde61e9564..d0fefdaa03 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, Reference} +import org.apache.tools.ant.types.Path class Settings { diff --git a/src/compiler/scala/tools/cmd/FromString.scala b/src/compiler/scala/tools/cmd/FromString.scala index 2a624875ee..c9df9f9145 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 d4f2060f81..4f1620d61a 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 5be819c134..6d523552b8 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 */ - var fresh: FreshNameCreator = new FreshNameCreator.Default + val 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 521f788fa1..11ee34af99 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 829e097714..577d28f5f6 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 6746b08155..daad704534 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 13bec828ca..8802c3ec80 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 */ - var printTypings = settings.Ytyperdebug.value - var printInfers = settings.Yinferdebug.value + val printTypings = settings.Ytyperdebug.value + val 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)] = { + def afterEachPhase[T](op: => T): List[(Phase, T)] = { // used in tests 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,9 +1181,8 @@ class Global(var currentSettings: Settings, var reporter: Reporter) val inlinerWarnings = new ConditionalWarning("inliner", settings.YinlinerWarnings) val allConditionalWarnings = List(deprecationWarnings0, uncheckedWarnings0, featureWarnings, inlinerWarnings) - // for sbt's benefit - def uncheckedWarnings: List[(Position, String)] = uncheckedWarnings0.warnings.toList - def deprecationWarnings: List[(Position, String)] = deprecationWarnings0.warnings.toList + def uncheckedWarnings: List[(Position, String)] = uncheckedWarnings0.warnings.toList // used in sbt + def deprecationWarnings: List[(Position, String)] = deprecationWarnings0.warnings.toList // used in sbt var reportedFeature = Set[Symbol]() @@ -1350,7 +1349,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") @@ -1363,7 +1362,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") @@ -1373,11 +1372,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. @@ -1743,7 +1742,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 3c75429311..e36e154925 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 aad70a9c5e..e81d3ebc8a 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 55fd196716..028fc24efb 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 0b307a861e..344a60903a 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 21407289db..40f97222a9 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 0414e0f123..d0aa004c9a 100644 --- a/src/compiler/scala/tools/nsc/ast/Printers.scala +++ b/src/compiler/scala/tools/nsc/ast/Printers.scala @@ -200,91 +200,17 @@ 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 3acefe9441..0696b0e673 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 = if (_mods == null) defaultMods else _mods + final def mods = defaultMods // 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 983f355c58..ea7f674809 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 97227a5b6e..5c1ab29548 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 efcde1f74f..501127865b 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala @@ -9,7 +9,8 @@ package scala.tools.nsc package ast.parser -import scala.collection.mutable.{ListBuffer, StringBuilder} +import scala.collection.{ mutable, immutable } +import mutable.{ ListBuffer, StringBuilder } import scala.reflect.internal.{ ModifierFlags => Flags } import scala.reflect.internal.Chars.{ isScalaLetter } import scala.reflect.internal.util.{ SourceFile, OffsetPosition } @@ -167,7 +168,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 @@ -463,7 +464,7 @@ self => /* ------------- ERROR HANDLING ------------------------------------------- */ - var assumedClosingParens = scala.collection.mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0) + val assumedClosingParens = mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0) private var inFunReturnType = false @inline private def fromWithinReturnType[T](body: => T): T = { @@ -640,7 +641,7 @@ self => case _ => false } - def isTypeIntro: Boolean = isTypeIntroToken(in.token) + // def isTypeIntro: Boolean = isTypeIntroToken(in.token) def isStatSeqEnd = in.token == RBRACE || in.token == EOF @@ -765,9 +766,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) @@ -1218,10 +1219,10 @@ self => * EqualsExpr ::= `=' Expr * }}} */ - def equalsExpr(): Tree = { - accept(EQUALS) - expr() - } + // def equalsExpr(): Tree = { + // accept(EQUALS) + // expr() + // } def condExpr(): Tree = { if (in.token == LPAREN) { @@ -1964,7 +1965,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 1be5fb1782..b346ce0a14 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala @@ -10,7 +10,8 @@ import scala.reflect.internal.util._ import scala.reflect.internal.Chars._ import Tokens._ import scala.annotation.switch -import scala.collection.mutable.{ ListBuffer, ArrayBuffer } +import scala.collection.{ mutable, immutable } +import mutable.{ ListBuffer, ArrayBuffer } import scala.xml.Utility.{ isNameStart } /** See Parsers.scala / ParsersCommon for some explanation of ScannersCommon. @@ -26,7 +27,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 @@ -51,7 +52,7 @@ trait Scanners extends ScannersCommon { type Offset = Int /** An undefined offset */ - val NoOffset: Offset = -1 + // val NoOffset: Offset = -1 trait TokenData extends CommonTokenData { @@ -88,7 +89,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 @@ -100,7 +101,7 @@ trait Scanners extends ScannersCommon { /** the last error offset */ - var errOffset: Offset = NoOffset + // var errOffset: Offset = NoOffset /** A character buffer for literals */ @@ -1063,7 +1064,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 @@ -1076,7 +1077,7 @@ trait Scanners extends ScannersCommon { def incompleteInputError(msg: String) { incompleteInputError(offset, msg) token = EOF - errOffset = offset + // errOffset = offset } override def toString() = token match { @@ -1241,7 +1242,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) @@ -1252,7 +1253,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) @@ -1311,7 +1312,7 @@ trait Scanners extends ScannersCommon { } class ParensAnalyzer(unit: CompilationUnit, patches: List[BracePatch]) extends UnitScanner(unit, patches) { - var balance = scala.collection.mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0) + val balance = mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0) init() @@ -1433,17 +1434,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 { @@ -1486,16 +1487,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 c3fd414426..be8e1bc8b4 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 49b772ed2c..6dc2055121 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 b62d5cb4e4..52fc3d08e1 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 f35996eeb9..e1732d5775 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 720896d0b3..d521f893d1 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 07abe9d74f..4192d794f9 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 0e7c75de50..6f7db042e6 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 - var hostClass: Symbol = method.owner; + val 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 c8579041ba..ebfb4ad591 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 e73015c4da..c8168cbfa6 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 f96dce9f1c..2df6811fd7 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 c1bf4304ea..c958f20853 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 53111d0ade..6534cd83f1 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 04c3eedbad..c232c3692a 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 15755f31ad..6e7ed9d4c4 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 8bae80c760..4a46a64dae 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 06f94ef46c..e258f38284 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 2253ae6e15..f7278a7590 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 */ - var currentHandlers = new mutable.Stack[ExceptionHandler] + val 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 8d6de821bb..b36e7a4636 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 7d741aab60..eaeba69382 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 62166f7def..d502f19e31 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 6b24073339..496dfdefcf 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 10e2f23142..0f2374a6f4 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 f11f090b4b..739a1b836d 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) - var memberSymsLazy = memberSyms.filter(t => templateShouldDocument(t, this) && !inOriginalOwner(t, this)) + val memberSymsLazy = memberSyms.filter(t => templateShouldDocument(t, this) && !inOriginalOwner(t, this)) // the direct members (methods, values, vars, types and directly contained templates) - var memberSymsEager = memberSyms.filter(!memberSymsLazy.contains(_)) + val 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 c1ca8c1448..e9c32b1af0 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 3e172544dd..4b75f3fd4d 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 9617b15068..7897421bd7 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 c2aa1f17f3..cb4659a71c 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) -} \ No newline at end of file + // def nodeDepth(node: Node) = _nodeDepth.getOrElse(node, -1) +} diff --git a/src/compiler/scala/tools/nsc/interactive/BuildManager.scala b/src/compiler/scala/tools/nsc/interactive/BuildManager.scala index a3f76994bc..921d4dc0e1 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 4dedbcfd3d..f71415450c 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 014661e525..42dad4c50d 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 1741a82775..a8eeee48b8 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 8042f0aee2..0b4ad1a29d 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 1dfccbfbf7..bf53fbb04b 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 3a0b48ef57..5b8a1791e4 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 13880bb8af..cddd7c930c 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 b5850d901c..0e3a2328a2 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 80debfacb9..f09c9a9557 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 ebd0030802..fbd0d15962 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala @@ -17,7 +17,8 @@ trait ExprTyper { import syntaxAnalyzer.UnitParser import naming.freshInternalVarName - object codeParser extends { val global: repl.global.type = repl.global } with CodeHandlers[Tree] { + object codeParser { + val global: repl.global.type = repl.global def applyRule[T](code: String, rule: UnitParser => T): T = { reporter.reset() val scanner = newUnitParser(code) @@ -29,10 +30,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 74549ef558..0e3dc3147b 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,20 +131,19 @@ 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.longHelp) + case Some(lc) => echo("\n" + lc.help) case _ => ambiguousError(line) } } private def helpSummary() = { val usageWidth = commands map (_.usageMsg.length) max - val formatStr = "%-" + usageWidth + "s %s %s" + val formatStr = "%-" + usageWidth + "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 => - val star = if (cmd.hasLongHelp) "*" else " " - echo(formatStr.format(cmd.usageMsg, star, cmd.help)) + echo(formatStr.format(cmd.usageMsg, cmd.help)) } } private def ambiguousError(cmd: String): Result = { @@ -194,10 +193,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) { @@ -208,8 +207,8 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) echo("%d %s".format(index + offset, line)) } - private var currentPrompt = Properties.shellPromptString - def setPrompt(prompt: String) = currentPrompt = prompt + private val currentPrompt = Properties.shellPromptString + // def setPrompt(prompt: String) = currentPrompt = prompt /** Prompt to print when awaiting input */ def prompt = currentPrompt @@ -684,7 +683,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)) @@ -704,21 +703,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) + def main(settings: Settings): Unit = process(settings) //used by sbt } object ILoop { diff --git a/src/compiler/scala/tools/nsc/interpreter/IMain.scala b/src/compiler/scala/tools/nsc/interpreter/IMain.scala index 0ef27ac96a..8ba6573e64 100644 --- a/src/compiler/scala/tools/nsc/interpreter/IMain.scala +++ b/src/compiler/scala/tools/nsc/interpreter/IMain.scala @@ -63,6 +63,7 @@ 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 @@ -82,20 +83,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 @@ -110,12 +111,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 } @@ -175,7 +176,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends } import global._ - import definitions.{ ObjectClass, termMember, typeMember, dropNullaryMethod} + import definitions.{ ObjectClass, termMember, dropNullaryMethod} lazy val runtimeMirror = ru.runtimeMirror(classLoader) @@ -189,13 +190,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) } @@ -211,7 +212,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._ @@ -310,11 +311,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 { @@ -354,7 +355,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() @@ -405,7 +406,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.") @@ -423,18 +424,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() @@ -653,17 +654,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() { @@ -719,7 +720,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) @@ -734,9 +735,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) { } @@ -749,7 +750,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) @@ -802,10 +803,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 @@ -817,7 +818,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) @@ -837,7 +838,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 @@ -931,7 +932,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))) @@ -1011,8 +1012,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)) @@ -1067,7 +1068,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) @@ -1075,67 +1076,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 302ba7a8ac..d45146383b 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 c5048ebfd8..978e220fab 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 6513381d77..a5f491fe6f 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() + def createDefault(): InteractiveReader = apply() // used by sbt } diff --git a/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala index 5ee5e5526d..5325c18710 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 e033bab03b..7f8beba32b 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 aeb25fc688..df3e90f0e2 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 60325ece30..168e611077 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 95482f1e46..6e564f4d17 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 eff0ef59c5..c10ba23691 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 0d03a8669a..57b1205fb3 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 24c01e9ae6..3d72e4b2a4 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 e6b780f177..3cf448f4c2 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 ab0f1c0033..88c20c5096 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 7cd0f436c4..d48ceb4eff 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 bc3e7a10d7..22c27513d3 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 670bbf9bae..ed035f8a1a 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 4371f7fe05..7183db2dfb 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,14 +20,13 @@ class RichClass[T](val clazz: Class[T]) { catch { case _: java.lang.InternalError => false } // good ol' "Malformed class name" ) - /** It's not easy... to be... me... */ - def supermans: List[ClassTag[_]] = supers map (_.toTag) + def supertags: 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 bccd8158ec..a07f84cc10 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 9fb79a9d6f..f9749feabe 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 6a2d69db2c..e6c9adb296 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 daa05b86db..b727a0494f 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 9f4e2b9df3..06e431fb30 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 7b4e385dd8..77d12ea022 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 ef2c9b13c0..6f1c322391 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 1a3a4f5c81..881af2e87a 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 56ff4a57ee..3f16784b2d 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 e766c1b2fd..cb264a671c 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 af745eb3e8..f6759be5eb 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 c29a7c96df..e9fb8a6d98 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 2f6c13dd67..63f08c42ec 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 e230585a8b..95a22f847b 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 a562de291d..90f73ec44a 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 5ce1aabcd8..07a79a174b 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 d2f5a98411..44387b59fb 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 ea4d9cd3f4..b5e25f3809 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 3ff5ce83bb..1aad24c2d6 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 e92c43f1fd..9cb91afb5b 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(elemtpt, elems) = tree + lazy val ArrayValue(_, 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(elem) = tree + // lazy val Star(_) = 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 e965370713..7b77613e2a 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) + def tryToSetFromPropertyValue(s: String): Unit = tryToSet(s :: Nil) // used in ide? /** 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 0bec113743..49b89392b9 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 -} \ No newline at end of file +// 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 +// } diff --git a/src/compiler/scala/tools/nsc/settings/MutableSettings.scala b/src/compiler/scala/tools/nsc/settings/MutableSettings.scala index 4f4f0544da..748c6069f0 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 = + def embeddedDefaults[T: ClassTag]: Unit = // called from sbt and repl 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 = + def add(srcDir: String, outDir: String): Unit = // used in ide? 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) { + override def tryToSetFromPropertyValue(s : String) { // used from ide 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) + override def tryToSetFromPropertyValue(s: String) = tryToSet(s.trim.split(',').toList) // used from ide 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) + override def tryToSetFromPropertyValue(s: String) = tryToSetColon(s::Nil) // used from ide withHelpSyntax(name + ":<" + helpArg + ">") } diff --git a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala index 8dce48ee9a..5074efbd01 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 e866ad6ae0..53d3557c67 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 d6d77278ab..d678fc60a8 100644 --- a/src/compiler/scala/tools/nsc/settings/Warnings.scala +++ b/src/compiler/scala/tools/nsc/settings/Warnings.scala @@ -39,9 +39,13 @@ 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 (_ => lintWarnings foreach (_.value = true)) + withPostSetHook { _ => + lint.value = true + allWarnings foreach (_.value = true) + } ) // Individual warnings. @@ -57,7 +61,7 @@ trait Warnings { val warnInferAny = BooleanSetting ("-Ywarn-infer-any", "Warn when a type argument is inferred to be `Any`.") // Backward compatibility. - def Xwarnfatal = fatalWarnings - def Xchecknull = warnSelectNullable - def Ywarndeadcode = warnDeadCode + def Xwarnfatal = fatalWarnings // used by sbt + // 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 427b5bf887..2d44d1e5f1 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 67f6c3ec5d..50a455b33f 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 b7511377cc..b5459ec773 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 { - 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() + 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 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 941604b154..324d62b662 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 78fb725041..0fe72c992e 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 2e0cc3bd98..798e604be4 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 b7da0e0087..f0414b8639 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 a8d7de6362..9ea1ff4263 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 79cd46e018..856043bca9 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 7d58155eb2..e5e52e91c3 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 576a21fe31..c17586335c 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 6aafd32237..bd37f055b7 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 28bed0f1bf..407749f833 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 252a738755..1588380bca 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 7cb420d2dc..27e539abbf 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 710adf5a9c..f1e6e48ccc 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 4f5291507e..ebeb8ef2c8 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 0a0ab53852..0a295febf3 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 bf44b65406..094b32673c 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 0c49b9b8e7..f82c504eb4 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 81c1b1d37a..2baab177b8 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 b7ed7903bc..a056a97a7c 100644 --- a/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala +++ b/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala @@ -17,46 +17,43 @@ 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: Boolean = if (bp < buf.length) true - else { - false - } + def hasNext = bp < buf.length - 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 @@ -66,8 +63,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 @@ -104,19 +101,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 a2994966fd..f09787ec4f 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 b103ae9cb0..a3b92aa2df 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 e9dcaa8e16..b40d3094f3 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 f0c88eadea..4fc3fede16 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 4d94581cc1..b80c65caa6 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 6b0821edf3..c88a8e13c4 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 = { + def fromPathString(path: String, context: JavaContext = DefaultJavaContext): JavaClassPath = { // called from scalap val s = new Settings() s.classpath.value = path new PathResolver(s, context) result @@ -160,7 +160,7 @@ object PathResolver { } } } -import PathResolver.{ Defaults, Environment, firstNonEmpty, ppcp } +import PathResolver.{ Defaults, Environment, ppcp } class PathResolver(settings: Settings, context: JavaContext) { def this(settings: Settings) = this(settings, if (settings.inline.value) new JavaContext else DefaultJavaContext) diff --git a/src/continuations/library/scala/util/continuations/ControlContext.scala b/src/continuations/library/scala/util/continuations/ControlContext.scala index 44a5b537b6..c196809da9 100644 --- a/src/continuations/library/scala/util/continuations/ControlContext.scala +++ b/src/continuations/library/scala/util/continuations/ControlContext.scala @@ -183,7 +183,7 @@ final class ControlContext[+A,-B,+C](val fun: (A => B, Exception => B) => C, val // need filter or other functions? - final def flatMapCatch[A1>:A,B1<:B,C1>:C<:B1](pf: PartialFunction[Exception, ControlContext[A1,B1,C1]]): ControlContext[A1,B1,C1] = { + final def flatMapCatch[A1>:A,B1<:B,C1>:C<:B1](pf: PartialFunction[Exception, ControlContext[A1,B1,C1]]): ControlContext[A1,B1,C1] = { // called by codegen from SelectiveCPSTransform if (fun eq null) this else { @@ -209,7 +209,7 @@ final class ControlContext[+A,-B,+C](val fun: (A => B, Exception => B) => C, val } } - final def mapFinally(f: () => Unit): ControlContext[A,B,C] = { + final def mapFinally(f: () => Unit): ControlContext[A,B,C] = { // called in code generated by SelectiveCPSTransform if (fun eq null) { try { f() diff --git a/src/continuations/library/scala/util/continuations/package.scala b/src/continuations/library/scala/util/continuations/package.scala index 1b50956c93..573fae85e7 100644 --- a/src/continuations/library/scala/util/continuations/package.scala +++ b/src/continuations/library/scala/util/continuations/package.scala @@ -166,7 +166,7 @@ package object continuations { throw new NoSuchMethodException("this code has to be compiled with the Scala continuations plugin enabled") } - def shiftUnitR[A,B](x: A): ControlContext[A,B,B] = { + def shiftUnitR[A,B](x: A): ControlContext[A,B,B] = { // called in code generated by SelectiveCPSTransform new ControlContext[A, B, B](null, x) } @@ -176,11 +176,11 @@ package object continuations { * a final result. * @see shift */ - def shiftR[A,B,C](fun: (A => B) => C): ControlContext[A,B,C] = { + def shiftR[A,B,C](fun: (A => B) => C): ControlContext[A,B,C] = { // called in code generated by SelectiveCPSTransform new ControlContext((f:A=>B,g:Exception=>B) => fun(f), null.asInstanceOf[A]) } - def reifyR[A,B,C](ctx: => ControlContext[A,B,C]): ControlContext[A,B,C] = { + def reifyR[A,B,C](ctx: => ControlContext[A,B,C]): ControlContext[A,B,C] = { // called in code generated by SelectiveCPSTransform ctx } diff --git a/src/detach/plugin/scala/tools/detach/Detach.scala b/src/detach/plugin/scala/tools/detach/Detach.scala index 73f6cde58c..499a97b761 100644 --- a/src/detach/plugin/scala/tools/detach/Detach.scala +++ b/src/detach/plugin/scala/tools/detach/Detach.scala @@ -73,7 +73,7 @@ abstract class Detach extends PluginComponent } private val serializableAnnotationInfo = - AnnotationInfo(SerializableAttr.tpe, List(), List()) + AnnotationInfo(requiredClass[scala.annotation.serializable].tpe, List(), List()) /* private val throwsAnnotationInfo = { val RemoteExceptionClass = definitions.getClass("java.rmi.RemoteException") diff --git a/src/partest/scala/tools/partest/CompilerTest.scala b/src/partest/scala/tools/partest/CompilerTest.scala index d73d99bc89..bb0732dcc6 100644 --- a/src/partest/scala/tools/partest/CompilerTest.scala +++ b/src/partest/scala/tools/partest/CompilerTest.scala @@ -21,7 +21,7 @@ abstract class CompilerTest extends DirectTest { lazy val global: Global = newCompiler() lazy val units = compilationUnits(global)(sources: _ *) import global._ - import definitions._ + import definitions.{ compilerTypeFromTag } override def extraSettings = "-usejavacp -d " + testOutput.path @@ -32,7 +32,6 @@ abstract class CompilerTest extends DirectTest { def sources: List[String] = List(code) // Utility functions - class MkType(sym: Symbol) { def apply[M](implicit t: ru.TypeTag[M]): Type = if (sym eq NoSymbol) NoType diff --git a/src/partest/scala/tools/partest/SecurityTest.scala b/src/partest/scala/tools/partest/SecurityTest.scala index 2d6f61d0b1..8d57e7e38d 100644 --- a/src/partest/scala/tools/partest/SecurityTest.scala +++ b/src/partest/scala/tools/partest/SecurityTest.scala @@ -11,8 +11,8 @@ import java.util._ abstract class SecurityTest extends App { def throwIt(x: Any) = throw new AccessControlException("" + x) - def readPerm(p: PropertyPermission) = p.getActions contains "read" - def writePerm(p: PropertyPermission) = p.getActions contains "write" + // def readPerm(p: PropertyPermission) = p.getActions contains "read" + // def writePerm(p: PropertyPermission) = p.getActions contains "write" def propertyCheck(p: PropertyPermission): Unit = throwIt(p) def check(perm: Permission): Unit = perm match { @@ -20,13 +20,13 @@ abstract class SecurityTest extends App { case _ => () } - lazy val sm = new SecurityManager { - // these two are the choke points for all permissions checks - override def checkPermission(perm: Permission): Unit = check(perm) - override def checkPermission(perm: Permission, context: Object): Unit = check(perm) - } - def securityOn(): Boolean = { - try { System.setSecurityManager(sm) ; true } - catch { case _: SecurityException => false } - } + // lazy val sm = new SecurityManager { + // // these two are the choke points for all permissions checks + // override def checkPermission(perm: Permission): Unit = check(perm) + // override def checkPermission(perm: Permission, context: Object): Unit = check(perm) + // } + // def securityOn(): Boolean = { + // try { System.setSecurityManager(sm) ; true } + // catch { case _: SecurityException => false } + // } } diff --git a/src/partest/scala/tools/partest/TestUtil.scala b/src/partest/scala/tools/partest/TestUtil.scala index 9bfd444180..bd5dc39498 100644 --- a/src/partest/scala/tools/partest/TestUtil.scala +++ b/src/partest/scala/tools/partest/TestUtil.scala @@ -24,13 +24,13 @@ trait TestUtil { } def nanos(body: => Unit): Long = alsoNanos(body)._1 - def verifySpeed(body1: => Unit, body2: => Unit, acceptableMultiple: Double) = { - val t1 = nanos(body1).toDouble - val t2 = nanos(body2).toDouble - val mult = if (t1 > t2) t1 / t2 else t2 / t1 + // def verifySpeed(body1: => Unit, body2: => Unit, acceptableMultiple: Double) = { + // val t1 = nanos(body1).toDouble + // val t2 = nanos(body2).toDouble + // val mult = if (t1 > t2) t1 / t2 else t2 / t1 - assert(mult <= acceptableMultiple, "Performance difference too great: multiple = " + mult) - } + // assert(mult <= acceptableMultiple, "Performance difference too great: multiple = " + mult) + // } def intercept[T <: Exception : ClassTag](code: => Unit): Unit = try { @@ -41,6 +41,6 @@ trait TestUtil { } } +// Used in tests. object TestUtil extends TestUtil { - } diff --git a/src/partest/scala/tools/partest/instrumented/Instrumentation.scala b/src/partest/scala/tools/partest/instrumented/Instrumentation.scala index 8a284b313b..18dd740208 100644 --- a/src/partest/scala/tools/partest/instrumented/Instrumentation.scala +++ b/src/partest/scala/tools/partest/instrumented/Instrumentation.scala @@ -78,6 +78,7 @@ object Instrumentation { !t.className.startsWith("scala/util/DynamicVariable") } + // Used in tests. def printStatistics(stats: Statistics = getStatistics, filter: MethodCallTrace => Boolean = standardFilter): Unit = { val stats = getStatistics println("Method call statistics:") diff --git a/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala b/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala index 75aed449a8..d8ae4b2403 100644 --- a/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala +++ b/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala @@ -79,7 +79,7 @@ class ConsoleFileManager extends FileManager { testClassesDir = Path(testClasses.get).toCanonical.toDirectory NestUI.verbose("Running with classes in "+testClassesDir) - latestFile = testClassesDir.parent / "bin" + // latestFile = testClassesDir.parent / "bin" latestLibFile = testClassesDir / "library" latestActorsFile = testClassesDir / "library" / "actors" latestReflectFile = testClassesDir / "reflect" @@ -90,7 +90,7 @@ class ConsoleFileManager extends FileManager { else if (testBuild.isDefined) { val dir = Path(testBuild.get) NestUI.verbose("Running on "+dir) - latestFile = dir / "bin" + // latestFile = dir / "bin" latestLibFile = dir / "lib/scala-library.jar" latestActorsFile = dir / "lib/scala-actors.jar" latestReflectFile = dir / "lib/scala-reflect.jar" @@ -101,7 +101,7 @@ class ConsoleFileManager extends FileManager { else { def setupQuick() { NestUI.verbose("Running build/quick") - latestFile = prefixFile("build/quick/bin") + // latestFile = prefixFile("build/quick/bin") latestLibFile = prefixFile("build/quick/classes/library") latestActorsFile = prefixFile("build/quick/classes/library/actors") latestReflectFile = prefixFile("build/quick/classes/reflect") @@ -112,7 +112,7 @@ class ConsoleFileManager extends FileManager { def setupInst() { NestUI.verbose("Running dist (installed)") val p = testParent.getParentFile - latestFile = prefixFileWith(p, "bin") + // latestFile = prefixFileWith(p, "bin") latestLibFile = prefixFileWith(p, "lib/scala-library.jar") latestActorsFile = prefixFileWith(p, "lib/scala-actors.jar") latestReflectFile = prefixFileWith(p, "lib/scala-reflect.jar") @@ -122,7 +122,7 @@ class ConsoleFileManager extends FileManager { def setupDist() { NestUI.verbose("Running dists/latest") - latestFile = prefixFile("dists/latest/bin") + // latestFile = prefixFile("dists/latest/bin") latestLibFile = prefixFile("dists/latest/lib/scala-library.jar") latestActorsFile = prefixFile("dists/latest/lib/scala-actors.jar") latestReflectFile = prefixFile("dists/latest/lib/scala-reflect.jar") @@ -132,7 +132,7 @@ class ConsoleFileManager extends FileManager { def setupPack() { NestUI.verbose("Running build/pack") - latestFile = prefixFile("build/pack/bin") + // latestFile = prefixFile("build/pack/bin") latestLibFile = prefixFile("build/pack/lib/scala-library.jar") latestActorsFile = prefixFile("build/pack/lib/scala-actors.jar") latestReflectFile = prefixFile("build/pack/lib/scala-reflect.jar") @@ -175,7 +175,7 @@ class ConsoleFileManager extends FileManager { var LATEST_PARTEST: String = "" var LATEST_ACTORS: String = "" - var latestFile: File = _ + // var latestFile: File = _ var latestLibFile: File = _ var latestActorsFile: File = _ var latestReflectFile: File = _ @@ -187,7 +187,7 @@ class ConsoleFileManager extends FileManager { // initialize above fields findLatest() - var testFiles: List[io.Path] = Nil + // var testFiles: List[io.Path] = Nil def getFiles(kind: String, cond: Path => Boolean): List[File] = { def ignoreDir(p: Path) = List("svn", "obj") exists (p hasExtension _) @@ -197,9 +197,7 @@ class ConsoleFileManager extends FileManager { if (dir.isDirectory) NestUI.verbose("look in %s for tests" format dir) else NestUI.failure("Directory '%s' not found" format dir) - val files = - if (testFiles.nonEmpty) testFiles filter (_.parent isSame dir) - else dir.list filterNot ignoreDir filter cond toList + val files = dir.list filterNot ignoreDir filter cond toList ( if (failed) files filter (x => logFileExists(x, kind)) else files ) map (_.jfile) } diff --git a/src/partest/scala/tools/partest/nest/ConsoleRunner.scala b/src/partest/scala/tools/partest/nest/ConsoleRunner.scala index d23ee81e4d..35bce01684 100644 --- a/src/partest/scala/tools/partest/nest/ConsoleRunner.scala +++ b/src/partest/scala/tools/partest/nest/ConsoleRunner.scala @@ -51,7 +51,7 @@ class ConsoleRunner extends DirectRunner { private val testSetArgs = testSets map ("--" + _.kind) private val testSetArgMap = testSetArgs zip testSets toMap - def denotesTestSet(arg: String) = testSetArgs contains arg + // def denotesTestSet(arg: String) = testSetArgs contains arg private def printVersion() { NestUI outline (versionMsg + "\n") } diff --git a/src/partest/scala/tools/partest/nest/FileManager.scala b/src/partest/scala/tools/partest/nest/FileManager.scala index 21fd314552..9e2a34a34e 100644 --- a/src/partest/scala/tools/partest/nest/FileManager.scala +++ b/src/partest/scala/tools/partest/nest/FileManager.scala @@ -74,15 +74,15 @@ trait FileManager extends FileUtil { var timeout = PartestDefaults.timeout // how can 15 minutes not be enough? What are you doing, run/lisp.scala? // You complete in 11 seconds on my machine. - var oneTestTimeout = 60 * 60 * 1000 + // var oneTestTimeout = 60 * 60 * 1000 /** Only when --debug is given. */ lazy val testTimings = new mutable.HashMap[String, Long] def recordTestTiming(name: String, milliseconds: Long) = synchronized { testTimings(name) = milliseconds } - def showTestTimings() { - testTimings.toList sortBy (-_._2) foreach { case (k, v) => println("%s: %s".format(k, v)) } - } + // def showTestTimings() { + // testTimings.toList sortBy (-_._2) foreach { case (k, v) => println("%s: %s".format(k, v)) } + // } def getLogFile(dir: File, fileBase: String, kind: String): File = new File(dir, fileBase + "-" + kind + ".log") diff --git a/src/partest/scala/tools/partest/nest/NestUI.scala b/src/partest/scala/tools/partest/nest/NestUI.scala index 70db6d0ed1..00aa27bd34 100644 --- a/src/partest/scala/tools/partest/nest/NestUI.scala +++ b/src/partest/scala/tools/partest/nest/NestUI.scala @@ -54,9 +54,9 @@ object NestUI { } def warning(msg: String) = print(_warning + msg + _default) - def warning(msg: String, wr: PrintWriter) = synchronized { - wr.print(_warning + msg + _default) - } + // def warning(msg: String, wr: PrintWriter) = synchronized { + // wr.print(_warning + msg + _default) + // } def normal(msg: String) = print(_default + msg) def normal(msg: String, wr: PrintWriter) = synchronized { @@ -104,7 +104,7 @@ object NestUI { } var _verbose = false - var _debug = false + // var _debug = false def verbose(msg: String) { if (_verbose) { @@ -112,10 +112,10 @@ object NestUI { println(msg) } } - def debug(msg: String) { - if (isPartestDebug) { - outline("debug: ") - println(msg) - } - } + // def debug(msg: String) { + // if (isPartestDebug) { + // outline("debug: ") + // println(msg) + // } + // } } diff --git a/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala b/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala index 5cb8589d66..4b0ed1f82a 100644 --- a/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala +++ b/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala @@ -3,8 +3,6 @@ * @author Philipp Haller */ -// $Id$ - package scala.tools.partest package nest @@ -12,7 +10,6 @@ import scala.tools.nsc.Properties.{ setProp, propOrEmpty } import scala.tools.nsc.util.ClassPath import scala.tools.nsc.io import io.Path -import RunnerUtils._ import java.net.URLClassLoader /* This class is used to load an instance of DirectRunner using @@ -28,6 +25,12 @@ class ReflectiveRunner { // was used to start the runner. val sepRunnerClassName = "scala.tools.partest.nest.ConsoleRunner" + private def searchPath(option: String, as: List[String]): Option[String] = as match { + case `option` :: r :: _ => Some(r) + case _ :: rest => searchPath(option, rest) + case Nil => None + } + def main(args: String) { val argList = (args.split("\\s")).toList diff --git a/src/partest/scala/tools/partest/nest/RunnerManager.scala b/src/partest/scala/tools/partest/nest/RunnerManager.scala index 548c5abbd9..2651088018 100644 --- a/src/partest/scala/tools/partest/nest/RunnerManager.scala +++ b/src/partest/scala/tools/partest/nest/RunnerManager.scala @@ -291,10 +291,10 @@ class RunnerManager(kind: String, val fileManager: FileManager, params: TestRunP ((swr, wr)) } - def fail(what: Any) = { - NestUI.verbose("scalac: compilation of "+what+" failed\n") - false - } + // def fail(what: Any) = { + // NestUI.verbose("scalac: compilation of "+what+" failed\n") + // false + // } def diffCheck(testFile: File, diff: String) = { testDiff = diff testDiff == "" diff --git a/src/partest/scala/tools/partest/nest/RunnerUtils.scala b/src/partest/scala/tools/partest/nest/RunnerUtils.scala index 6707a9338a..8a47989b7c 100644 --- a/src/partest/scala/tools/partest/nest/RunnerUtils.scala +++ b/src/partest/scala/tools/partest/nest/RunnerUtils.scala @@ -1,29 +1,29 @@ -/* NEST (New Scala Test) - * Copyright 2007-2013 LAMP/EPFL - * @author Philipp Haller - */ +// /* NEST (New Scala Test) +// * Copyright 2007-2013 LAMP/EPFL +// * @author Philipp Haller +// */ -// $Id$ +// // $Id$ -package scala.tools.partest -package nest +// package scala.tools.partest +// package nest -object RunnerUtils { - def splitArgs(str: String) = str split "\\s" filterNot (_ == "") toList +// object RunnerUtils { +// def splitArgs(str: String) = str split "\\s" filterNot (_ == "") toList - def searchPath(option: String, as: List[String]): Option[String] = as match { - case `option` :: r :: _ => Some(r) - case _ :: rest => searchPath(option, rest) - case Nil => None - } +// def searchPath(option: String, as: List[String]): Option[String] = as match { +// case `option` :: r :: _ => Some(r) +// case _ :: rest => searchPath(option, rest) +// case Nil => None +// } - def searchAndRemovePath(option: String, as: List[String]) = (as indexOf option) match { - case -1 => (None, as) - case idx => (Some(as(idx + 1)), (as take idx) ::: (as drop (idx + 2))) - } +// def searchAndRemovePath(option: String, as: List[String]) = (as indexOf option) match { +// case -1 => (None, as) +// case idx => (Some(as(idx + 1)), (as take idx) ::: (as drop (idx + 2))) +// } - def searchAndRemoveOption(option: String, as: List[String]) = (as indexOf option) match { - case -1 => (false, as) - case idx => (true, (as take idx) ::: (as drop (idx + 1))) - } -} +// def searchAndRemoveOption(option: String, as: List[String]) = (as indexOf option) match { +// case -1 => (false, as) +// case idx => (true, (as take idx) ::: (as drop (idx + 1))) +// } +// } diff --git a/src/partest/scala/tools/partest/package.scala b/src/partest/scala/tools/partest/package.scala index 58cc7d5b0b..fa0c88a2b2 100644 --- a/src/partest/scala/tools/partest/package.scala +++ b/src/partest/scala/tools/partest/package.scala @@ -13,9 +13,9 @@ import java.util.concurrent.Callable package partest { class TestState { - def isOk = this eq TestState.Ok - def isFail = this eq TestState.Fail - def isTimeout = this eq TestState.Timeout + // def isOk = this eq TestState.Ok + // def isFail = this eq TestState.Fail + // def isTimeout = this eq TestState.Timeout } object TestState { val Ok = new TestState @@ -43,7 +43,7 @@ package object partest { def callable[T](body: => T): Callable[T] = new Callable[T] { override def call() = body } - def path2String(path: String) = file2String(new JFile(path)) + // def path2String(path: String) = file2String(new JFile(path)) def file2String(f: JFile) = try SFile(f).slurp(scala.io.Codec.UTF8) catch { case _: FileNotFoundException => "" } diff --git a/src/partest/scala/tools/partest/utils/PrintMgr.scala b/src/partest/scala/tools/partest/utils/PrintMgr.scala index d25be87c1e..56fdcda2ea 100644 --- a/src/partest/scala/tools/partest/utils/PrintMgr.scala +++ b/src/partest/scala/tools/partest/utils/PrintMgr.scala @@ -1,52 +1,52 @@ -/* __ *\ -** ________ ___ / / ___ Scala Parallel Testing ** -** / __/ __// _ | / / / _ | (c) 2007-2013, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.tools.partest -package utils - -/** - * @author Thomas Hofer - */ -object PrintMgr { - - val NONE = 0 - val SOME = 1 - val MANY = 2 - - var outline = "" - var success = "" - var failure = "" - var warning = "" - var default = "" - - def initialization(number: Int) = number match { - case MANY => - outline = Console.BOLD + Console.BLACK - success = Console.BOLD + Console.GREEN - failure = Console.BOLD + Console.RED - warning = Console.BOLD + Console.YELLOW - default = Console.RESET - case SOME => - outline = Console.BOLD + Console.BLACK - success = Console.RESET - failure = Console.BOLD + Console.BLACK - warning = Console.BOLD + Console.BLACK - default = Console.RESET - case _ => - } - - def printOutline(msg: String) = print(outline + msg + default) - - def printSuccess(msg: String) = print(success + msg + default) - - def printFailure(msg: String) = print(failure + msg + default) - - def printWarning(msg: String) = print(warning + msg + default) -} +// /* __ *\ +// ** ________ ___ / / ___ Scala Parallel Testing ** +// ** / __/ __// _ | / / / _ | (c) 2007-2013, LAMP/EPFL ** +// ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +// ** /____/\___/_/ |_/____/_/ | | ** +// ** |/ ** +// \* */ + +// // $Id$ + +// package scala.tools.partest +// package utils + +// /** +// * @author Thomas Hofer +// */ +// object PrintMgr { + +// val NONE = 0 +// val SOME = 1 +// val MANY = 2 + +// var outline = "" +// var success = "" +// var failure = "" +// var warning = "" +// var default = "" + +// def initialization(number: Int) = number match { +// case MANY => +// outline = Console.BOLD + Console.BLACK +// success = Console.BOLD + Console.GREEN +// failure = Console.BOLD + Console.RED +// warning = Console.BOLD + Console.YELLOW +// default = Console.RESET +// case SOME => +// outline = Console.BOLD + Console.BLACK +// success = Console.RESET +// failure = Console.BOLD + Console.BLACK +// warning = Console.BOLD + Console.BLACK +// default = Console.RESET +// case _ => +// } + +// def printOutline(msg: String) = print(outline + msg + default) + +// def printSuccess(msg: String) = print(success + msg + default) + +// def printFailure(msg: String) = print(failure + msg + default) + +// def printWarning(msg: String) = print(warning + msg + default) +// } diff --git a/src/reflect/scala/reflect/internal/AnnotationInfos.scala b/src/reflect/scala/reflect/internal/AnnotationInfos.scala index 7c12b5979d..82be2fa04a 100644 --- a/src/reflect/scala/reflect/internal/AnnotationInfos.scala +++ b/src/reflect/scala/reflect/internal/AnnotationInfos.scala @@ -6,7 +6,6 @@ package scala.reflect package internal -import util._ import pickling.ByteCodecs import scala.annotation.tailrec import scala.collection.immutable.ListMap @@ -289,8 +288,8 @@ trait AnnotationInfos extends api.Annotations { self: SymbolTable => def refsSymbol(sym: Symbol) = hasArgWhich(_.symbol == sym) /** Change all ident's with Symbol "from" to instead use symbol "to" */ - def substIdentSyms(from: Symbol, to: Symbol) = - AnnotationInfo(atp, args map (_ substituteSymbols (List(from), List(to))), assocs) setPos pos + // def substIdentSyms(from: Symbol, to: Symbol) = + // AnnotationInfo(atp, args map (_ substituteSymbols (List(from), List(to))), assocs) setPos pos def stringArg(index: Int) = constantAtIndex(index) map (_.stringValue) def intArg(index: Int) = constantAtIndex(index) map (_.intValue) @@ -325,14 +324,14 @@ trait AnnotationInfos extends api.Annotations { self: SymbolTable => implicit val AnnotationTag = ClassTag[AnnotationInfo](classOf[AnnotationInfo]) object UnmappableAnnotation extends CompleteAnnotationInfo(NoType, Nil, Nil) - + /** Extracts symbol of thrown exception from AnnotationInfo. - * + * * Supports both “old-style” `@throws(classOf[Exception])` * as well as “new-stye” `@throws[Exception]("cause")` annotations. */ object ThrownException { - def unapply(ann: AnnotationInfo): Option[Symbol] = + def unapply(ann: AnnotationInfo): Option[Symbol] = ann match { case AnnotationInfo(tpe, _, _) if tpe.typeSymbol != ThrowsClass => None diff --git a/src/reflect/scala/reflect/internal/BuildUtils.scala b/src/reflect/scala/reflect/internal/BuildUtils.scala index 9f41f0336e..9da6ad652a 100644 --- a/src/reflect/scala/reflect/internal/BuildUtils.scala +++ b/src/reflect/scala/reflect/internal/BuildUtils.scala @@ -1,8 +1,6 @@ package scala.reflect package internal -import Flags._ - trait BuildUtils { self: SymbolTable => class BuildImpl extends BuildApi { diff --git a/src/reflect/scala/reflect/internal/ClassfileConstants.scala b/src/reflect/scala/reflect/internal/ClassfileConstants.scala index b1462e9709..c8af1732a9 100644 --- a/src/reflect/scala/reflect/internal/ClassfileConstants.scala +++ b/src/reflect/scala/reflect/internal/ClassfileConstants.scala @@ -381,10 +381,10 @@ object ClassfileConstants { def toScalaClassFlags(flags: Int): Long = FlagTranslation classFlags flags def toScalaFieldFlags(flags: Int): Long = FlagTranslation fieldFlags flags - @deprecated("Use another method in this object", "2.10.0") - def toScalaFlags(flags: Int, isClass: Boolean = false, isField: Boolean = false): Long = ( - if (isClass) toScalaClassFlags(flags) - else if (isField) toScalaFieldFlags(flags) - else toScalaMethodFlags(flags) - ) + // @deprecated("Use another method in this object", "2.10.0") + // def toScalaFlags(flags: Int, isClass: Boolean = false, isField: Boolean = false): Long = ( + // if (isClass) toScalaClassFlags(flags) + // else if (isField) toScalaFieldFlags(flags) + // else toScalaMethodFlags(flags) + // ) } diff --git a/src/reflect/scala/reflect/internal/Definitions.scala b/src/reflect/scala/reflect/internal/Definitions.scala index 9a358cec46..8ecb189c27 100644 --- a/src/reflect/scala/reflect/internal/Definitions.scala +++ b/src/reflect/scala/reflect/internal/Definitions.scala @@ -9,7 +9,6 @@ package internal import scala.annotation.{ switch, meta } import scala.collection.{ mutable, immutable } import Flags._ -import PartialFunction._ import scala.reflect.api.{Universe => ApiUniverse} trait Definitions extends api.StandardDefinitions { @@ -149,7 +148,7 @@ trait Definitions extends api.StandardDefinitions { FloatClass, DoubleClass ) - def ScalaValueClassCompanions: List[Symbol] = ScalaValueClasses map (_.companionSymbol) + // def ScalaValueClassCompanions: List[Symbol] = ScalaValueClasses map (_.companionSymbol) def ScalaPrimitiveValueClasses: List[ClassSymbol] = ScalaValueClasses } @@ -158,7 +157,7 @@ trait Definitions extends api.StandardDefinitions { def isDefinitionsInitialized = isInitialized // symbols related to packages - var emptypackagescope: Scope = null //debug + // var emptypackagescope: Scope = null //debug @deprecated("Moved to rootMirror.RootPackage", "2.10.0") val RootPackage: ModuleSymbol = rootMirror.RootPackage @@ -181,7 +180,7 @@ trait Definitions extends api.StandardDefinitions { lazy val RuntimePackage = getRequiredPackage("scala.runtime") lazy val RuntimePackageClass = RuntimePackage.moduleClass.asClass - lazy val JavaLangEnumClass = requiredClass[java.lang.Enum[_]] + // lazy val JavaLangEnumClass = requiredClass[java.lang.Enum[_]] // convenient one-argument parameter lists lazy val anyparam = List(AnyClass.tpe) @@ -262,7 +261,7 @@ trait Definitions extends api.StandardDefinitions { || tp =:= AnyRefClass.tpe ) /** Does this type have a parent which is none of Any, AnyVal, or AnyRef? */ - def hasNonTrivialParent(tp: Type) = tp.parents exists (t => !isTrivialTopType(tp)) + // def hasNonTrivialParent(tp: Type) = tp.parents exists (t => !isTrivialTopType(tp)) private def fixupAsAnyTrait(tpe: Type): Type = tpe match { case ClassInfoType(parents, decls, clazz) => @@ -358,11 +357,11 @@ trait Definitions extends api.StandardDefinitions { lazy val UnqualifiedOwners = UnqualifiedModules.toSet ++ UnqualifiedModules.map(_.moduleClass) lazy val PredefModule = requiredModule[scala.Predef.type] - lazy val PredefModuleClass = PredefModule.moduleClass + // lazy val PredefModuleClass = PredefModule.moduleClass def Predef_classOf = getMemberMethod(PredefModule, nme.classOf) - def Predef_identity = getMemberMethod(PredefModule, nme.identity) - def Predef_conforms = getMemberMethod(PredefModule, nme.conforms) + // def Predef_identity = getMemberMethod(PredefModule, nme.identity) + // def Predef_conforms = getMemberMethod(PredefModule, nme.conforms) def Predef_wrapRefArray = getMemberMethod(PredefModule, nme.wrapRefArray) def Predef_wrapArray(tp: Type) = getMemberMethod(PredefModule, wrapArrayMethodName(tp)) def Predef_??? = getMemberMethod(PredefModule, nme.???) @@ -382,7 +381,7 @@ trait Definitions extends api.StandardDefinitions { lazy val SpecializableModule = requiredModule[Specializable] lazy val GroupOfSpecializable = getMemberClass(SpecializableModule, tpnme.Group) - lazy val ConsoleModule = requiredModule[scala.Console.type] + // lazy val ConsoleModule = requiredModule[scala.Console.type] lazy val ScalaRunTimeModule = requiredModule[scala.runtime.ScalaRunTime.type] lazy val SymbolModule = requiredModule[scala.Symbol.type] lazy val Symbol_apply = getMemberMethod(SymbolModule, nme.apply) @@ -392,9 +391,9 @@ trait Definitions extends api.StandardDefinitions { def arrayLengthMethod = getMemberMethod(ScalaRunTimeModule, nme.array_length) def arrayCloneMethod = getMemberMethod(ScalaRunTimeModule, nme.array_clone) def ensureAccessibleMethod = getMemberMethod(ScalaRunTimeModule, nme.ensureAccessible) - def scalaRuntimeSameElements = getMemberMethod(ScalaRunTimeModule, nme.sameElements) + // def scalaRuntimeSameElements = getMemberMethod(ScalaRunTimeModule, nme.sameElements) def arrayClassMethod = getMemberMethod(ScalaRunTimeModule, nme.arrayClass) - def arrayElementClassMethod = getMemberMethod(ScalaRunTimeModule, nme.arrayElementClass) + // def arrayElementClassMethod = getMemberMethod(ScalaRunTimeModule, nme.arrayElementClass) // classes with special meanings lazy val StringAddClass = requiredClass[scala.runtime.StringAdd] @@ -457,10 +456,10 @@ trait Definitions extends api.StandardDefinitions { case _ => tp } - def isPrimitiveArray(tp: Type) = tp match { - case TypeRef(_, ArrayClass, arg :: Nil) => isPrimitiveValueClass(arg.typeSymbol) - case _ => false - } + // def isPrimitiveArray(tp: Type) = tp match { + // case TypeRef(_, ArrayClass, arg :: Nil) => isPrimitiveValueClass(arg.typeSymbol) + // case _ => false + // } def isReferenceArray(tp: Type) = tp match { case TypeRef(_, ArrayClass, arg :: Nil) => arg <:< AnyRefClass.tpe case _ => false @@ -470,11 +469,11 @@ trait Definitions extends api.StandardDefinitions { case _ => false } - lazy val MatchingStrategyClass = getRequiredClass("scala.MatchingStrategy") + // lazy val MatchingStrategyClass = getRequiredClass("scala.MatchingStrategy") // collections classes lazy val ConsClass = requiredClass[scala.collection.immutable.::[_]] - lazy val IterableClass = requiredClass[scala.collection.Iterable[_]] + // lazy val IterableClass = requiredClass[scala.collection.Iterable[_]] lazy val IteratorClass = requiredClass[scala.collection.Iterator[_]] lazy val ListClass = requiredClass[scala.collection.immutable.List[_]] lazy val SeqClass = requiredClass[scala.collection.Seq[_]] @@ -485,8 +484,8 @@ trait Definitions extends api.StandardDefinitions { lazy val List_apply = getMemberMethod(ListModule, nme.apply) lazy val NilModule = requiredModule[scala.collection.immutable.Nil.type] lazy val SeqModule = requiredModule[scala.collection.Seq.type] - lazy val IteratorModule = requiredModule[scala.collection.Iterator.type] - lazy val Iterator_apply = getMemberMethod(IteratorModule, nme.apply) + // lazy val IteratorModule = requiredModule[scala.collection.Iterator.type] + // lazy val Iterator_apply = getMemberMethod(IteratorModule, nme.apply) // arrays and their members lazy val ArrayModule = requiredModule[scala.Array.type] @@ -501,9 +500,9 @@ trait Definitions extends api.StandardDefinitions { // reflection / structural types lazy val SoftReferenceClass = requiredClass[java.lang.ref.SoftReference[_]] - lazy val WeakReferenceClass = requiredClass[java.lang.ref.WeakReference[_]] + // lazy val WeakReferenceClass = requiredClass[java.lang.ref.WeakReference[_]] lazy val MethodClass = getClassByName(sn.MethodAsObject) - def methodClass_setAccessible = getMemberMethod(MethodClass, nme.setAccessible) + // def methodClass_setAccessible = getMemberMethod(MethodClass, nme.setAccessible) lazy val EmptyMethodCacheClass = requiredClass[scala.runtime.EmptyMethodCache] lazy val MethodCacheClass = requiredClass[scala.runtime.MethodCache] def methodCache_find = getMemberMethod(MethodCacheClass, nme.find_) @@ -527,7 +526,7 @@ trait Definitions extends api.StandardDefinitions { lazy val ExprClass = if (ExprsClass != NoSymbol) getMemberClass(ExprsClass, tpnme.Expr) else NoSymbol def ExprSplice = if (ExprsClass != NoSymbol) getMemberMethod(ExprClass, nme.splice) else NoSymbol def ExprValue = if (ExprsClass != NoSymbol) getMemberMethod(ExprClass, nme.value) else NoSymbol - lazy val ExprModule = if (ExprsClass != NoSymbol) getMemberModule(ExprsClass, nme.Expr) else NoSymbol + // lazy val ExprModule = if (ExprsClass != NoSymbol) getMemberModule(ExprsClass, nme.Expr) else NoSymbol lazy val ClassTagModule = requiredModule[scala.reflect.ClassTag[_]] lazy val ClassTagClass = requiredClass[scala.reflect.ClassTag[_]] @@ -553,7 +552,7 @@ trait Definitions extends api.StandardDefinitions { def MacroContextPrefix = if (MacroContextClass != NoSymbol) getMemberMethod(MacroContextClass, nme.prefix) else NoSymbol def MacroContextPrefixType = if (MacroContextClass != NoSymbol) getTypeMember(MacroContextClass, tpnme.PrefixType) else NoSymbol def MacroContextUniverse = if (MacroContextClass != NoSymbol) getMemberMethod(MacroContextClass, nme.universe) else NoSymbol - def MacroContextMirror = if (MacroContextClass != NoSymbol) getMemberMethod(MacroContextClass, nme.mirror) else NoSymbol + // def MacroContextMirror = if (MacroContextClass != NoSymbol) getMemberMethod(MacroContextClass, nme.mirror) else NoSymbol lazy val MacroImplAnnotation = requiredClass[scala.reflect.macros.internal.macroImpl] lazy val StringContextClass = requiredClass[scala.StringContext] @@ -585,12 +584,12 @@ trait Definitions extends api.StandardDefinitions { // The given class has a main method. def hasJavaMainMethod(sym: Symbol): Boolean = (sym.tpe member nme.main).alternatives exists isJavaMainMethod - def hasJavaMainMethod(path: String): Boolean = - hasJavaMainMethod(getModuleIfDefined(path)) + // def hasJavaMainMethod(path: String): Boolean = + // hasJavaMainMethod(getModuleIfDefined(path)) - def isOptionType(tp: Type) = tp.typeSymbol isSubClass OptionClass - def isSomeType(tp: Type) = tp.typeSymbol eq SomeClass - def isNoneType(tp: Type) = tp.typeSymbol eq NoneModule + // def isOptionType(tp: Type) = tp.typeSymbol isSubClass OptionClass + // def isSomeType(tp: Type) = tp.typeSymbol eq SomeClass + // def isNoneType(tp: Type) = tp.typeSymbol eq NoneModule // Product, Tuple, Function, AbstractFunction private def mkArityArray(name: String, arity: Int, countFrom: Int): Array[ClassSymbol] = { @@ -613,7 +612,7 @@ trait Definitions extends api.StandardDefinitions { /** Creators for TupleN, ProductN, FunctionN. */ def tupleType(elems: List[Type]) = aritySpecificType(TupleClass, elems) - def productType(elems: List[Type]) = aritySpecificType(ProductClass, elems) + // def productType(elems: List[Type]) = aritySpecificType(ProductClass, elems) def functionType(formals: List[Type], restpe: Type) = aritySpecificType(FunctionClass, formals, restpe) def abstractFunctionType(formals: List[Type], restpe: Type) = aritySpecificType(AbstractFunctionClass, formals, restpe) @@ -632,10 +631,10 @@ trait Definitions extends api.StandardDefinitions { else nme.genericWrapArray } - @deprecated("Use isTupleType", "2.10.0") - def isTupleTypeOrSubtype(tp: Type) = isTupleType(tp) + // @deprecated("Use isTupleType", "2.10.0") + // def isTupleTypeOrSubtype(tp: Type) = isTupleType(tp) - def tupleField(n: Int, j: Int) = getMemberValue(TupleClass(n), nme.productAccessorName(j)) + // def tupleField(n: Int, j: Int) = getMemberValue(TupleClass(n), nme.productAccessorName(j)) // NOTE: returns true for NoSymbol since it's included in the TupleClass array -- is this intensional? def isTupleSymbol(sym: Symbol) = TupleClass contains unspecializedSymbol(sym) def isProductNClass(sym: Symbol) = ProductClass contains sym @@ -684,10 +683,10 @@ trait Definitions extends api.StandardDefinitions { // def Product_productElementName = getMemberMethod(ProductRootClass, nme.productElementName) def productProj(z:Symbol, j: Int): TermSymbol = getMemberValue(z, nme.productAccessorName(j)) - def productProj(n: Int, j: Int): TermSymbol = productProj(ProductClass(n), j) + // def productProj(n: Int, j: Int): TermSymbol = productProj(ProductClass(n), j) /** returns true if this type is exactly ProductN[T1,...,Tn], not some subclass */ - def isExactProductType(tp: Type): Boolean = isProductNClass(tp.typeSymbol) + // def isExactProductType(tp: Type): Boolean = isProductNClass(tp.typeSymbol) /** if tpe <: ProductN[T1,...,TN], returns List(T1,...,TN) else Nil */ def getProductArgs(tpe: Type): List[Type] = tpe.baseClasses find isProductNClass match { @@ -705,7 +704,7 @@ trait Definitions extends api.StandardDefinitions { case tp => tp } - def functionApply(n: Int) = getMemberMethod(FunctionClass(n), nme.apply) + // def functionApply(n: Int) = getMemberMethod(FunctionClass(n), nme.apply) def abstractFunctionForFunctionType(tp: Type) = if (isFunctionType(tp)) abstractFunctionType(tp.typeArgs.init, tp.typeArgs.last) @@ -724,7 +723,7 @@ trait Definitions extends api.StandardDefinitions { (sym eq PartialFunctionClass) || (sym eq AbstractPartialFunctionClass) } - def isSeqType(tp: Type) = elementType(SeqClass, tp.normalize) != NoType + // def isSeqType(tp: Type) = elementType(SeqClass, tp.normalize) != NoType def elementType(container: Symbol, tp: Type): Type = tp match { case TypeRef(_, `container`, arg :: Nil) => arg @@ -738,10 +737,10 @@ trait Definitions extends api.StandardDefinitions { def optionType(tp: Type) = appliedType(OptionClass, tp) def scalaRepeatedType(arg: Type) = appliedType(RepeatedParamClass, arg) def seqType(arg: Type) = appliedType(SeqClass, arg) - def someType(tp: Type) = appliedType(SomeClass, tp) + // def someType(tp: Type) = appliedType(SomeClass, tp) - def StringArray = arrayType(StringClass.tpe) - lazy val ObjectArray = arrayType(ObjectClass.tpe) + // def StringArray = arrayType(StringClass.tpe) + // lazy val ObjectArray = arrayType(ObjectClass.tpe) def ClassType(arg: Type) = if (phase.erasedTypes || forMSIL) ClassClass.tpe @@ -754,8 +753,8 @@ trait Definitions extends api.StandardDefinitions { // - .linkedClassOfClass: the ClassSymbol of the enumeration (class E) sym.owner.linkedClassOfClass.tpe - def vmClassType(arg: Type): Type = ClassType(arg) - def vmSignature(sym: Symbol, info: Type): String = signature(info) // !!! + // def vmClassType(arg: Type): Type = ClassType(arg) + // def vmSignature(sym: Symbol, info: Type): String = signature(info) // !!! /** Given a class symbol C with type parameters T1, T2, ... Tn * which have upper/lower bounds LB1/UB1, LB1/UB2, ..., LBn/UBn, @@ -768,14 +767,14 @@ trait Definitions extends api.StandardDefinitions { /** Given type U, creates a Type representing Class[_ <: U]. */ - def boundedClassType(upperBound: Type) = - appliedTypeAsUpperBounds(ClassClass.typeConstructor, List(upperBound)) + // def boundedClassType(upperBound: Type) = + // appliedTypeAsUpperBounds(ClassClass.typeConstructor, List(upperBound)) /** To avoid unchecked warnings on polymorphic classes, translate * a Foo[T] into a Foo[_] for use in the pattern matcher. */ - @deprecated("Use classExistentialType", "2.10.0") - def typeCaseType(clazz: Symbol): Type = classExistentialType(clazz) + // @deprecated("Use classExistentialType", "2.10.0") + // def typeCaseType(clazz: Symbol): Type = classExistentialType(clazz) // // .NET backend @@ -783,7 +782,7 @@ trait Definitions extends api.StandardDefinitions { lazy val ComparatorClass = getRequiredClass("scala.runtime.Comparator") // System.ValueType - lazy val ValueTypeClass: ClassSymbol = getClassByName(sn.ValueType) + // lazy val ValueTypeClass: ClassSymbol = getClassByName(sn.ValueType) // System.MulticastDelegate lazy val DelegateClass: ClassSymbol = getClassByName(sn.Delegate) var Delegate_scalaCallers: List[Symbol] = List() // Syncnote: No protection necessary yet as only for .NET where reflection is not supported. @@ -876,11 +875,11 @@ trait Definitions extends api.StandardDefinitions { x :: removeRedundantObjects(xs) } /** Order a list of types with non-trait classes before others. */ - def classesFirst(tps: List[Type]): List[Type] = { - val (classes, others) = tps partition (t => t.typeSymbol.isClass && !t.typeSymbol.isTrait) - if (classes.isEmpty || others.isEmpty || (tps startsWith classes)) tps - else classes ::: others - } + // def classesFirst(tps: List[Type]): List[Type] = { + // val (classes, others) = tps partition (t => t.typeSymbol.isClass && !t.typeSymbol.isTrait) + // if (classes.isEmpty || others.isEmpty || (tps startsWith classes)) tps + // else classes ::: others + // } /** The following transformations applied to a list of parents. * If any parent is a class/trait, all parents which normalize to * Object are discarded. Otherwise, all parents which normalize @@ -908,10 +907,10 @@ trait Definitions extends api.StandardDefinitions { def parentsString(parents: List[Type]) = normalizedParents(parents) mkString " with " - def typeParamsString(tp: Type) = tp match { - case PolyType(tparams, _) => tparams map (_.defString) mkString ("[", ",", "]") - case _ => "" - } + // def typeParamsString(tp: Type) = tp match { + // case PolyType(tparams, _) => tparams map (_.defString) mkString ("[", ",", "]") + // case _ => "" + // } def valueParamsString(tp: Type) = tp match { case MethodType(params, _) => params map (_.defString) mkString ("(", ",", ")") case _ => "" @@ -948,12 +947,12 @@ trait Definitions extends api.StandardDefinitions { lazy val BoxedNumberClass = getClassByName(sn.BoxedNumber) lazy val BoxedCharacterClass = getClassByName(sn.BoxedCharacter) lazy val BoxedBooleanClass = getClassByName(sn.BoxedBoolean) - lazy val BoxedByteClass = requiredClass[java.lang.Byte] - lazy val BoxedShortClass = requiredClass[java.lang.Short] - lazy val BoxedIntClass = requiredClass[java.lang.Integer] - lazy val BoxedLongClass = requiredClass[java.lang.Long] - lazy val BoxedFloatClass = requiredClass[java.lang.Float] - lazy val BoxedDoubleClass = requiredClass[java.lang.Double] + // lazy val BoxedByteClass = requiredClass[java.lang.Byte] + // lazy val BoxedShortClass = requiredClass[java.lang.Short] + // lazy val BoxedIntClass = requiredClass[java.lang.Integer] + // lazy val BoxedLongClass = requiredClass[java.lang.Long] + // lazy val BoxedFloatClass = requiredClass[java.lang.Float] + // lazy val BoxedDoubleClass = requiredClass[java.lang.Double] lazy val Boxes_isNumberOrBool = getDecl(BoxesRunTimeClass, nme.isBoxedNumberOrBoolean) lazy val Boxes_isNumber = getDecl(BoxesRunTimeClass, nme.isBoxedNumber) @@ -974,7 +973,7 @@ trait Definitions extends api.StandardDefinitions { lazy val ImplicitNotFoundClass = requiredClass[scala.annotation.implicitNotFound] lazy val MigrationAnnotationClass = requiredClass[scala.annotation.migration] lazy val ScalaStrictFPAttr = requiredClass[scala.annotation.strictfp] - lazy val SerializableAttr = requiredClass[scala.annotation.serializable] // @serializable is deprecated + // lazy val SerializableAttr = requiredClass[scala.annotation.serializable] // @serializable is deprecated lazy val SwitchClass = requiredClass[scala.annotation.switch] lazy val TailrecClass = requiredClass[scala.annotation.tailrec] lazy val VarargsClass = requiredClass[scala.annotation.varargs] @@ -1009,7 +1008,7 @@ trait Definitions extends api.StandardDefinitions { lazy val ParamTargetClass = requiredClass[meta.param] lazy val SetterTargetClass = requiredClass[meta.setter] lazy val ClassTargetClass = requiredClass[meta.companionClass] - lazy val ObjectTargetClass = requiredClass[meta.companionObject] + // lazy val ObjectTargetClass = requiredClass[meta.companionObject] lazy val MethodTargetClass = requiredClass[meta.companionMethod] // TODO: module, moduleClass? package, packageObject? lazy val LanguageFeatureAnnot = requiredClass[meta.languageFeature] @@ -1054,7 +1053,7 @@ trait Definitions extends api.StandardDefinitions { def getLanguageFeature(name: String, owner: Symbol = languageFeatureModule): Symbol = getMember(owner, newTypeName(name)) def termMember(owner: Symbol, name: String): Symbol = owner.info.member(newTermName(name)) - def typeMember(owner: Symbol, name: String): Symbol = owner.info.member(newTypeName(name)) + // def typeMember(owner: Symbol, name: String): Symbol = owner.info.member(newTypeName(name)) def findNamedMember(fullName: Name, root: Symbol): Symbol = { val segs = nme.segments(fullName.toString, fullName.isTermName) @@ -1121,8 +1120,8 @@ trait Definitions extends api.StandardDefinitions { def getDeclIfDefined(owner: Symbol, name: Name): Symbol = owner.info.nonPrivateDecl(name) - def packageExists(packageName: String): Boolean = - getModuleIfDefined(packageName).isPackage + // def packageExists(packageName: String): Boolean = + // getModuleIfDefined(packageName).isPackage private def newAlias(owner: Symbol, name: TypeName, alias: Type): AliasTypeSymbol = owner.newAliasType(name) setInfoAndEnter alias @@ -1155,7 +1154,7 @@ trait Definitions extends api.StandardDefinitions { newPolyMethod(1, owner, name, flags)(tparams => (Some(Nil), createFn(tparams.head))) } - lazy val boxedClassValues = boxedClass.values.toSet[Symbol] + // lazy val boxedClassValues = boxedClass.values.toSet[Symbol] lazy val isUnbox = unboxMethod.values.toSet[Symbol] lazy val isBox = boxMethod.values.toSet[Symbol] @@ -1215,8 +1214,8 @@ trait Definitions extends api.StandardDefinitions { /** Is symbol a value class? */ def isPrimitiveValueClass(sym: Symbol) = ScalaValueClasses contains sym - def isNonUnitValueClass(sym: Symbol) = isPrimitiveValueClass(sym) && (sym != UnitClass) - def isSpecializableClass(sym: Symbol) = isPrimitiveValueClass(sym) || (sym == AnyRefClass) + // def isNonUnitValueClass(sym: Symbol) = isPrimitiveValueClass(sym) && (sym != UnitClass) + // def isSpecializableClass(sym: Symbol) = isPrimitiveValueClass(sym) || (sym == AnyRefClass) def isPrimitiveValueType(tp: Type) = isPrimitiveValueClass(tp.typeSymbol) /** Is symbol a boxed value class, e.g. java.lang.Integer? */ diff --git a/src/reflect/scala/reflect/internal/ExistentialsAndSkolems.scala b/src/reflect/scala/reflect/internal/ExistentialsAndSkolems.scala index 59c027868e..2a0fe9d19a 100644 --- a/src/reflect/scala/reflect/internal/ExistentialsAndSkolems.scala +++ b/src/reflect/scala/reflect/internal/ExistentialsAndSkolems.scala @@ -7,7 +7,6 @@ package scala.reflect package internal import scala.collection.{ mutable, immutable } -import util._ /** The name of this trait defines the eventual intent better than * it does the initial contents. diff --git a/src/reflect/scala/reflect/internal/Importers.scala b/src/reflect/scala/reflect/internal/Importers.scala index ea8d6078ff..592523c639 100644 --- a/src/reflect/scala/reflect/internal/Importers.scala +++ b/src/reflect/scala/reflect/internal/Importers.scala @@ -316,7 +316,7 @@ trait Importers extends api.Importers { self: SymbolTable => def importName(name: from.Name): Name = if (name.isTypeName) newTypeName(name.toString) else newTermName(name.toString) def importTypeName(name: from.TypeName): TypeName = importName(name).toTypeName - def importTermName(name: from.TermName): TermName = importName(name).toTermName + // def importTermName(name: from.TermName): TermName = importName(name).toTermName def importModifiers(mods: from.Modifiers): Modifiers = new Modifiers(mods.flags, importName(mods.privateWithin), mods.annotations map importTree) diff --git a/src/reflect/scala/reflect/internal/Names.scala b/src/reflect/scala/reflect/internal/Names.scala index 9193674f3e..7d98823c7e 100644 --- a/src/reflect/scala/reflect/internal/Names.scala +++ b/src/reflect/scala/reflect/internal/Names.scala @@ -135,8 +135,8 @@ trait Names extends api.Names with LowPriorityNames { def newTypeName(bs: Array[Byte], offset: Int, len: Int): TypeName = newTermName(bs, offset, len).toTypeName - def nameChars: Array[Char] = chrs - @deprecated("", "2.9.0") def view(s: String): TermName = newTermName(s) + // def nameChars: Array[Char] = chrs + // @deprecated("", "2.9.0") def view(s: String): TermName = newTermName(s) // Classes ---------------------------------------------------------------------- @@ -186,22 +186,22 @@ trait Names extends api.Names with LowPriorityNames { scala.compat.Platform.arraycopy(chrs, index, cs, offset, len) /** @return the ascii representation of this name */ - final def toChars: Array[Char] = { - val cs = new Array[Char](len) - copyChars(cs, 0) - cs - } + // final def toChars: Array[Char] = { + // val cs = new Array[Char](len) + // copyChars(cs, 0) + // cs + // } /** Write to UTF8 representation of this name to given character array. * Start copying to index `to`. Return index of next free byte in array. * Array must have enough remaining space for all bytes * (i.e. maximally 3*length bytes). */ - final def copyUTF8(bs: Array[Byte], offset: Int): Int = { - val bytes = Codec.toUTF8(chrs, index, len) - scala.compat.Platform.arraycopy(bytes, 0, bs, offset, bytes.length) - offset + bytes.length - } + // final def copyUTF8(bs: Array[Byte], offset: Int): Int = { + // val bytes = Codec.toUTF8(chrs, index, len) + // scala.compat.Platform.arraycopy(bytes, 0, bs, offset, bytes.length) + // offset + bytes.length + // } /** @return the hash value of this name */ final override def hashCode(): Int = index @@ -283,7 +283,7 @@ trait Names extends api.Names with LowPriorityNames { */ final def lastPos(c: Char): Int = lastPos(c, len - 1) - final def lastPos(s: String): Int = lastPos(s, len - s.length) + // final def lastPos(s: String): Int = lastPos(s, len - s.length) /** Returns the index of the last occurrence of char c in this * name from start, -1 if not found. @@ -305,18 +305,18 @@ trait Names extends api.Names with LowPriorityNames { * @param start ... * @return the index of the last occurrence of s */ - final def lastPos(s: String, start: Int): Int = { - var i = lastPos(s.charAt(0), start) - while (i >= 0) { - var j = 1; - while (s.charAt(j) == chrs(index + i + j)) { - j += 1 - if (j == s.length()) return i; - } - i = lastPos(s.charAt(0), i - 1) - } - -s.length() - } + // final def lastPos(s: String, start: Int): Int = { + // var i = lastPos(s.charAt(0), start) + // while (i >= 0) { + // var j = 1; + // while (s.charAt(j) == chrs(index + i + j)) { + // j += 1 + // if (j == s.length()) return i; + // } + // i = lastPos(s.charAt(0), i - 1) + // } + // -s.length() + // } /** Does this name start with prefix? */ final def startsWith(prefix: Name): Boolean = startsWith(prefix, 0) @@ -379,7 +379,7 @@ trait Names extends api.Names with LowPriorityNames { if (idx == length) -1 else idx } def lastIndexOf(ch: Char) = lastPos(ch) - def lastIndexOf(ch: Char, fromIndex: Int) = lastPos(ch, fromIndex) + // def lastIndexOf(ch: Char, fromIndex: Int) = lastPos(ch, fromIndex) /** Replace all occurrences of `from` by `to` in * name; result is always a term name. @@ -428,12 +428,12 @@ trait Names extends api.Names with LowPriorityNames { def append(ch: Char) = newName("" + this + ch) def append(suffix: String) = newName("" + this + suffix) def append(suffix: Name) = newName("" + this + suffix) - def prepend(ch: Char) = newName("" + ch + this) + // def prepend(ch: Char) = newName("" + ch + this) def prepend(prefix: String) = newName("" + prefix + this) - def prepend(prefix: Name) = newName("" + prefix + this) + // def prepend(prefix: Name) = newName("" + prefix + this) def decodedName: ThisNameType = newName(decode) - def isOperatorName: Boolean = decode != toString + // def isOperatorName: Boolean = decode != toString def longString: String = nameKind + " " + decode def debugString = { val s = decode ; if (isTypeName) s + "!" else s } } @@ -445,7 +445,7 @@ trait Names extends api.Names with LowPriorityNames { def stripSuffix(suffix: Name): T = if (name endsWith suffix) dropRight(suffix.length) else name def dropRight(n: Int): T = name.subName(0, name.length - n).asInstanceOf[T] def drop(n: Int): T = name.subName(n, name.length).asInstanceOf[T] - def nonEmpty: Boolean = name.length > 0 + // def nonEmpty: Boolean = name.length > 0 } implicit val NameTag = ClassTag[Name](classOf[Name]) @@ -489,7 +489,7 @@ trait Names extends api.Names with LowPriorityNames { type ThisNameType = TermName protected[this] def thisName: TermName = this - var next: TermName = termHashtable(hash) + val next: TermName = termHashtable(hash) termHashtable(hash) = this def isTermName: Boolean = true def isTypeName: Boolean = false @@ -518,7 +518,7 @@ trait Names extends api.Names with LowPriorityNames { type ThisNameType = TypeName protected[this] def thisName: TypeName = this - var next: TypeName = typeHashtable(hash) + val next: TypeName = typeHashtable(hash) typeHashtable(hash) = this def isTermName: Boolean = false def isTypeName: Boolean = true diff --git a/src/reflect/scala/reflect/internal/Printers.scala b/src/reflect/scala/reflect/internal/Printers.scala index 31f9cb7e59..58e3aff46f 100644 --- a/src/reflect/scala/reflect/internal/Printers.scala +++ b/src/reflect/scala/reflect/internal/Printers.scala @@ -475,8 +475,8 @@ trait Printers extends api.Printers { self: SymbolTable => } def newRawTreePrinter(writer: PrintWriter): RawTreePrinter = new RawTreePrinter(writer) - def newRawTreePrinter(stream: OutputStream): RawTreePrinter = newRawTreePrinter(new PrintWriter(stream)) - def newRawTreePrinter(): RawTreePrinter = newRawTreePrinter(new PrintWriter(ConsoleWriter)) + // def newRawTreePrinter(stream: OutputStream): RawTreePrinter = newRawTreePrinter(new PrintWriter(stream)) + // def newRawTreePrinter(): RawTreePrinter = newRawTreePrinter(new PrintWriter(ConsoleWriter)) // provides footnotes for types and mirrors import scala.collection.mutable.{Map, WeakHashMap, SortedSet} diff --git a/src/reflect/scala/reflect/internal/Scopes.scala b/src/reflect/scala/reflect/internal/Scopes.scala index 950e30dbc5..31907772cb 100644 --- a/src/reflect/scala/reflect/internal/Scopes.scala +++ b/src/reflect/scala/reflect/internal/Scopes.scala @@ -343,7 +343,7 @@ trait Scopes extends api.Scopes { self: SymbolTable => */ def iterator: Iterator[Symbol] = toList.iterator - def containsSymbol(s: Symbol) = lookupAll(s.name) contains s + // def containsSymbol(s: Symbol) = lookupAll(s.name) contains s override def foreach[U](p: Symbol => U): Unit = toList foreach p diff --git a/src/reflect/scala/reflect/internal/StdNames.scala b/src/reflect/scala/reflect/internal/StdNames.scala index 5e7f5777b2..7947a1a1e1 100644 --- a/src/reflect/scala/reflect/internal/StdNames.scala +++ b/src/reflect/scala/reflect/internal/StdNames.scala @@ -104,7 +104,7 @@ trait StdNames { val IMPORT: NameType = "" val MODULE_SUFFIX_NAME: NameType = MODULE_SUFFIX_STRING val MODULE_VAR_SUFFIX: NameType = "$module" - val NAME_JOIN_NAME: NameType = NAME_JOIN_STRING + // val NAME_JOIN_NAME: NameType = NAME_JOIN_STRING val PACKAGE: NameType = "package" val ROOT: NameType = "" val SPECIALIZED_SUFFIX: NameType = "$sp" @@ -121,8 +121,8 @@ trait StdNames { final val Short: NameType = "Short" final val Unit: NameType = "Unit" - final val ScalaValueNames: scala.List[NameType] = - scala.List(Byte, Char, Short, Int, Long, Float, Double, Boolean, Unit) + // final val ScalaValueNames: scala.List[NameType] = + // scala.List(Byte, Char, Short, Int, Long, Float, Double, Boolean, Unit) // some types whose companions we utilize final val AnyRef: NameType = "AnyRef" @@ -130,7 +130,7 @@ trait StdNames { final val List: NameType = "List" final val Seq: NameType = "Seq" final val Symbol: NameType = "Symbol" - final val ClassTag: NameType = "ClassTag" + // final val ClassTag: NameType = "ClassTag" final val WeakTypeTag: NameType = "WeakTypeTag" final val TypeTag : NameType = "TypeTag" final val Expr: NameType = "Expr" @@ -220,12 +220,12 @@ trait StdNames { final val Any: NameType = "Any" final val AnyVal: NameType = "AnyVal" - final val ExprApi: NameType = "ExprApi" + // final val ExprApi: NameType = "ExprApi" final val Mirror: NameType = "Mirror" final val Nothing: NameType = "Nothing" final val Null: NameType = "Null" final val Object: NameType = "Object" - final val PartialFunction: NameType = "PartialFunction" + // final val PartialFunction: NameType = "PartialFunction" final val PrefixType: NameType = "PrefixType" final val Product: NameType = "Product" final val Serializable: NameType = "Serializable" @@ -239,7 +239,7 @@ trait StdNames { final val Group: NameType = "Group" final val Tree: NameType = "Tree" final val Type : NameType = "Type" - final val TypeTree: NameType = "TypeTree" + // final val TypeTree: NameType = "TypeTree" // Annotation simple names, used in Namer final val BeanPropertyAnnot: NameType = "BeanProperty" @@ -249,13 +249,13 @@ trait StdNames { // Classfile Attributes final val AnnotationDefaultATTR: NameType = "AnnotationDefault" final val BridgeATTR: NameType = "Bridge" - final val ClassfileAnnotationATTR: NameType = "RuntimeInvisibleAnnotations" // RetentionPolicy.CLASS. Currently not used (Apr 2009). + // final val ClassfileAnnotationATTR: NameType = "RuntimeInvisibleAnnotations" // RetentionPolicy.CLASS. Currently not used (Apr 2009). final val CodeATTR: NameType = "Code" final val ConstantValueATTR: NameType = "ConstantValue" final val DeprecatedATTR: NameType = "Deprecated" final val ExceptionsATTR: NameType = "Exceptions" final val InnerClassesATTR: NameType = "InnerClasses" - final val LineNumberTableATTR: NameType = "LineNumberTable" + // final val LineNumberTableATTR: NameType = "LineNumberTable" final val LocalVariableTableATTR: NameType = "LocalVariableTable" final val RuntimeAnnotationATTR: NameType = "RuntimeVisibleAnnotations" // RetentionPolicy.RUNTIME final val RuntimeParamAnnotationATTR: NameType = "RuntimeVisibleParameterAnnotations" // RetentionPolicy.RUNTIME (annotations on parameters) @@ -284,9 +284,9 @@ trait StdNames { val EXCEPTION_RESULT_PREFIX = "exceptionResult" val EXPAND_SEPARATOR_STRING = "$$" val INTERPRETER_IMPORT_WRAPPER = "$iw" - val INTERPRETER_LINE_PREFIX = "line" - val INTERPRETER_VAR_PREFIX = "res" - val INTERPRETER_WRAPPER_SUFFIX = "$object" + // val INTERPRETER_LINE_PREFIX = "line" + // val INTERPRETER_VAR_PREFIX = "res" + // val INTERPRETER_WRAPPER_SUFFIX = "$object" val LOCALDUMMY_PREFIX = " true - case _ => false - } + // def isDeprecatedIdentifierName(name: Name) = name.toTermName match { + // case nme.`then` | nme.`macro` => true + // case _ => false + // } def isOpAssignmentName(name: Name) = name match { case raw.NE | raw.LE | raw.GE | EMPTY => false @@ -461,14 +461,14 @@ trait StdNames { // If the name ends with $nn where nn are // all digits, strip the $ and the digits. // Otherwise return the argument. - def stripAnonNumberSuffix(name: Name): Name = { - var pos = name.length - while (pos > 0 && name.charAt(pos - 1).isDigit) - pos -= 1 + // def stripAnonNumberSuffix(name: Name): Name = { + // var pos = name.length + // while (pos > 0 && name.charAt(pos - 1).isDigit) + // pos -= 1 - if (pos <= 0 || pos == name.length || name.charAt(pos - 1) != '$') name - else name.subName(0, pos - 1) - } + // if (pos <= 0 || pos == name.length || name.charAt(pos - 1) != '$') name + // else name.subName(0, pos - 1) + // } def stripModuleSuffix(name: Name): Name = ( if (isModuleName(name)) name dropRight MODULE_SUFFIX_STRING.length else name @@ -484,8 +484,8 @@ trait StdNames { final val Nil: NameType = "Nil" final val Predef: NameType = "Predef" - final val ScalaRunTime: NameType = "ScalaRunTime" - final val Some: NameType = "Some" + // final val ScalaRunTime: NameType = "ScalaRunTime" + // final val Some: NameType = "Some" val _1 : NameType = "_1" val _2 : NameType = "_2" @@ -581,14 +581,14 @@ trait StdNames { val Annotation: NameType = "Annotation" val Any: NameType = "Any" val AnyVal: NameType = "AnyVal" - val AppliedTypeTree: NameType = "AppliedTypeTree" - val Apply: NameType = "Apply" + // val AppliedTypeTree: NameType = "AppliedTypeTree" + // val Apply: NameType = "Apply" val ArrayAnnotArg: NameType = "ArrayAnnotArg" - val Constant: NameType = "Constant" + // val Constant: NameType = "Constant" val ConstantType: NameType = "ConstantType" val EmptyPackage: NameType = "EmptyPackage" val EmptyPackageClass: NameType = "EmptyPackageClass" - val ExistentialTypeTree: NameType = "ExistentialTypeTree" + // val ExistentialTypeTree: NameType = "ExistentialTypeTree" val Flag : NameType = "Flag" val Ident: NameType = "Ident" val Import: NameType = "Import" @@ -597,10 +597,10 @@ trait StdNames { val Modifiers: NameType = "Modifiers" val NestedAnnotArg: NameType = "NestedAnnotArg" val NoFlags: NameType = "NoFlags" - val NoPrefix: NameType = "NoPrefix" + // val NoPrefix: NameType = "NoPrefix" val NoSymbol: NameType = "NoSymbol" val Nothing: NameType = "Nothing" - val NoType: NameType = "NoType" + // val NoType: NameType = "NoType" val Null: NameType = "Null" val Object: NameType = "Object" val RootPackage: NameType = "RootPackage" @@ -609,17 +609,17 @@ trait StdNames { val StringContext: NameType = "StringContext" val This: NameType = "This" val ThisType: NameType = "ThisType" - val Tree : NameType = "Tree" + // val Tree : NameType = "Tree" val Tuple2: NameType = "Tuple2" val TYPE_ : NameType = "TYPE" - val TypeApply: NameType = "TypeApply" + // val TypeApply: NameType = "TypeApply" val TypeRef: NameType = "TypeRef" val TypeTree: NameType = "TypeTree" val UNIT : NameType = "UNIT" val add_ : NameType = "add" val annotation: NameType = "annotation" val anyValClass: NameType = "anyValClass" - val append: NameType = "append" + // val append: NameType = "append" val apply: NameType = "apply" val applyDynamic: NameType = "applyDynamic" val applyDynamicNamed: NameType = "applyDynamicNamed" @@ -627,34 +627,34 @@ trait StdNames { val args : NameType = "args" val argv : NameType = "argv" val arrayClass: NameType = "arrayClass" - val arrayElementClass: NameType = "arrayElementClass" - val arrayValue: NameType = "arrayValue" + // val arrayElementClass: NameType = "arrayElementClass" + // val arrayValue: NameType = "arrayValue" val array_apply : NameType = "array_apply" val array_clone : NameType = "array_clone" val array_length : NameType = "array_length" val array_update : NameType = "array_update" - val arraycopy: NameType = "arraycopy" - val asTerm: NameType = "asTerm" + // val arraycopy: NameType = "arraycopy" + // val asTerm: NameType = "asTerm" val asModule: NameType = "asModule" - val asMethod: NameType = "asMethod" + // val asMethod: NameType = "asMethod" val asType: NameType = "asType" - val asClass: NameType = "asClass" + // val asClass: NameType = "asClass" val asInstanceOf_ : NameType = "asInstanceOf" val asInstanceOf_Ob : NameType = "$asInstanceOf" - val assert_ : NameType = "assert" - val assume_ : NameType = "assume" + // val assert_ : NameType = "assert" + // val assume_ : NameType = "assume" val box: NameType = "box" val build : NameType = "build" val bytes: NameType = "bytes" val canEqual_ : NameType = "canEqual" val checkInitialized: NameType = "checkInitialized" - val ClassManifestFactory: NameType = "ClassManifestFactory" + // val ClassManifestFactory: NameType = "ClassManifestFactory" val classOf: NameType = "classOf" val clone_ : NameType = if (forMSIL) "MemberwiseClone" else "clone" // sn.OClone causes checkinit failure val conforms: NameType = "conforms" val copy: NameType = "copy" val currentMirror: NameType = "currentMirror" - val definitions: NameType = "definitions" + // val definitions: NameType = "definitions" val delayedInit: NameType = "delayedInit" val delayedInitArg: NameType = "delayedInit$body" val drop: NameType = "drop" @@ -667,7 +667,7 @@ trait StdNames { val equalsNumObject : NameType = "equalsNumObject" val equals_ : NameType = if (forMSIL) "Equals" else "equals" val error: NameType = "error" - val eval: NameType = "eval" + // val eval: NameType = "eval" val ex: NameType = "ex" val experimental: NameType = "experimental" val f: NameType = "f" @@ -678,17 +678,17 @@ trait StdNames { val flagsFromBits : NameType = "flagsFromBits" val flatMap: NameType = "flatMap" val foreach: NameType = "foreach" - val genericArrayOps: NameType = "genericArrayOps" + // val genericArrayOps: NameType = "genericArrayOps" val get: NameType = "get" - val getOrElse: NameType = "getOrElse" - val hasNext: NameType = "hasNext" + // val getOrElse: NameType = "getOrElse" + // val hasNext: NameType = "hasNext" val hashCode_ : NameType = if (forMSIL) "GetHashCode" else "hashCode" val hash_ : NameType = "hash" - val head: NameType = "head" - val identity: NameType = "identity" + // val head: NameType = "head" + // val identity: NameType = "identity" val implicitly: NameType = "implicitly" val in: NameType = "in" - val info: NameType = "info" + // val info: NameType = "info" val inlinedEquals: NameType = "inlinedEquals" val isArray: NameType = "isArray" val isDefinedAt: NameType = "isDefinedAt" @@ -700,57 +700,57 @@ trait StdNames { val lang: NameType = "lang" val length: NameType = "length" val lengthCompare: NameType = "lengthCompare" - val liftedTree: NameType = "liftedTree" - val `macro` : NameType = "macro" - val macroThis : NameType = "_this" + // val liftedTree: NameType = "liftedTree" + // val `macro` : NameType = "macro" + // val macroThis : NameType = "_this" val macroContext : NameType = "c" val main: NameType = "main" - val manifest: NameType = "manifest" - val ManifestFactory: NameType = "ManifestFactory" + // val manifest: NameType = "manifest" + // val ManifestFactory: NameType = "ManifestFactory" val manifestToTypeTag: NameType = "manifestToTypeTag" val map: NameType = "map" val materializeClassTag: NameType = "materializeClassTag" val materializeWeakTypeTag: NameType = "materializeWeakTypeTag" val materializeTypeTag: NameType = "materializeTypeTag" - val mirror : NameType = "mirror" + // val mirror : NameType = "mirror" val moduleClass : NameType = "moduleClass" - val name: NameType = "name" + // val name: NameType = "name" val ne: NameType = "ne" val newArray: NameType = "newArray" val newFreeTerm: NameType = "newFreeTerm" val newFreeType: NameType = "newFreeType" val newNestedSymbol: NameType = "newNestedSymbol" val newScopeWith: NameType = "newScopeWith" - val next: NameType = "next" + // val next: NameType = "next" val nmeNewTermName: NameType = "newTermName" val nmeNewTypeName: NameType = "newTypeName" - val normalize: NameType = "normalize" + // val normalize: NameType = "normalize" val notifyAll_ : NameType = "notifyAll" val notify_ : NameType = "notify" val null_ : NameType = "null" - val ofDim: NameType = "ofDim" - val origin: NameType = "origin" + // val ofDim: NameType = "ofDim" + // val origin: NameType = "origin" val prefix : NameType = "prefix" val productArity: NameType = "productArity" val productElement: NameType = "productElement" val productIterator: NameType = "productIterator" val productPrefix: NameType = "productPrefix" val readResolve: NameType = "readResolve" - val reflect : NameType = "reflect" + // val reflect : NameType = "reflect" val reify : NameType = "reify" val rootMirror : NameType = "rootMirror" - val runOrElse: NameType = "runOrElse" + // val runOrElse: NameType = "runOrElse" val runtime: NameType = "runtime" val runtimeClass: NameType = "runtimeClass" val runtimeMirror: NameType = "runtimeMirror" - val sameElements: NameType = "sameElements" + // val sameElements: NameType = "sameElements" val scala_ : NameType = "scala" val selectDynamic: NameType = "selectDynamic" val selectOverloadedMethod: NameType = "selectOverloadedMethod" val selectTerm: NameType = "selectTerm" val selectType: NameType = "selectType" val self: NameType = "self" - val setAccessible: NameType = "setAccessible" + // val setAccessible: NameType = "setAccessible" val setAnnotations: NameType = "setAnnotations" val setSymbol: NameType = "setSymbol" val setType: NameType = "setType" @@ -760,15 +760,15 @@ trait StdNames { val staticModule : NameType = "staticModule" val staticPackage : NameType = "staticPackage" val synchronized_ : NameType = "synchronized" - val tail: NameType = "tail" - val `then` : NameType = "then" + // val tail: NameType = "tail" + // val `then` : NameType = "then" val this_ : NameType = "this" val thisPrefix : NameType = "thisPrefix" - val throw_ : NameType = "throw" + // val throw_ : NameType = "throw" val toArray: NameType = "toArray" - val toList: NameType = "toList" + // val toList: NameType = "toList" val toObjectArray : NameType = "toObjectArray" - val toSeq: NameType = "toSeq" + // val toSeq: NameType = "toSeq" val toString_ : NameType = if (forMSIL) "ToString" else "toString" val toTypeConstructor: NameType = "toTypeConstructor" val tpe : NameType = "tpe" @@ -788,14 +788,14 @@ trait StdNames { val view_ : NameType = "view" val wait_ : NameType = "wait" val withFilter: NameType = "withFilter" - val wrap: NameType = "wrap" - val zip: NameType = "zip" + // val wrap: NameType = "wrap" + // val zip: NameType = "zip" - val synthSwitch: NameType = "$synthSwitch" + // val synthSwitch: NameType = "$synthSwitch" // unencoded operators object raw { - final val AMP : NameType = "&" + // final val AMP : NameType = "&" final val BANG : NameType = "!" final val BAR : NameType = "|" final val DOLLAR: NameType = "$" @@ -804,7 +804,7 @@ trait StdNames { final val MINUS: NameType = "-" final val NE: NameType = "!=" final val PLUS : NameType = "+" - final val SLASH: NameType = "/" + // final val SLASH: NameType = "/" final val STAR : NameType = "*" final val TILDE: NameType = "~" @@ -860,14 +860,14 @@ trait StdNames { // Grouped here so Cleanup knows what tests to perform. val CommonOpNames = Set[Name](OR, XOR, AND, EQ, NE) - val ConversionNames = Set[Name](toByte, toChar, toDouble, toFloat, toInt, toLong, toShort) + // val ConversionNames = Set[Name](toByte, toChar, toDouble, toFloat, toInt, toLong, toShort) val BooleanOpNames = Set[Name](ZOR, ZAND, UNARY_!) ++ CommonOpNames - val NumberOpNames = ( - Set[Name](ADD, SUB, MUL, DIV, MOD, LSL, LSR, ASR, LT, LE, GE, GT) - ++ Set(UNARY_+, UNARY_-, UNARY_!) - ++ ConversionNames - ++ CommonOpNames - ) + // val NumberOpNames = ( + // Set[Name](ADD, SUB, MUL, DIV, MOD, LSL, LSR, ASR, LT, LE, GE, GT) + // ++ Set(UNARY_+, UNARY_-, UNARY_!) + // ++ ConversionNames + // ++ CommonOpNames + // ) val add: NameType = "add" val complement: NameType = "complement" @@ -999,7 +999,7 @@ trait StdNames { object fulltpnme extends TypeNames { val RuntimeNothing: NameType = "scala.runtime.Nothing$" val RuntimeNull: NameType = "scala.runtime.Null$" - val JavaLangEnum: NameType = "java.lang.Enum" + // val JavaLangEnum: NameType = "java.lang.Enum" } /** Java binary names, like scala/runtime/Nothing$. @@ -1015,15 +1015,15 @@ trait StdNames { object nme extends TermNames { - def isModuleVarName(name: Name): Boolean = - stripAnonNumberSuffix(name) endsWith MODULE_VAR_SUFFIX + // def isModuleVarName(name: Name): Boolean = + // stripAnonNumberSuffix(name) endsWith MODULE_VAR_SUFFIX def moduleVarName(name: TermName): TermName = newTermNameCached("" + name + MODULE_VAR_SUFFIX) def getCause = sn.GetCause def getClass_ = sn.GetClass - def getComponentType = sn.GetComponentType + // def getComponentType = sn.GetComponentType def getMethod_ = sn.GetMethod def invoke_ = sn.Invoke @@ -1036,14 +1036,14 @@ trait StdNames { val reflMethodCacheName: NameType = "reflMethod$Cache" val reflMethodName: NameType = "reflMethod$Method" - private val reflectionCacheNames = Set[NameType]( - reflPolyCacheName, - reflClassCacheName, - reflParamsCacheName, - reflMethodCacheName, - reflMethodName - ) - def isReflectionCacheName(name: Name) = reflectionCacheNames exists (name startsWith _) + // private val reflectionCacheNames = Set[NameType]( + // reflPolyCacheName, + // reflClassCacheName, + // reflParamsCacheName, + // reflMethodCacheName, + // reflMethodName + // ) + // def isReflectionCacheName(name: Name) = reflectionCacheNames exists (name startsWith _) @deprecated("Use a method in tpnme", "2.10.0") def dropSingletonName(name: Name): TypeName = tpnme.dropSingletonName(name) @deprecated("Use a method in tpnme", "2.10.0") def singletonName(name: Name): TypeName = tpnme.singletonName(name) @@ -1056,28 +1056,28 @@ trait StdNames { protected val stringToTypeName = null protected implicit def createNameType(s: String): TypeName = newTypeNameCached(s) - val BeanProperty : TypeName - val BooleanBeanProperty : TypeName + // val BeanProperty : TypeName + // val BooleanBeanProperty : TypeName val BoxedBoolean : TypeName val BoxedCharacter : TypeName val BoxedNumber : TypeName - val Class : TypeName + // val Class : TypeName val Delegate : TypeName val IOOBException : TypeName // IndexOutOfBoundsException val InvTargetException : TypeName // InvocationTargetException - val JavaSerializable : TypeName + // val JavaSerializable : TypeName val MethodAsObject : TypeName val NPException : TypeName // NullPointerException val Object : TypeName - val String : TypeName + // val String : TypeName val Throwable : TypeName val ValueType : TypeName - val ForName : TermName + // val ForName : TermName val GetCause : TermName val GetClass : TermName val GetClassLoader : TermName - val GetComponentType : TermName + // val GetComponentType : TermName val GetMethod : TermName val Invoke : TermName val JavaLang : TermName @@ -1152,22 +1152,22 @@ trait StdNames { final val BoxedLong: TypeName = "java.lang.Long" final val BoxedNumber: TypeName = "java.lang.Number" final val BoxedShort: TypeName = "java.lang.Short" - final val Class: TypeName = "java.lang.Class" + // final val Class: TypeName = "java.lang.Class" final val Delegate: TypeName = tpnme.NO_NAME final val IOOBException: TypeName = "java.lang.IndexOutOfBoundsException" final val InvTargetException: TypeName = "java.lang.reflect.InvocationTargetException" final val MethodAsObject: TypeName = "java.lang.reflect.Method" final val NPException: TypeName = "java.lang.NullPointerException" final val Object: TypeName = "java.lang.Object" - final val String: TypeName = "java.lang.String" + // final val String: TypeName = "java.lang.String" final val Throwable: TypeName = "java.lang.Throwable" final val ValueType: TypeName = tpnme.NO_NAME - final val ForName: TermName = newTermName("forName") + // final val ForName: TermName = newTermName("forName") final val GetCause: TermName = newTermName("getCause") final val GetClass: TermName = newTermName("getClass") final val GetClassLoader: TermName = newTermName("getClassLoader") - final val GetComponentType: TermName = newTermName("getComponentType") + // final val GetComponentType: TermName = newTermName("getComponentType") final val GetMethod: TermName = newTermName("getMethod") final val Invoke: TermName = newTermName("invoke") final val JavaLang: TermName = newTermName("java.lang") @@ -1185,28 +1185,28 @@ trait StdNames { } private class MSILNames extends SymbolNames { - final val BeanProperty: TypeName = tpnme.NO_NAME - final val BooleanBeanProperty: TypeName = tpnme.NO_NAME + // final val BeanProperty: TypeName = tpnme.NO_NAME + // final val BooleanBeanProperty: TypeName = tpnme.NO_NAME final val BoxedBoolean: TypeName = "System.IConvertible" final val BoxedCharacter: TypeName = "System.IConvertible" final val BoxedNumber: TypeName = "System.IConvertible" - final val Class: TypeName = "System.Type" + // final val Class: TypeName = "System.Type" final val Delegate: TypeName = "System.MulticastDelegate" final val IOOBException: TypeName = "System.IndexOutOfRangeException" final val InvTargetException: TypeName = "System.Reflection.TargetInvocationException" - final val JavaSerializable: TypeName = tpnme.NO_NAME + // final val JavaSerializable: TypeName = tpnme.NO_NAME final val MethodAsObject: TypeName = "System.Reflection.MethodInfo" final val NPException: TypeName = "System.NullReferenceException" final val Object: TypeName = "System.Object" - final val String: TypeName = "System.String" + // final val String: TypeName = "System.String" final val Throwable: TypeName = "System.Exception" final val ValueType: TypeName = "System.ValueType" - final val ForName: TermName = newTermName("GetType") + // final val ForName: TermName = newTermName("GetType") final val GetCause: TermName = newTermName("InnerException") /* System.Reflection.TargetInvocationException.InnerException */ final val GetClass: TermName = newTermName("GetType") final lazy val GetClassLoader: TermName = throw new UnsupportedOperationException("Scala reflection is not supported on this platform"); - final val GetComponentType: TermName = newTermName("GetElementType") + // final val GetComponentType: TermName = newTermName("GetElementType") final val GetMethod: TermName = newTermName("GetMethod") final val Invoke: TermName = newTermName("Invoke") final val JavaLang: TermName = newTermName("System") @@ -1223,13 +1223,13 @@ trait StdNames { ) } - private class J2SENames extends JavaNames { - final val BeanProperty: TypeName = "scala.beans.BeanProperty" - final val BooleanBeanProperty: TypeName = "scala.beans.BooleanBeanProperty" - final val JavaSerializable: TypeName = "java.io.Serializable" - } + // private class J2SENames extends JavaNames { + // final val BeanProperty: TypeName = "scala.beans.BeanProperty" + // final val BooleanBeanProperty: TypeName = "scala.beans.BooleanBeanProperty" + // final val JavaSerializable: TypeName = "java.io.Serializable" + // } lazy val sn: SymbolNames = if (forMSIL) new MSILNames - else new J2SENames + else new JavaNames { } } diff --git a/src/reflect/scala/reflect/internal/SymbolTable.scala b/src/reflect/scala/reflect/internal/SymbolTable.scala index fb1bf9ed9d..c72fb96611 100644 --- a/src/reflect/scala/reflect/internal/SymbolTable.scala +++ b/src/reflect/scala/reflect/internal/SymbolTable.scala @@ -184,7 +184,7 @@ abstract class SymbolTable extends macros.Universe final def phaseId(period: Period): Phase#Id = period & 0xFF /** The period at the start of run that includes `period`. */ - final def startRun(period: Period): Period = period & 0xFFFFFF00 + // final def startRun(period: Period): Period = period & 0xFFFFFF00 /** The current period. */ final def currentPeriod: Period = { @@ -298,7 +298,6 @@ abstract class SymbolTable extends macros.Universe object perRunCaches { import java.lang.ref.WeakReference - import scala.runtime.ScalaRunTime.stringOf import scala.collection.generic.Clearable // Weak references so the garbage collector will take care of diff --git a/src/reflect/scala/reflect/internal/Symbols.scala b/src/reflect/scala/reflect/internal/Symbols.scala index eec780470e..89c3659b2e 100644 --- a/src/reflect/scala/reflect/internal/Symbols.scala +++ b/src/reflect/scala/reflect/internal/Symbols.scala @@ -19,7 +19,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => protected var ids = 0 - val emptySymbolArray = new Array[Symbol](0) + // val emptySymbolArray = new Array[Symbol](0) protected def nextId() = { ids += 1; ids } @@ -256,8 +256,8 @@ trait Symbols extends api.Symbols { self: SymbolTable => (m, c) } - final def newPackageSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol = - newTermSymbol(name, pos, newFlags).asInstanceOf[ModuleSymbol] + // final def newPackageSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol = + // newTermSymbol(name, pos, newFlags).asInstanceOf[ModuleSymbol] final def newModuleClassSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleClassSymbol = newClassSymbol(name, pos, newFlags).asInstanceOf[ModuleClassSymbol] @@ -323,8 +323,8 @@ trait Symbols extends api.Symbols { self: SymbolTable => /** Synthetic value parameters when parameter symbols are not available */ - final def newSyntheticValueParamss(argtypess: List[List[Type]]): List[List[TermSymbol]] = - argtypess map (xs => newSyntheticValueParams(xs, freshNamer)) + // final def newSyntheticValueParamss(argtypess: List[List[Type]]): List[List[TermSymbol]] = + // argtypess map (xs => newSyntheticValueParams(xs, freshNamer)) /** Synthetic value parameters when parameter symbols are not available. * Calling this method multiple times will re-use the same parameter names. @@ -341,7 +341,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => final def newSyntheticValueParam(argtype: Type, name: TermName = nme.syntheticParamName(1)): TermSymbol = newValueParameter(name, owner.pos.focus, SYNTHETIC) setInfo argtype - def newSyntheticTypeParam(): TypeSymbol = newSyntheticTypeParam("T0", 0L) + // def newSyntheticTypeParam(): TypeSymbol = newSyntheticTypeParam("T0", 0L) def newSyntheticTypeParam(name: String, newFlags: Long): TypeSymbol = newTypeParameter(newTypeName(name), NoPosition, newFlags) setInfo TypeBounds.empty def newSyntheticTypeParams(num: Int): List[TypeSymbol] = (0 until num).toList map (n => newSyntheticTypeParam("T" + n, 0L)) @@ -407,11 +407,11 @@ trait Symbols extends api.Symbols { self: SymbolTable => /** Create a new getter for current symbol (which must be a field) */ - final def newGetter: MethodSymbol = ( - owner.newMethod(nme.getterName(name.toTermName), NoPosition, getterFlags(flags)) - setPrivateWithin privateWithin - setInfo MethodType(Nil, tpe) - ) + // final def newGetter: MethodSymbol = ( + // owner.newMethod(nme.getterName(name.toTermName), NoPosition, getterFlags(flags)) + // setPrivateWithin privateWithin + // setInfo MethodType(Nil, tpe) + // ) final def newErrorSymbol(name: Name): Symbol = name match { case x: TypeName => newErrorClass(x) @@ -528,14 +528,14 @@ trait Symbols extends api.Symbols { self: SymbolTable => */ def isContravariant = false def isCovariant = false - def isExistentialQuantified = false + // def isExistentialQuantified = false def isExistentialSkolem = false def isExistentiallyBound = false def isGADTSkolem = false def isTypeParameter = false def isTypeParameterOrSkolem = false def isTypeSkolem = false - def isTypeMacro = false + // def isTypeMacro = false def isInvariant = !isCovariant && !isContravariant /** Qualities of Terms, always false for TypeSymbols. @@ -719,14 +719,14 @@ trait Symbols extends api.Symbols { self: SymbolTable => = hasAnnotation(DeprecatedInheritanceAttr) def deprecatedInheritanceMessage = getAnnotation(DeprecatedInheritanceAttr) flatMap (_ stringArg 0) - def deprecatedInheritanceVersion - = getAnnotation(DeprecatedInheritanceAttr) flatMap (_ stringArg 1) + // def deprecatedInheritanceVersion + // = getAnnotation(DeprecatedInheritanceAttr) flatMap (_ stringArg 1) def hasDeprecatedOverridingAnnotation = hasAnnotation(DeprecatedOverridingAttr) def deprecatedOverridingMessage = getAnnotation(DeprecatedOverridingAttr) flatMap (_ stringArg 0) - def deprecatedOverridingVersion - = getAnnotation(DeprecatedOverridingAttr) flatMap (_ stringArg 1) + // def deprecatedOverridingVersion + // = getAnnotation(DeprecatedOverridingAttr) flatMap (_ stringArg 1) // !!! when annotation arguments are not literal strings, but any sort of // assembly of strings, there is a fair chance they will turn up here not as @@ -806,7 +806,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => final def isStaticOwner: Boolean = isPackageClass || isModuleClass && isStatic - def isTopLevelModule = hasFlag(MODULE) && owner.isPackageClass + // def isTopLevelModule = hasFlag(MODULE) && owner.isPackageClass /** A helper function for isEffectivelyFinal. */ private def isNotOverridden = ( @@ -844,7 +844,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => */ def isLocalClass = false - def isStableClass = false + // def isStableClass = false /* code for fixing nested objects override final def isModuleClass: Boolean = @@ -869,8 +869,8 @@ trait Symbols extends api.Symbols { self: SymbolTable => final def isPossibleInRefinement = !isConstructor && !isOverridingSymbol /** Is this symbol a member of class `clazz`? */ - def isMemberOf(clazz: Symbol) = - clazz.info.member(name).alternatives contains this + // def isMemberOf(clazz: Symbol) = + // clazz.info.member(name).alternatives contains this /** A a member of class `base` is incomplete if * (1) it is declared deferred or @@ -972,6 +972,14 @@ trait Symbols extends api.Symbols { self: SymbolTable => def ownerChain: List[Symbol] = this :: owner.ownerChain def originalOwnerChain: List[Symbol] = this :: originalOwner.getOrElse(this, rawowner).originalOwnerChain + // All the symbols overridden by this symbol and this symbol at the head, + // or Nil if this is NoSymbol. + def overrideChain = ( + if (this eq NoSymbol) Nil + else if (!owner.isClass) this :: Nil + else this :: allOverriddenSymbols + ) + // Non-classes skip self and return rest of owner chain; overridden in ClassSymbol. def enclClassChain: List[Symbol] = owner.enclClassChain @@ -1081,8 +1089,8 @@ trait Symbols extends api.Symbols { self: SymbolTable => protected def createImplClassSymbol(name: TypeName, pos: Position, newFlags: Long): ClassSymbol = new ClassSymbol(this, pos, name) with ImplClassSymbol initFlags newFlags - protected def createTermSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol = - new TermSymbol(this, pos, name) initFlags newFlags + // protected def createTermSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol = + // new TermSymbol(this, pos, name) initFlags newFlags protected def createMethodSymbol(name: TermName, pos: Position, newFlags: Long): MethodSymbol = new MethodSymbol(this, pos, name) initFlags newFlags @@ -1446,12 +1454,12 @@ trait Symbols extends api.Symbols { self: SymbolTable => !isInitialized && (flags & LOCKED) == 0 && shouldTriggerCompleter(this, if (infos ne null) infos.info else null, isFlagRelated, mask) /** Was symbol's type updated during given phase? */ - final def isUpdatedAt(pid: Phase#Id): Boolean = { - assert(isCompilerUniverse) - var infos = this.infos - while ((infos ne null) && phaseId(infos.validFrom) != pid + 1) infos = infos.prev - infos ne null - } + // final def isUpdatedAt(pid: Phase#Id): Boolean = { + // assert(isCompilerUniverse) + // var infos = this.infos + // while ((infos ne null) && phaseId(infos.validFrom) != pid + 1) infos = infos.prev + // infos ne null + // } /** Was symbol's type updated during given phase? */ final def hasTypeAt(pid: Phase#Id): Boolean = { @@ -1944,10 +1952,10 @@ trait Symbols extends api.Symbols { self: SymbolTable => (this.rawInfo ne NoType) && (this.effectiveOwner == that.effectiveOwner) && ( !this.effectiveOwner.isPackageClass - || (this.sourceFile eq null) - || (that.sourceFile eq null) - || (this.sourceFile.path == that.sourceFile.path) // Cheap possibly wrong check, then expensive normalization - || (this.sourceFile.canonicalPath == that.sourceFile.canonicalPath) + || (this.associatedFile eq null) + || (that.associatedFile eq null) + || (this.associatedFile.path == that.associatedFile.path) // Cheap possibly wrong check, then expensive normalization + || (this.associatedFile.canonicalPath == that.associatedFile.canonicalPath) ) ) @@ -2074,9 +2082,10 @@ trait Symbols extends api.Symbols { self: SymbolTable => if (isClassConstructor) NoSymbol else matchingSymbol(ofclazz, ofclazz.thisType) /** Returns all symbols overriden by this symbol. */ - final def allOverriddenSymbols: List[Symbol] = - if (!owner.isClass) Nil + final def allOverriddenSymbols: List[Symbol] = ( + if ((this eq NoSymbol) || !owner.isClass) Nil else owner.ancestors map overriddenSymbol filter (_ != NoSymbol) + ) /** Equivalent to allOverriddenSymbols.nonEmpty, but more efficient. */ // !!! When if ever will this answer differ from .isOverride? @@ -2087,7 +2096,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => ) /** Equivalent to allOverriddenSymbols.head (or NoSymbol if no overrides) but more efficient. */ def nextOverriddenSymbol: Symbol = { - if (owner.isClass) owner.ancestors foreach { base => + if ((this ne NoSymbol) && owner.isClass) owner.ancestors foreach { base => val sym = overriddenSymbol(base) if (sym != NoSymbol) return sym @@ -2208,10 +2217,10 @@ trait Symbols extends api.Symbols { self: SymbolTable => private def sourceFileOnly(file: AbstractFile): AbstractFile = if ((file eq null) || (file.path endsWith ".class")) null else file - private def binaryFileOnly(file: AbstractFile): AbstractFile = - if ((file eq null) || !(file.path endsWith ".class")) null else file + // private def binaryFileOnly(file: AbstractFile): AbstractFile = + // if ((file eq null) || !(file.path endsWith ".class")) null else file - final def binaryFile: AbstractFile = binaryFileOnly(associatedFile) + // final def binaryFile: AbstractFile = binaryFileOnly(associatedFile) final def sourceFile: AbstractFile = sourceFileOnly(associatedFile) /** Overridden in ModuleSymbols to delegate to the module class. */ @@ -2236,7 +2245,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => // ------ toString ------------------------------------------------------------------- /** A tag which (in the ideal case) uniquely identifies class symbols */ - final def tag: Int = fullName.## + // final def tag: Int = fullName.## /** The simple name of this Symbol */ final def simpleName: Name = name @@ -2705,7 +2714,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => final def asNameType(n: Name) = n.toTypeName override def isNonClassType = true - override def isTypeMacro = hasFlag(MACRO) + // override def isTypeMacro = hasFlag(MACRO) override def resolveOverloadedFlag(flag: Long) = flag match { case TRAIT => "" // DEFAULTPARAM @@ -2723,7 +2732,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => override def isAbstractType = this hasFlag DEFERRED override def isContravariant = this hasFlag CONTRAVARIANT override def isCovariant = this hasFlag COVARIANT - override def isExistentialQuantified = isExistentiallyBound && !isSkolem + // override def isExistentialQuantified = isExistentiallyBound && !isSkolem override def isExistentiallyBound = this hasFlag EXISTENTIAL override def isTypeParameter = isTypeParameterOrSkolem && !isSkolem override def isTypeParameterOrSkolem = this hasFlag PARAM @@ -2854,7 +2863,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => override def isTypeSkolem = this hasFlag PARAM override def isAbstractType = this hasFlag DEFERRED - override def isExistentialQuantified = false + // override def isExistentialQuantified = false override def existentialBound = if (isAbstractType) this.info else super.existentialBound /** If typeskolem comes from a type parameter, that parameter, otherwise skolem itself */ @@ -2940,21 +2949,21 @@ trait Symbols extends api.Symbols { self: SymbolTable => || isLocal || !owner.isPackageClass && owner.isLocalClass ) - override def isStableClass = (this hasFlag STABLE) || checkStable() - - private def checkStable() = { - def hasNoAbstractTypeMember(clazz: Symbol): Boolean = - (clazz hasFlag STABLE) || { - var e = clazz.info.decls.elems - while ((e ne null) && !(e.sym.isAbstractType && info.member(e.sym.name) == e.sym)) - e = e.next - e == null - } - (info.baseClasses forall hasNoAbstractTypeMember) && { - setFlag(STABLE) - true - } - } + // override def isStableClass = (this hasFlag STABLE) || checkStable() + + // private def checkStable() = { + // def hasNoAbstractTypeMember(clazz: Symbol): Boolean = + // (clazz hasFlag STABLE) || { + // var e = clazz.info.decls.elems + // while ((e ne null) && !(e.sym.isAbstractType && info.member(e.sym.name) == e.sym)) + // e = e.next + // e == null + // } + // (info.baseClasses forall hasNoAbstractTypeMember) && { + // setFlag(STABLE) + // true + // } + // } override def enclClassChain = this :: owner.enclClassChain diff --git a/src/reflect/scala/reflect/internal/TreeGen.scala b/src/reflect/scala/reflect/internal/TreeGen.scala index 6ce93d93b2..6c8ba047d6 100644 --- a/src/reflect/scala/reflect/internal/TreeGen.scala +++ b/src/reflect/scala/reflect/internal/TreeGen.scala @@ -11,10 +11,10 @@ abstract class TreeGen extends macros.TreeBuilder { def rootScalaDot(name: Name) = Select(rootId(nme.scala_) setSymbol ScalaPackage, name) def scalaDot(name: Name) = Select(Ident(nme.scala_) setSymbol ScalaPackage, name) def scalaAnnotationDot(name: Name) = Select(scalaDot(nme.annotation), name) - def scalaAnyRefConstr = scalaDot(tpnme.AnyRef) setSymbol AnyRefClass - def scalaUnitConstr = scalaDot(tpnme.Unit) setSymbol UnitClass - def productConstr = scalaDot(tpnme.Product) setSymbol ProductRootClass - def serializableConstr = scalaDot(tpnme.Serializable) setSymbol SerializableClass + // def scalaAnyRefConstr = scalaDot(tpnme.AnyRef) setSymbol AnyRefClass + // def scalaUnitConstr = scalaDot(tpnme.Unit) setSymbol UnitClass + // def productConstr = scalaDot(tpnme.Product) setSymbol ProductRootClass + // def serializableConstr = scalaDot(tpnme.Serializable) setSymbol SerializableClass def scalaFunctionConstr(argtpes: List[Tree], restpe: Tree, abstractFun: Boolean = false): Tree = { val cls = if (abstractFun) @@ -248,8 +248,8 @@ abstract class TreeGen extends macros.TreeBuilder { Literal(Constant(tp)) setType ConstantType(Constant(tp)) /** Builds a list with given head and tail. */ - def mkNewCons(head: Tree, tail: Tree): Tree = - New(Apply(mkAttributedRef(ConsClass), List(head, tail))) + // def mkNewCons(head: Tree, tail: Tree): Tree = + // New(Apply(mkAttributedRef(ConsClass), List(head, tail))) /** Builds a list with given head and tail. */ def mkNil: Tree = mkAttributedRef(NilModule) diff --git a/src/reflect/scala/reflect/internal/TreeInfo.scala b/src/reflect/scala/reflect/internal/TreeInfo.scala index 7ae7cf1821..2b1292e145 100644 --- a/src/reflect/scala/reflect/internal/TreeInfo.scala +++ b/src/reflect/scala/reflect/internal/TreeInfo.scala @@ -135,8 +135,8 @@ abstract class TreeInfo { @deprecated("Use isExprSafeToInline instead", "2.10.0") def isPureExpr(tree: Tree) = isExprSafeToInline(tree) - def zipMethodParamsAndArgs(params: List[Symbol], args: List[Tree]): List[(Symbol, Tree)] = - mapMethodParamsAndArgs(params, args)((param, arg) => ((param, arg))) + // def zipMethodParamsAndArgs(params: List[Symbol], args: List[Tree]): List[(Symbol, Tree)] = + // mapMethodParamsAndArgs(params, args)((param, arg) => ((param, arg))) def mapMethodParamsAndArgs[R](params: List[Symbol], args: List[Tree])(f: (Symbol, Tree) => R): List[R] = { val b = List.newBuilder[R] @@ -186,25 +186,25 @@ abstract class TreeInfo { * * Also accounts for varargs. */ - private def applyMethodParameters(fn: Tree): List[Symbol] = { - val depth = applyDepth(fn) - // There could be applies which go beyond the parameter list(s), - // being applied to the result of the method call. - // !!! Note that this still doesn't seem correct, although it should - // be closer than what it replaced. - if (depth < fn.symbol.paramss.size) fn.symbol.paramss(depth) - else if (fn.symbol.paramss.isEmpty) Nil - else fn.symbol.paramss.last - } - - def zipMethodParamsAndArgs(t: Tree): List[(Symbol, Tree)] = t match { - case Apply(fn, args) => zipMethodParamsAndArgs(applyMethodParameters(fn), args) - case _ => Nil - } - def foreachMethodParamAndArg(t: Tree)(f: (Symbol, Tree) => Unit): Unit = t match { - case Apply(fn, args) => foreachMethodParamAndArg(applyMethodParameters(fn), args)(f) - case _ => - } + // private def applyMethodParameters(fn: Tree): List[Symbol] = { + // val depth = applyDepth(fn) + // // There could be applies which go beyond the parameter list(s), + // // being applied to the result of the method call. + // // !!! Note that this still doesn't seem correct, although it should + // // be closer than what it replaced. + // if (depth < fn.symbol.paramss.size) fn.symbol.paramss(depth) + // else if (fn.symbol.paramss.isEmpty) Nil + // else fn.symbol.paramss.last + // } + + // def zipMethodParamsAndArgs(t: Tree): List[(Symbol, Tree)] = t match { + // case Apply(fn, args) => zipMethodParamsAndArgs(applyMethodParameters(fn), args) + // case _ => Nil + // } + // def foreachMethodParamAndArg(t: Tree)(f: (Symbol, Tree) => Unit): Unit = t match { + // case Apply(fn, args) => foreachMethodParamAndArg(applyMethodParameters(fn), args)(f) + // case _ => + // } /** Is symbol potentially a getter of a variable? */ @@ -354,10 +354,10 @@ abstract class TreeInfo { case x: Ident => !x.isBackquoted && nme.isVariableName(x.name) case _ => false } - def isDeprecatedIdentifier(tree: Tree): Boolean = tree match { - case x: Ident => !x.isBackquoted && nme.isDeprecatedIdentifierName(x.name) - case _ => false - } + // def isDeprecatedIdentifier(tree: Tree): Boolean = tree match { + // case x: Ident => !x.isBackquoted && nme.isDeprecatedIdentifierName(x.name) + // case _ => false + // } /** The first constructor definitions in `stats` */ def firstConstructor(stats: List[Tree]): Tree = stats find { @@ -417,10 +417,10 @@ abstract class TreeInfo { def isLeftAssoc(operator: Name) = operator.nonEmpty && (operator.endChar != ':') /** Is tree a `this` node which belongs to `enclClass`? */ - def isSelf(tree: Tree, enclClass: Symbol): Boolean = tree match { - case This(_) => tree.symbol == enclClass - case _ => false - } + // def isSelf(tree: Tree, enclClass: Symbol): Boolean = tree match { + // case This(_) => tree.symbol == enclClass + // case _ => false + // } /** a Match(Typed(_, tpt), _) must be translated into a switch if isSwitchAnnotation(tpt.tpe) */ def isSwitchAnnotation(tpe: Type) = tpe hasAnnotation definitions.SwitchClass diff --git a/src/reflect/scala/reflect/internal/Trees.scala b/src/reflect/scala/reflect/internal/Trees.scala index ed08226ec7..c93750165d 100644 --- a/src/reflect/scala/reflect/internal/Trees.scala +++ b/src/reflect/scala/reflect/internal/Trees.scala @@ -847,7 +847,7 @@ trait Trees extends api.Trees { self: SymbolTable => /** Is the tree Predef, scala.Predef, or _root_.scala.Predef? */ def isReferenceToPredef(t: Tree) = isReferenceToScalaMember(t, nme.Predef) - def isReferenceToAnyVal(t: Tree) = isReferenceToScalaMember(t, tpnme.AnyVal) + // def isReferenceToAnyVal(t: Tree) = isReferenceToScalaMember(t, tpnme.AnyVal) // --- modifiers implementation --------------------------------------- diff --git a/src/reflect/scala/reflect/internal/TypeDebugging.scala b/src/reflect/scala/reflect/internal/TypeDebugging.scala index 68b4fa69a1..9c2457e402 100644 --- a/src/reflect/scala/reflect/internal/TypeDebugging.scala +++ b/src/reflect/scala/reflect/internal/TypeDebugging.scala @@ -9,8 +9,6 @@ package internal trait TypeDebugging { self: SymbolTable => - import definitions._ - // @M toString that is safe during debugging (does not normalize, ...) object typeDebug { private def to_s(x: Any): String = x match { @@ -20,7 +18,7 @@ trait TypeDebugging { case x: Product => x.productIterator mkString ("(", ", ", ")") case _ => "" + x } - def ptIndent(x: Any) = ("" + x).replaceAll("\\n", " ") + // def ptIndent(x: Any) = ("" + x).replaceAll("\\n", " ") def ptBlock(label: String, pairs: (String, Any)*): String = { if (pairs.isEmpty) label + "{ }" else { diff --git a/src/reflect/scala/reflect/internal/Types.scala b/src/reflect/scala/reflect/internal/Types.scala index 42a9d9e456..0f92388993 100644 --- a/src/reflect/scala/reflect/internal/Types.scala +++ b/src/reflect/scala/reflect/internal/Types.scala @@ -167,10 +167,10 @@ trait Types extends api.Types { self: SymbolTable => log = Nil } finally unlock() } - def size = { - lock() - try log.size finally unlock() - } + // def size = { + // lock() + // try log.size finally unlock() + // } // `block` should not affect constraints on typevars def undo[T](block: => T): T = { @@ -184,18 +184,18 @@ trait Types extends api.Types { self: SymbolTable => } // if `block` evaluates to false, it should not affect constraints on typevars - def undoUnless(block: => Boolean): Boolean = { - lock() - try { - val before = log - var result = false + // def undoUnless(block: => Boolean): Boolean = { + // lock() + // try { + // val before = log + // var result = false - try result = block - finally if (!result) undoTo(before) + // try result = block + // finally if (!result) undoTo(before) - result - } finally unlock() - } + // result + // } finally unlock() + // } } /** A map from lists to compound types that have the given list as parents. @@ -292,7 +292,7 @@ trait Types extends api.Types { self: SymbolTable => abstract class TypeApiImpl extends TypeApi { this: Type => def declaration(name: Name): Symbol = decl(name) - def nonPrivateDeclaration(name: Name): Symbol = nonPrivateDecl(name) + // def nonPrivateDeclaration(name: Name): Symbol = nonPrivateDecl(name) def declarations = decls def typeArguments = typeArgs def erasure = this match { @@ -522,7 +522,7 @@ trait Types extends api.Types { self: SymbolTable => /** If this is a TypeRef `clazz`[`T`], return the argument `T` * otherwise return this type */ - def remove(clazz: Symbol): Type = this + // def remove(clazz: Symbol): Type = this /** For a curried/nullary method or poly type its non-method result type, * the type itself for all other types */ @@ -663,13 +663,13 @@ trait Types extends api.Types { self: SymbolTable => /** All members with the given flags, excluding bridges. */ - def membersWithFlags(requiredFlags: Long): Scope = - membersBasedOnFlags(BridgeFlags, requiredFlags) + // def membersWithFlags(requiredFlags: Long): Scope = + // membersBasedOnFlags(BridgeFlags, requiredFlags) /** All non-private members with the given flags, excluding bridges. */ - def nonPrivateMembersWithFlags(requiredFlags: Long): Scope = - membersBasedOnFlags(BridgeAndPrivateFlags, requiredFlags) + // def nonPrivateMembersWithFlags(requiredFlags: Long): Scope = + // membersBasedOnFlags(BridgeAndPrivateFlags, requiredFlags) /** The non-private member with given name, admitting members with given flags `admit`. * "Admitting" refers to the fact that members with a PRIVATE, BRIDGE, or VBRIDGE @@ -806,7 +806,7 @@ trait Types extends api.Types { self: SymbolTable => else substThis(from, to).substSym(symsFrom, symsTo) /** Returns all parts of this type which satisfy predicate `p` */ - def filter(p: Type => Boolean): List[Type] = new FilterTypeCollector(p) collect this + // def filter(p: Type => Boolean): List[Type] = new FilterTypeCollector(p) collect this def withFilter(p: Type => Boolean) = new FilterMapForeach(p) class FilterMapForeach(p: Type => Boolean) extends FilterTypeCollector(p){ @@ -837,7 +837,7 @@ trait Types extends api.Types { self: SymbolTable => def contains(sym: Symbol): Boolean = new ContainsCollector(sym).collect(this) /** Does this type contain a reference to this type */ - def containsTp(tp: Type): Boolean = new ContainsTypeCollector(tp).collect(this) + // def containsTp(tp: Type): Boolean = new ContainsTypeCollector(tp).collect(this) /** Is this type a subtype of that type? */ def <:<(that: Type): Boolean = { @@ -900,9 +900,9 @@ trait Types extends api.Types { self: SymbolTable => ); /** Does this type implement symbol `sym` with same or stronger type? */ - def specializes(sym: Symbol): Boolean = - if (explainSwitch) explain("specializes", specializesSym, this, sym) - else specializesSym(this, sym) + // def specializes(sym: Symbol): Boolean = + // if (explainSwitch) explain("specializes", specializesSym, this, sym) + // else specializesSym(this, sym) /** Is this type close enough to that type so that members * with the two type would override each other? @@ -1243,7 +1243,7 @@ trait Types extends api.Types { self: SymbolTable => /** Remove any annotations from this type and from any * types embedded in this type. */ - def stripAnnotations = StripAnnotationsMap(this) + // def stripAnnotations = StripAnnotationsMap(this) /** Set the self symbol of an annotated type, or do nothing * otherwise. */ @@ -2917,14 +2917,14 @@ trait Types extends api.Types { self: SymbolTable => } // Not used yet. - object HasTypeParams { - def unapply(tp: Type): Option[(List[Symbol], Type)] = tp match { - case AnnotatedType(_, tp, _) => unapply(tp) - case ExistentialType(tparams, qtpe) => Some((tparams, qtpe)) - case PolyType(tparams, restpe) => Some((tparams, restpe)) - case _ => None - } - } + // object HasTypeParams { + // def unapply(tp: Type): Option[(List[Symbol], Type)] = tp match { + // case AnnotatedType(_, tp, _) => unapply(tp) + // case ExistentialType(tparams, qtpe) => Some((tparams, qtpe)) + // case PolyType(tparams, restpe) => Some((tparams, restpe)) + // case _ => None + // } + // } //@M // a TypeVar used to be a case class with only an origin and a constr @@ -3019,7 +3019,7 @@ trait Types extends api.Types { self: SymbolTable => require(params.nonEmpty, this) override def isHigherKinded = true - override protected def typeVarString = params.map(_.name).mkString("[", ", ", "]=>" + originName) + // override protected def typeVarString = params.map(_.name).mkString("[", ", ", "]=>" + originName) } /** Precondition: zipped params/args nonEmpty. (Size equivalence enforced structurally.) @@ -3035,9 +3035,9 @@ trait Types extends api.Types { self: SymbolTable => override def params: List[Symbol] = zippedArgs map (_._1) override def typeArgs: List[Type] = zippedArgs map (_._2) - override protected def typeVarString = ( - zippedArgs map { case (p, a) => p.name + "=" + a } mkString (origin + "[", ", ", "]") - ) + // override protected def typeVarString = ( + // zippedArgs map { case (p, a) => p.name + "=" + a } mkString (origin + "[", ", ", "]") + // ) } trait UntouchableTypeVar extends TypeVar { @@ -3357,7 +3357,7 @@ trait Types extends api.Types { self: SymbolTable => ).flatten map (s => s.decodedName + tparamsOfSym(s)) mkString "#" } private def levelString = if (settings.explaintypes.value) level else "" - protected def typeVarString = originName + // protected def typeVarString = originName override def safeToString = ( if ((constr eq null) || (constr.inst eq null)) "TVar<" + originName + "=null>" else if (constr.inst ne NoType) "=?" + constr.inst @@ -3714,18 +3714,18 @@ trait Types extends api.Types { self: SymbolTable => * list given is List(AnyRefClass), the resulting type would be * e.g. Set[_ <: AnyRef] rather than Set[AnyRef] . */ - def appliedTypeAsUpperBounds(tycon: Type, args: List[Type]): Type = { - tycon match { - case TypeRef(pre, sym, _) if sameLength(sym.typeParams, args) => - val eparams = typeParamsToExistentials(sym) - val bounds = args map (TypeBounds upper _) - foreach2(eparams, bounds)(_ setInfo _) - - newExistentialType(eparams, typeRef(pre, sym, eparams map (_.tpe))) - case _ => - appliedType(tycon, args) - } - } + // def appliedTypeAsUpperBounds(tycon: Type, args: List[Type]): Type = { + // tycon match { + // case TypeRef(pre, sym, _) if sameLength(sym.typeParams, args) => + // val eparams = typeParamsToExistentials(sym) + // val bounds = args map (TypeBounds upper _) + // foreach2(eparams, bounds)(_ setInfo _) + + // newExistentialType(eparams, typeRef(pre, sym, eparams map (_.tpe))) + // case _ => + // appliedType(tycon, args) + // } + // } /** A creator and extractor for type parameterizations that strips empty type parameter lists. * Use this factory method to indicate the type has kind * (it's a polymorphic value) @@ -3829,16 +3829,16 @@ trait Types extends api.Types { self: SymbolTable => } /** Substitutes the empty scope for any non-empty decls in the type. */ - object dropAllRefinements extends TypeMap { - def apply(tp: Type): Type = tp match { - case rt @ RefinedType(parents, decls) if !decls.isEmpty => - mapOver(copyRefinedType(rt, parents, EmptyScope)) - case ClassInfoType(parents, decls, clazz) if !decls.isEmpty => - mapOver(ClassInfoType(parents, EmptyScope, clazz)) - case _ => - mapOver(tp) - } - } + // object dropAllRefinements extends TypeMap { + // def apply(tp: Type): Type = tp match { + // case rt @ RefinedType(parents, decls) if !decls.isEmpty => + // mapOver(copyRefinedType(rt, parents, EmptyScope)) + // case ClassInfoType(parents, decls, clazz) if !decls.isEmpty => + // mapOver(ClassInfoType(parents, EmptyScope, clazz)) + // case _ => + // mapOver(tp) + // } + // } /** Type with all top-level occurrences of abstract types replaced by their bounds */ def abstractTypesToBounds(tp: Type): Type = tp match { // @M don't normalize here (compiler loops on pos/bug1090.scala ) @@ -4855,14 +4855,14 @@ trait Types extends api.Types { self: SymbolTable => } } - object StripAnnotationsMap extends TypeMap { - def apply(tp: Type): Type = tp match { - case AnnotatedType(_, atp, _) => - mapOver(atp) - case tp => - mapOver(tp) - } - } + // object StripAnnotationsMap extends TypeMap { + // def apply(tp: Type): Type = tp match { + // case AnnotatedType(_, atp, _) => + // mapOver(atp) + // case tp => + // mapOver(tp) + // } + // } /** A map to convert every occurrence of a wildcard type to a fresh * type variable */ @@ -4925,7 +4925,7 @@ trait Types extends api.Types { self: SymbolTable => /** A map to implement the `filter` method. */ class FilterTypeCollector(p: Type => Boolean) extends TypeCollector[List[Type]](Nil) { - def withFilter(q: Type => Boolean) = new FilterTypeCollector(tp => p(tp) && q(tp)) + // def withFilter(q: Type => Boolean) = new FilterTypeCollector(tp => p(tp) && q(tp)) override def collect(tp: Type) = super.collect(tp).reverse @@ -5868,7 +5868,7 @@ trait Types extends api.Types { self: SymbolTable => * useful as documentation; it is likely that !isNonValueType(tp) * will serve better than isValueType(tp). */ - def isValueType(tp: Type) = isValueElseNonValue(tp) + // def isValueType(tp: Type) = isValueElseNonValue(tp) /** SLS 3.3, Non-Value Types * Is the given type definitely a non-value type, as defined in SLS 3.3? @@ -5879,7 +5879,7 @@ trait Types extends api.Types { self: SymbolTable => * not designated non-value types because there is code which depends on using * them as type arguments, but their precise status is unclear. */ - def isNonValueType(tp: Type) = !isValueElseNonValue(tp) + // def isNonValueType(tp: Type) = !isValueElseNonValue(tp) def isNonRefinementClassType(tpe: Type) = tpe match { case SingleType(_, sym) => sym.isModuleClass @@ -5928,7 +5928,7 @@ trait Types extends api.Types { self: SymbolTable => corresponds3(tps1, tps2, tparams map (_.variance))(isSubArg) } - def differentOrNone(tp1: Type, tp2: Type) = if (tp1 eq tp2) NoType else tp1 + // def differentOrNone(tp1: Type, tp2: Type) = if (tp1 eq tp2) NoType else tp1 /** Does type `tp1` conform to `tp2`? */ private def isSubType2(tp1: Type, tp2: Type, depth: Int): Boolean = { @@ -6136,14 +6136,14 @@ trait Types extends api.Types { self: SymbolTable => /** Are `tps1` and `tps2` lists of equal length such that all elements * of `tps1` conform to corresponding elements of `tps2`? */ - def isSubTypes(tps1: List[Type], tps2: List[Type]): Boolean = (tps1 corresponds tps2)(_ <:< _) + // def isSubTypes(tps1: List[Type], tps2: List[Type]): Boolean = (tps1 corresponds tps2)(_ <:< _) /** Does type `tp` implement symbol `sym` with same or * stronger type? Exact only if `sym` is a member of some * refinement type, otherwise we might return false negatives. */ - def specializesSym(tp: Type, sym: Symbol): Boolean = - specializesSym(tp, sym, AnyDepth) + // def specializesSym(tp: Type, sym: Symbol): Boolean = + // specializesSym(tp, sym, AnyDepth) def specializesSym(tp: Type, sym: Symbol, depth: Int): Boolean = tp.typeSymbol == NothingClass || @@ -6586,10 +6586,10 @@ trait Types extends api.Types { self: SymbolTable => case _ => t } - def elimRefinement(t: Type) = t match { - case RefinedType(parents, decls) if !decls.isEmpty => intersectionType(parents) - case _ => t - } + // def elimRefinement(t: Type) = t match { + // case RefinedType(parents, decls) if !decls.isEmpty => intersectionType(parents) + // case _ => t + // } /** Eliminate from list of types all elements which are a subtype * of some other element of the list. */ @@ -6634,15 +6634,15 @@ trait Types extends api.Types { self: SymbolTable => (annotationsLub(lub(ts map (_.withoutAnnotations)), ts), true) else (lub(ts), false) - def weakGlb(ts: List[Type]) = { - if (ts.nonEmpty && (ts forall isNumericValueType)) { - val nglb = numericGlb(ts) - if (nglb != NoType) (nglb, true) - else (glb(ts), false) - } else if (ts exists typeHasAnnotations) { - (annotationsGlb(glb(ts map (_.withoutAnnotations)), ts), true) - } else (glb(ts), false) - } + // def weakGlb(ts: List[Type]) = { + // if (ts.nonEmpty && (ts forall isNumericValueType)) { + // val nglb = numericGlb(ts) + // if (nglb != NoType) (nglb, true) + // else (glb(ts), false) + // } else if (ts exists typeHasAnnotations) { + // (annotationsGlb(glb(ts map (_.withoutAnnotations)), ts), true) + // } else (glb(ts), false) + // } def numericLub(ts: List[Type]) = ts reduceLeft ((t1, t2) => @@ -6650,11 +6650,11 @@ trait Types extends api.Types { self: SymbolTable => else if (isNumericSubType(t2, t1)) t1 else IntClass.tpe) - def numericGlb(ts: List[Type]) = - ts reduceLeft ((t1, t2) => - if (isNumericSubType(t1, t2)) t1 - else if (isNumericSubType(t2, t1)) t2 - else NoType) + // def numericGlb(ts: List[Type]) = + // ts reduceLeft ((t1, t2) => + // if (isNumericSubType(t1, t2)) t1 + // else if (isNumericSubType(t2, t1)) t2 + // else NoType) def isWeakSubType(tp1: Type, tp2: Type) = tp1.deconst.normalize match { @@ -7017,8 +7017,8 @@ trait Types extends api.Types { self: SymbolTable => // Without this, the matchesType call would lead to type variables on both // sides of a subtyping/equality judgement, which can lead to recursive types // being constructed. See pos/t0851 for a situation where this happens. - def suspendingTypeVarsInType[T](tp: Type)(op: => T): T = - suspendingTypeVars(typeVarsInType(tp))(op) + // def suspendingTypeVarsInType[T](tp: Type)(op: => T): T = + // suspendingTypeVars(typeVarsInType(tp))(op) @inline final def suspendingTypeVars[T](tvs: List[TypeVar])(op: => T): T = { val saved = tvs map (_.suspended) @@ -7257,7 +7257,7 @@ trait Types extends api.Types { self: SymbolTable => /** Members which can be imported into other scopes. */ - def importableMembers(clazz: Symbol): Scope = importableMembers(clazz.info) + // def importableMembers(clazz: Symbol): Scope = importableMembers(clazz.info) def importableMembers(pre: Type): Scope = pre.members filter isImportable def objToAny(tp: Type): Type = @@ -7353,7 +7353,7 @@ trait Types extends api.Types { self: SymbolTable => object TypesStats { import BaseTypeSeqsStats._ val rawTypeCount = Statistics.newCounter ("#raw type creations") - val asSeenFromCount = Statistics.newCounter ("#asSeenFrom ops") + // val asSeenFromCount = Statistics.newCounter ("#asSeenFrom ops") val subtypeCount = Statistics.newCounter ("#subtype ops") val sametypeCount = Statistics.newCounter ("#sametype ops") val lubCount = Statistics.newCounter ("#toplevel lubs/glbs") diff --git a/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala b/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala index 6170fcbb90..4dfeb913ce 100644 --- a/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala +++ b/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala @@ -95,7 +95,7 @@ class PickleBuffer(data: Array[Byte], from: Int, to: Int) { // -- Basic input routines -------------------------------------------- /** Peek at the current byte without moving the read index */ - def peekByte(): Int = bytes(readIndex) + // def peekByte(): Int = bytes(readIndex) /** Read a byte */ def readByte(): Int = { diff --git a/src/reflect/scala/reflect/internal/pickling/PickleFormat.scala b/src/reflect/scala/reflect/internal/pickling/PickleFormat.scala index 94b2f77ff9..1f522e8ee3 100644 --- a/src/reflect/scala/reflect/internal/pickling/PickleFormat.scala +++ b/src/reflect/scala/reflect/internal/pickling/PickleFormat.scala @@ -115,7 +115,7 @@ object PickleFormat { */ val MajorVersion = 5 val MinorVersion = 0 - def VersionString = "V" + MajorVersion + "." + MinorVersion + // def VersionString = "V" + MajorVersion + "." + MinorVersion final val TERMname = 1 final val TYPEname = 2 diff --git a/src/reflect/scala/reflect/internal/pickling/UnPickler.scala b/src/reflect/scala/reflect/internal/pickling/UnPickler.scala index c82546b552..76a4af850c 100644 --- a/src/reflect/scala/reflect/internal/pickling/UnPickler.scala +++ b/src/reflect/scala/reflect/internal/pickling/UnPickler.scala @@ -186,8 +186,8 @@ abstract class UnPickler /*extends scala.reflect.generic.UnPickler*/ { case _ => errorBadSignature("bad name tag: " + tag) } } - protected def readTermName(): TermName = readName().toTermName - protected def readTypeName(): TypeName = readName().toTypeName + // protected def readTermName(): TermName = readName().toTermName + // protected def readTypeName(): TypeName = readName().toTypeName private def readEnd() = readNat() + readIndex /** Read a symbol */ @@ -793,7 +793,7 @@ abstract class UnPickler /*extends scala.reflect.generic.UnPickler*/ { protected def readTreeRef(): Tree = at(readNat(), readTree) protected def readTypeNameRef(): TypeName = readNameRef().toTypeName - protected def readTermNameRef(): TermName = readNameRef().toTermName + // protected def readTermNameRef(): TermName = readNameRef().toTermName protected def readTemplateRef(): Template = readTreeRef() match { @@ -829,10 +829,10 @@ abstract class UnPickler /*extends scala.reflect.generic.UnPickler*/ { protected def errorBadSignature(msg: String) = throw new RuntimeException("malformed Scala signature of " + classRoot.name + " at " + readIndex + "; " + msg) - protected def errorMissingRequirement(name: Name, owner: Symbol): Symbol = - mirrorThatLoaded(owner).missingHook(owner, name) orElse MissingRequirementError.signal( - s"bad reference while unpickling $filename: ${name.longString} not found in ${owner.tpe.widen}" - ) + // protected def errorMissingRequirement(name: Name, owner: Symbol): Symbol = + // mirrorThatLoaded(owner).missingHook(owner, name) orElse MissingRequirementError.signal( + // s"bad reference while unpickling $filename: ${name.longString} not found in ${owner.tpe.widen}" + // ) def inferMethodAlternative(fun: Tree, argtpes: List[Type], restpe: Type) {} // can't do it; need a compiler for that. diff --git a/src/reflect/scala/reflect/internal/util/Collections.scala b/src/reflect/scala/reflect/internal/util/Collections.scala index 2ba15e0776..8d2ac3565e 100644 --- a/src/reflect/scala/reflect/internal/util/Collections.scala +++ b/src/reflect/scala/reflect/internal/util/Collections.scala @@ -40,8 +40,8 @@ trait Collections { mforeach(xss)(x => if ((res eq null) && p(x)) res = Some(x)) if (res eq null) None else res } - final def mfilter[A](xss: List[List[A]])(p: A => Boolean) = - for (xs <- xss; x <- xs; if p(x)) yield x + // final def mfilter[A](xss: List[List[A]])(p: A => Boolean) = + // for (xs <- xss; x <- xs; if p(x)) yield x final def map2[A, B, C](xs1: List[A], xs2: List[B])(f: (A, B) => C): List[C] = { val lb = new ListBuffer[C] @@ -78,18 +78,18 @@ trait Collections { lb.toList } - final def distinctBy[A, B](xs: List[A])(f: A => B): List[A] = { - val buf = new ListBuffer[A] - val seen = mutable.Set[B]() - xs foreach { x => - val y = f(x) - if (!seen(y)) { - buf += x - seen += y - } - } - buf.toList - } + // final def distinctBy[A, B](xs: List[A])(f: A => B): List[A] = { + // val buf = new ListBuffer[A] + // val seen = mutable.Set[B]() + // xs foreach { x => + // val y = f(x) + // if (!seen(y)) { + // buf += x + // seen += y + // } + // } + // buf.toList + // } @tailrec final def flattensToEmpty(xss: Seq[Seq[_]]): Boolean = { xss.isEmpty || xss.head.isEmpty && flattensToEmpty(xss.tail) @@ -189,18 +189,18 @@ trait Collections { } false } - final def forall2[A, B](xs1: List[A], xs2: List[B])(f: (A, B) => Boolean): Boolean = { - var ys1 = xs1 - var ys2 = xs2 - while (!ys1.isEmpty && !ys2.isEmpty) { - if (!f(ys1.head, ys2.head)) - return false - - ys1 = ys1.tail - ys2 = ys2.tail - } - true - } + // final def forall2[A, B](xs1: List[A], xs2: List[B])(f: (A, B) => Boolean): Boolean = { + // var ys1 = xs1 + // var ys2 = xs2 + // while (!ys1.isEmpty && !ys2.isEmpty) { + // if (!f(ys1.head, ys2.head)) + // return false + + // ys1 = ys1.tail + // ys2 = ys2.tail + // } + // true + // } final def forall3[A, B, C](xs1: List[A], xs2: List[B], xs3: List[C])(f: (A, B, C) => Boolean): Boolean = { var ys1 = xs1 var ys2 = xs2 @@ -223,5 +223,5 @@ trait Collections { } } -object Collections extends Collections { } +// object Collections extends Collections { } diff --git a/src/reflect/scala/reflect/internal/util/HashSet.scala b/src/reflect/scala/reflect/internal/util/HashSet.scala index 4135f3c469..e580315285 100644 --- a/src/reflect/scala/reflect/internal/util/HashSet.scala +++ b/src/reflect/scala/reflect/internal/util/HashSet.scala @@ -6,8 +6,8 @@ package scala.reflect.internal.util object HashSet { - def apply[T >: Null <: AnyRef](): HashSet[T] = this(16) - def apply[T >: Null <: AnyRef](label: String): HashSet[T] = this(label, 16) + // def apply[T >: Null <: AnyRef](): HashSet[T] = this(16) + // def apply[T >: Null <: AnyRef](label: String): HashSet[T] = this(label, 16) def apply[T >: Null <: AnyRef](initialCapacity: Int): HashSet[T] = this("No Label", initialCapacity) def apply[T >: Null <: AnyRef](label: String, initialCapacity: Int): HashSet[T] = new HashSet[T](label, initialCapacity) diff --git a/src/reflect/scala/reflect/internal/util/Origins.scala b/src/reflect/scala/reflect/internal/util/Origins.scala index 3259a12163..a2b9e24ebc 100644 --- a/src/reflect/scala/reflect/internal/util/Origins.scala +++ b/src/reflect/scala/reflect/internal/util/Origins.scala @@ -6,9 +6,7 @@ package scala.reflect package internal.util -import NameTransformer._ import scala.collection.{ mutable, immutable } -import Origins._ /** A debugging class for logging from whence a method is being called. * Say you wanted to discover who was calling phase_= in SymbolTable. diff --git a/src/reflect/scala/reflect/internal/util/Position.scala b/src/reflect/scala/reflect/internal/util/Position.scala index 0725e9775b..bbc95feaab 100644 --- a/src/reflect/scala/reflect/internal/util/Position.scala +++ b/src/reflect/scala/reflect/internal/util/Position.scala @@ -128,7 +128,7 @@ abstract class Position extends scala.reflect.api.Position { self => def endOrPoint: Int = point @deprecated("use point instead", "2.9.0") - def offset: Option[Int] = if (isDefined) Some(point) else None + def offset: Option[Int] = if (isDefined) Some(point) else None // used by sbt /** The same position with a different start value (if a range) */ def withStart(off: Int): Position = this diff --git a/src/reflect/scala/reflect/internal/util/SourceFile.scala b/src/reflect/scala/reflect/internal/util/SourceFile.scala index bc2d0ee4db..4d10372662 100644 --- a/src/reflect/scala/reflect/internal/util/SourceFile.scala +++ b/src/reflect/scala/reflect/internal/util/SourceFile.scala @@ -24,7 +24,7 @@ abstract class SourceFile { assert(offset < length, file + ": " + offset + " >= " + length) new OffsetPosition(this, offset) } - def position(line: Int, column: Int) : Position = new OffsetPosition(this, lineToOffset(line) + column) + // def position(line: Int, column: Int) : Position = new OffsetPosition(this, lineToOffset(line) + column) def offsetToLine(offset: Int): Int def lineToOffset(index : Int): Int @@ -37,8 +37,8 @@ abstract class SourceFile { def dbg(offset: Int) = (new OffsetPosition(this, offset)).dbgString def path = file.path - def beginsWith(offset: Int, text: String): Boolean = - (content drop offset) startsWith text + // def beginsWith(offset: Int, text: String): Boolean = + // (content drop offset) startsWith text def lineToString(index: Int): String = content drop lineToOffset(index) takeWhile (c => !isLineBreakChar(c.toChar)) mkString "" @@ -81,7 +81,7 @@ object ScriptSourceFile { } else 0 } - def stripHeader(cs: Array[Char]): Array[Char] = cs drop headerLength(cs) + // def stripHeader(cs: Array[Char]): Array[Char] = cs drop headerLength(cs) def apply(file: AbstractFile, content: Array[Char]) = { val underlying = new BatchSourceFile(file, content) @@ -91,7 +91,6 @@ object ScriptSourceFile { stripped } } -import ScriptSourceFile._ class ScriptSourceFile(underlying: BatchSourceFile, content: Array[Char], override val start: Int) extends BatchSourceFile(underlying.file, content) { override def isSelfContained = false diff --git a/src/reflect/scala/reflect/internal/util/StringOps.scala b/src/reflect/scala/reflect/internal/util/StringOps.scala index bc02ad1058..3e8de65869 100644 --- a/src/reflect/scala/reflect/internal/util/StringOps.scala +++ b/src/reflect/scala/reflect/internal/util/StringOps.scala @@ -16,24 +16,24 @@ package scala.reflect.internal.util * @version 1.0 */ trait StringOps { - def onull(s: String) = if (s == null) "" else s - def oempty(xs: String*) = xs filterNot (x => x == null || x == "") - def ojoin(xs: String*): String = oempty(xs: _*) mkString " " - def ojoin(xs: Seq[String], sep: String): String = oempty(xs: _*) mkString sep - def ojoinOr(xs: Seq[String], sep: String, orElse: String) = { - val ys = oempty(xs: _*) - if (ys.isEmpty) orElse else ys mkString sep - } - def trimTrailingSpace(s: String) = { - if (s.length == 0 || !s.charAt(s.length - 1).isWhitespace) s - else { - var idx = s.length - 1 - while (idx >= 0 && s.charAt(idx).isWhitespace) - idx -= 1 + // def onull(s: String) = if (s == null) "" else s + def oempty(xs: String*) = xs filterNot (x => x == null || x == "") + def ojoin(xs: String*): String = oempty(xs: _*) mkString " " + // def ojoin(xs: Seq[String], sep: String): String = oempty(xs: _*) mkString sep + // def ojoinOr(xs: Seq[String], sep: String, orElse: String) = { + // val ys = oempty(xs: _*) + // if (ys.isEmpty) orElse else ys mkString sep + // } + // def trimTrailingSpace(s: String) = { + // if (s.length == 0 || !s.charAt(s.length - 1).isWhitespace) s + // else { + // var idx = s.length - 1 + // while (idx >= 0 && s.charAt(idx).isWhitespace) + // idx -= 1 - s.substring(0, idx + 1) - } - } + // s.substring(0, idx + 1) + // } + // } def longestCommonPrefix(xs: List[String]): String = { if (xs.isEmpty || xs.contains("")) "" else xs.head.head match { @@ -57,13 +57,13 @@ trait StringOps { def words(str: String): List[String] = decompose(str, ' ') - def stripPrefixOpt(str: String, prefix: String): Option[String] = - if (str startsWith prefix) Some(str drop prefix.length) - else None + // def stripPrefixOpt(str: String, prefix: String): Option[String] = + // if (str startsWith prefix) Some(str drop prefix.length) + // else None - def stripSuffixOpt(str: String, suffix: String): Option[String] = - if (str endsWith suffix) Some(str dropRight suffix.length) - else None + // def stripSuffixOpt(str: String, suffix: String): Option[String] = + // if (str endsWith suffix) Some(str dropRight suffix.length) + // else None def splitWhere(str: String, f: Char => Boolean, doDropIndex: Boolean = false): Option[(String, String)] = splitAt(str, str indexWhere f, doDropIndex) diff --git a/src/reflect/scala/reflect/internal/util/TableDef.scala b/src/reflect/scala/reflect/internal/util/TableDef.scala index 8e2bcc2ff7..8208097d5c 100644 --- a/src/reflect/scala/reflect/internal/util/TableDef.scala +++ b/src/reflect/scala/reflect/internal/util/TableDef.scala @@ -67,11 +67,11 @@ class TableDef[T](_cols: Column[T]*) { override def toString = allToSeq mkString "\n" } - def formatterFor(rows: Seq[T]): T => String = { - val formatStr = new Table(rows).rowFormat + // def formatterFor(rows: Seq[T]): T => String = { + // val formatStr = new Table(rows).rowFormat - x => formatStr.format(colApply(x) : _*) - } + // x => formatStr.format(colApply(x) : _*) + // } def table(rows: Seq[T]) = new Table(rows) diff --git a/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala b/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala index 7ea8a75417..abedda8737 100644 --- a/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala +++ b/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala @@ -12,12 +12,10 @@ trait TraceSymbolActivity { if (enabled && global.isCompilerUniverse) scala.sys addShutdownHook showAllSymbols() - private type Set[T] = scala.collection.immutable.Set[T] - val allSymbols = mutable.Map[Int, Symbol]() val allChildren = mutable.Map[Int, List[Int]]() withDefaultValue Nil val prevOwners = mutable.Map[Int, List[(Int, Phase)]]() withDefaultValue Nil - val symsCaused = mutable.Map[Int, Int]() withDefaultValue 0 + // val symsCaused = mutable.Map[Int, Int]() withDefaultValue 0 val allTrees = mutable.Set[Tree]() def recordSymbolsInTree(tree: Tree) { diff --git a/src/reflect/scala/reflect/internal/util/WeakHashSet.scala b/src/reflect/scala/reflect/internal/util/WeakHashSet.scala index 9882aad5e5..41e74f80e9 100644 --- a/src/reflect/scala/reflect/internal/util/WeakHashSet.scala +++ b/src/reflect/scala/reflect/internal/util/WeakHashSet.scala @@ -1,9 +1,6 @@ package scala.reflect.internal.util import scala.collection.mutable -import scala.collection.mutable.ArrayBuffer -import scala.collection.mutable.Builder -import scala.collection.mutable.SetBuilder import scala.collection.generic.Clearable import scala.runtime.AbstractFunction1 diff --git a/src/reflect/scala/reflect/io/AbstractFile.scala b/src/reflect/scala/reflect/io/AbstractFile.scala index 15befb67f1..de37176cd5 100644 --- a/src/reflect/scala/reflect/io/AbstractFile.scala +++ b/src/reflect/scala/reflect/io/AbstractFile.scala @@ -14,9 +14,9 @@ import scala.collection.mutable.ArrayBuffer /** * An abstraction over files for use in the reflection/compiler libraries. - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' - * + * * @author Philippe Altherr * @version 1.0, 23/03/2004 */ @@ -85,7 +85,7 @@ object AbstractFile { * all other cases, the class SourceFile is used, which honors * global.settings.encoding.value. *

- * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ abstract class AbstractFile extends Iterable[AbstractFile] { @@ -195,9 +195,9 @@ abstract class AbstractFile extends Iterable[AbstractFile] { * @param directory ... * @return ... */ - def lookupPath(path: String, directory: Boolean): AbstractFile = { - lookup((f, p, dir) => f.lookupName(p, dir), path, directory) - } + // def lookupPath(path: String, directory: Boolean): AbstractFile = { + // lookup((f, p, dir) => f.lookupName(p, dir), path, directory) + // } /** Return an abstract file that does not check that `path` denotes * an existing file. diff --git a/src/reflect/scala/reflect/io/Directory.scala b/src/reflect/scala/reflect/io/Directory.scala index c040d1eac5..3a21509457 100644 --- a/src/reflect/scala/reflect/io/Directory.scala +++ b/src/reflect/scala/reflect/io/Directory.scala @@ -14,12 +14,12 @@ import java.io.{ File => JFile } * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ object Directory { - import scala.util.Properties.{ tmpDir, userHome, userDir } + import scala.util.Properties.{ userHome, userDir } private def normalizePath(s: String) = Some(apply(Path(s).normalize)) def Current: Option[Directory] = if (userDir == "") None else normalizePath(userDir) - def Home: Option[Directory] = if (userHome == "") None else normalizePath(userHome) - def TmpDir: Option[Directory] = if (tmpDir == "") None else normalizePath(tmpDir) + // def Home: Option[Directory] = if (userHome == "") None else normalizePath(userHome) + // def TmpDir: Option[Directory] = if (tmpDir == "") None else normalizePath(tmpDir) def apply(path: Path): Directory = path.toDirectory @@ -30,20 +30,19 @@ object Directory { path.createDirectory() } } -import Path._ /** An abstraction for directories. * * @author Paul Phillips * @since 2.8 - * + * * ''Note: This is library is considered experimental and should not be used unless you know what you are doing.'' */ class Directory(jfile: JFile) extends Path(jfile) { override def toAbsolute: Directory = if (isAbsolute) this else super.toAbsolute.toDirectory override def toDirectory: Directory = this override def toFile: File = new File(jfile) - override def isValid = jfile.isDirectory() || !jfile.exists() + // override def isValid = jfile.isDirectory() || !jfile.exists() override def normalize: Directory = super.normalize.toDirectory /** An iterator over the contents of this directory. @@ -60,7 +59,7 @@ class Directory(jfile: JFile) extends Path(jfile) { override def walkFilter(cond: Path => Boolean): Iterator[Path] = list filter cond flatMap (_ walkFilter cond) - def deepDirs: Iterator[Directory] = Path.onlyDirs(deepList()) + // def deepDirs: Iterator[Directory] = Path.onlyDirs(deepList()) def deepFiles: Iterator[File] = Path.onlyFiles(deepList()) /** If optional depth argument is not given, will recurse @@ -74,6 +73,6 @@ class Directory(jfile: JFile) extends Path(jfile) { /** An iterator over the directories underneath this directory, * to the (optionally) given depth. */ - def subdirs(depth: Int = 1): Iterator[Directory] = - deepList(depth) collect { case x: Directory => x } + // def subdirs(depth: Int = 1): Iterator[Directory] = + // deepList(depth) collect { case x: Directory => x } } diff --git a/src/reflect/scala/reflect/io/File.scala b/src/reflect/scala/reflect/io/File.scala index 736ba5d51e..04e122af67 100644 --- a/src/reflect/scala/reflect/io/File.scala +++ b/src/reflect/scala/reflect/io/File.scala @@ -35,12 +35,12 @@ object File { type HasClose = { def close(): Unit } - def closeQuietly(target: HasClose) { - try target.close() catch { case e: IOException => } - } - def closeQuietly(target: JCloseable) { - try target.close() catch { case e: IOException => } - } + // def closeQuietly(target: HasClose) { + // try target.close() catch { case e: IOException => } + // } + // def closeQuietly(target: JCloseable) { + // try target.close() catch { case e: IOException => } + // } // this is a workaround for http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6503430 // we are using a static initializer to statically initialize a java class so we don't @@ -65,8 +65,8 @@ object File { // case _: IllegalArgumentException | _: IllegalStateException | _: IOException | _: SecurityException => () // } } -import File._ -import Path._ +// import File._ +// import Path._ /** An abstraction for files. For character data, a Codec * can be supplied at either creation time or when a method @@ -76,19 +76,19 @@ import Path._ * * @author Paul Phillips * @since 2.8 - * + * * ''Note: This is library is considered experimental and should not be used unless you know what you are doing.'' */ class File(jfile: JFile)(implicit constructorCodec: Codec) extends Path(jfile) with Streamable.Chars { override val creationCodec = constructorCodec - def withCodec(codec: Codec): File = new File(jfile)(codec) + // def withCodec(codec: Codec): File = new File(jfile)(codec) override def addExtension(ext: String): File = super.addExtension(ext).toFile override def toAbsolute: File = if (isAbsolute) this else super.toAbsolute.toFile override def toDirectory: Directory = new Directory(jfile) override def toFile: File = this override def normalize: File = super.normalize.toFile - override def isValid = jfile.isFile() || !jfile.exists() + // override def isValid = jfile.isFile() || !jfile.exists() override def length = super[Path].length override def walkFilter(cond: Path => Boolean): Iterator[Path] = if (cond(this)) Iterator.single(this) else Iterator.empty @@ -99,14 +99,14 @@ class File(jfile: JFile)(implicit constructorCodec: Codec) extends Path(jfile) w /** Obtains a OutputStream. */ def outputStream(append: Boolean = false) = new FileOutputStream(jfile, append) def bufferedOutput(append: Boolean = false) = new BufferedOutputStream(outputStream(append)) - def printStream(append: Boolean = false) = new PrintStream(outputStream(append), true) + // def printStream(append: Boolean = false) = new PrintStream(outputStream(append), true) /** Obtains an OutputStreamWriter wrapped around a FileOutputStream. * This should behave like a less broken version of java.io.FileWriter, * in that unlike the java version you can specify the encoding. */ - def writer(): OutputStreamWriter = writer(false) - def writer(append: Boolean): OutputStreamWriter = writer(append, creationCodec) + // def writer(): OutputStreamWriter = writer(false) + // def writer(append: Boolean): OutputStreamWriter = writer(append, creationCodec) def writer(append: Boolean, codec: Codec): OutputStreamWriter = new OutputStreamWriter(outputStream(append), codec.charSet) @@ -118,7 +118,7 @@ class File(jfile: JFile)(implicit constructorCodec: Codec) extends Path(jfile) w new BufferedWriter(writer(append, codec)) def printWriter(): PrintWriter = new PrintWriter(bufferedWriter(), true) - def printWriter(append: Boolean): PrintWriter = new PrintWriter(bufferedWriter(append), true) + // def printWriter(append: Boolean): PrintWriter = new PrintWriter(bufferedWriter(append), true) /** Creates a new file and writes all the Strings to it. */ def writeAll(strings: String*): Unit = { @@ -127,11 +127,11 @@ class File(jfile: JFile)(implicit constructorCodec: Codec) extends Path(jfile) w finally out.close() } - def writeBytes(bytes: Array[Byte]): Unit = { - val out = bufferedOutput() - try out write bytes - finally out.close() - } + // def writeBytes(bytes: Array[Byte]): Unit = { + // val out = bufferedOutput() + // try out write bytes + // finally out.close() + // } def appendAll(strings: String*): Unit = { val out = bufferedWriter(append = true) @@ -150,38 +150,38 @@ class File(jfile: JFile)(implicit constructorCodec: Codec) extends Path(jfile) w try Some(slurp()) catch { case _: IOException => None } - def copyTo(destPath: Path, preserveFileDate: Boolean = false): Boolean = { - val CHUNK = 1024 * 1024 * 16 // 16 MB - val dest = destPath.toFile - if (!isValid) fail("Source %s is not a valid file." format name) - if (this.normalize == dest.normalize) fail("Source and destination are the same.") - if (!dest.parent.exists) fail("Destination cannot be created.") - if (dest.exists && !dest.canWrite) fail("Destination exists but is not writable.") - if (dest.isDirectory) fail("Destination exists but is a directory.") - - lazy val in_s = inputStream() - lazy val out_s = dest.outputStream() - lazy val in = in_s.getChannel() - lazy val out = out_s.getChannel() - - try { - val size = in.size() - var pos, count = 0L - while (pos < size) { - count = (size - pos) min CHUNK - pos += out.transferFrom(in, pos, count) - } - } - finally List[HasClose](out, out_s, in, in_s) foreach closeQuietly - - if (this.length != dest.length) - fail("Failed to completely copy %s to %s".format(name, dest.name)) - - if (preserveFileDate) - dest.lastModified = this.lastModified - - true - } + // def copyTo(destPath: Path, preserveFileDate: Boolean = false): Boolean = { + // val CHUNK = 1024 * 1024 * 16 // 16 MB + // val dest = destPath.toFile + // if (!isValid) fail("Source %s is not a valid file." format name) + // if (this.normalize == dest.normalize) fail("Source and destination are the same.") + // if (!dest.parent.exists) fail("Destination cannot be created.") + // if (dest.exists && !dest.canWrite) fail("Destination exists but is not writable.") + // if (dest.isDirectory) fail("Destination exists but is a directory.") + + // lazy val in_s = inputStream() + // lazy val out_s = dest.outputStream() + // lazy val in = in_s.getChannel() + // lazy val out = out_s.getChannel() + + // try { + // val size = in.size() + // var pos, count = 0L + // while (pos < size) { + // count = (size - pos) min CHUNK + // pos += out.transferFrom(in, pos, count) + // } + // } + // finally List[HasClose](out, out_s, in, in_s) foreach closeQuietly + + // if (this.length != dest.length) + // fail("Failed to completely copy %s to %s".format(name, dest.name)) + + // if (preserveFileDate) + // dest.lastModified = this.lastModified + + // true + // } /** Reflection since we're into the java 6+ API. */ diff --git a/src/reflect/scala/reflect/io/Path.scala b/src/reflect/scala/reflect/io/Path.scala index 36fdc04db4..77b5065db1 100644 --- a/src/reflect/scala/reflect/io/Path.scala +++ b/src/reflect/scala/reflect/io/Path.scala @@ -27,7 +27,7 @@ import scala.language.implicitConversions * * @author Paul Phillips * @since 2.8 - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ object Path { @@ -65,11 +65,11 @@ object Path { def onlyDirs(xs: Iterator[Path]): Iterator[Directory] = xs filter (_.isDirectory) map (_.toDirectory) def onlyDirs(xs: List[Path]): List[Directory] = xs filter (_.isDirectory) map (_.toDirectory) def onlyFiles(xs: Iterator[Path]): Iterator[File] = xs filter (_.isFile) map (_.toFile) - def onlyFiles(xs: List[Path]): List[File] = xs filter (_.isFile) map (_.toFile) + // def onlyFiles(xs: List[Path]): List[File] = xs filter (_.isFile) map (_.toFile) def roots: List[Path] = java.io.File.listRoots().toList map Path.apply - def apply(segments: Seq[String]): Path = apply(segments mkString java.io.File.separator) + // def apply(segments: Seq[String]): Path = apply(segments mkString java.io.File.separator) def apply(path: String): Path = apply(new JFile(path)) def apply(jfile: JFile): Path = if (jfile.isFile) new File(jfile) @@ -84,7 +84,7 @@ import Path._ /** The Path constructor is private so we can enforce some * semantics regarding how a Path might relate to the world. - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ class Path private[io] (val jfile: JFile) { @@ -95,7 +95,7 @@ class Path private[io] (val jfile: JFile) { // contents of the filesystem are in agreement. All objects are // valid except File objects whose path points to a directory and // Directory objects whose path points to a file. - def isValid: Boolean = true + // def isValid: Boolean = true // conversions def toFile: File = new File(jfile) @@ -136,7 +136,7 @@ class Path private[io] (val jfile: JFile) { def name: String = jfile.getName() def path: String = jfile.getPath() def normalize: Path = Path(jfile.getAbsolutePath()) - def isRootPath: Boolean = roots exists (_ isSame this) + // def isRootPath: Boolean = roots exists (_ isSame this) def resolve(other: Path) = if (other.isAbsolute || isEmpty) other else /(other) def relativize(other: Path) = { @@ -153,7 +153,7 @@ class Path private[io] (val jfile: JFile) { } // derived from identity - def root: Option[Path] = roots find (this startsWith _) + // def root: Option[Path] = roots find (this startsWith _) def segments: List[String] = (path split separator).toList filterNot (_.length == 0) /** * @return The path of the parent directory, or root if path is already root @@ -213,22 +213,22 @@ class Path private[io] (val jfile: JFile) { def canRead = jfile.canRead() def canWrite = jfile.canWrite() def exists = jfile.exists() - def notExists = try !jfile.exists() catch { case ex: SecurityException => false } + // def notExists = try !jfile.exists() catch { case ex: SecurityException => false } def isFile = jfile.isFile() def isDirectory = jfile.isDirectory() def isAbsolute = jfile.isAbsolute() - def isHidden = jfile.isHidden() + // def isHidden = jfile.isHidden() def isEmpty = path.length == 0 // Information def lastModified = jfile.lastModified() - def lastModified_=(time: Long) = jfile setLastModified time // should use setXXX function? + // def lastModified_=(time: Long) = jfile setLastModified time // should use setXXX function? def length = jfile.length() // Boolean path comparisons def endsWith(other: Path) = segments endsWith other.segments - def startsWith(other: Path) = segments startsWith other.segments + // def startsWith(other: Path) = segments startsWith other.segments def isSame(other: Path) = toCanonical == other.toCanonical def isFresher(other: Path) = lastModified > other.lastModified @@ -248,7 +248,7 @@ class Path private[io] (val jfile: JFile) { // deletions def delete() = jfile.delete() - def deleteIfExists() = if (jfile.exists()) delete() else false + // def deleteIfExists() = if (jfile.exists()) delete() else false /** Deletes the path recursively. Returns false on failure. * Use with caution! @@ -270,11 +270,11 @@ class Path private[io] (val jfile: JFile) { length == 0 } - def touch(modTime: Long = System.currentTimeMillis) = { - createFile() - if (isFile) - lastModified = modTime - } + // def touch(modTime: Long = System.currentTimeMillis) = { + // createFile() + // if (isFile) + // lastModified = modTime + // } // todo // def copyTo(target: Path, options ...): Boolean diff --git a/src/reflect/scala/reflect/io/PlainFile.scala b/src/reflect/scala/reflect/io/PlainFile.scala index 82b0568657..6ee51d3d37 100644 --- a/src/reflect/scala/reflect/io/PlainFile.scala +++ b/src/reflect/scala/reflect/io/PlainFile.scala @@ -8,17 +8,17 @@ package scala.reflect package io import java.io.{ FileInputStream, FileOutputStream, IOException } -import PartialFunction._ + /** ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ object PlainFile { /** * If the specified File exists, returns an abstract file backed * by it. Otherwise, returns null. */ - def fromPath(file: Path): PlainFile = - if (file.isDirectory) new PlainDirectory(file.toDirectory) - else if (file.isFile) new PlainFile(file) - else null + // def fromPath(file: Path): PlainFile = + // if (file.isDirectory) new PlainDirectory(file.toDirectory) + // else if (file.isFile) new PlainFile(file) + // else null } /** ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ class PlainDirectory(givenPath: Directory) extends PlainFile(givenPath) { @@ -28,7 +28,7 @@ class PlainDirectory(givenPath: Directory) extends PlainFile(givenPath) { } /** This class implements an abstract file backed by a File. - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ class PlainFile(val givenPath: Path) extends AbstractFile { diff --git a/src/reflect/scala/reflect/io/Streamable.scala b/src/reflect/scala/reflect/io/Streamable.scala index 61ec8a4c23..615f44acc5 100644 --- a/src/reflect/scala/reflect/io/Streamable.scala +++ b/src/reflect/scala/reflect/io/Streamable.scala @@ -17,14 +17,14 @@ import Path.fail * * @author Paul Phillips * @since 2.8 - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ object Streamable { /** Traits which can be viewed as a sequence of bytes. Source types * which know their length should override def length: Long for more * efficient method implementations. - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ trait Bytes { @@ -69,7 +69,7 @@ object Streamable { } /** For objects which can be viewed as Chars. - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ trait Chars extends Bytes { @@ -81,7 +81,7 @@ object Streamable { */ def creationCodec: Codec = implicitly[Codec] - def chars(): BufferedSource = chars(creationCodec) + // def chars(): BufferedSource = chars(creationCodec) def chars(codec: Codec): BufferedSource = Source.fromInputStream(inputStream())(codec) def lines(): Iterator[String] = lines(creationCodec) @@ -89,7 +89,7 @@ object Streamable { /** Obtains an InputStreamReader wrapped around a FileInputStream. */ - def reader(): InputStreamReader = reader(creationCodec) + // def reader(): InputStreamReader = reader(creationCodec) def reader(codec: Codec): InputStreamReader = new InputStreamReader(inputStream, codec.charSet) /** Wraps a BufferedReader around the result of reader(). diff --git a/src/reflect/scala/reflect/io/VirtualDirectory.scala b/src/reflect/scala/reflect/io/VirtualDirectory.scala index 78713c2ae0..72ffff2aa9 100644 --- a/src/reflect/scala/reflect/io/VirtualDirectory.scala +++ b/src/reflect/scala/reflect/io/VirtualDirectory.scala @@ -11,7 +11,7 @@ import scala.collection.mutable * An in-memory directory. * * @author Lex Spoon - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ class VirtualDirectory(val name: String, maybeContainer: Option[VirtualDirectory]) @@ -26,7 +26,8 @@ extends AbstractFile { def container = maybeContainer.get def isDirectory = true - var lastModified: Long = System.currentTimeMillis + val lastModified: Long = System.currentTimeMillis + // var lastModified: Long = System.currentTimeMillis override def file = null override def input = sys.error("directories cannot be read") diff --git a/src/reflect/scala/reflect/io/VirtualFile.scala b/src/reflect/scala/reflect/io/VirtualFile.scala index 95f4429fad..014e02c6cd 100644 --- a/src/reflect/scala/reflect/io/VirtualFile.scala +++ b/src/reflect/scala/reflect/io/VirtualFile.scala @@ -14,7 +14,7 @@ import java.io.{ File => JFile } * * @author Philippe Altherr * @version 1.0, 23/03/2004 - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ class VirtualFile(val name: String, override val path: String) extends AbstractFile { @@ -65,7 +65,7 @@ class VirtualFile(val name: String, override val path: String) extends AbstractF /** Returns the time that this abstract file was last modified. */ private var _lastModified: Long = 0 def lastModified: Long = _lastModified - def lastModified_=(x: Long) = _lastModified = x + // def lastModified_=(x: Long) = _lastModified = x /** Returns all abstract subfiles of this abstract directory. */ def iterator: Iterator[AbstractFile] = { diff --git a/src/reflect/scala/reflect/io/ZipArchive.scala b/src/reflect/scala/reflect/io/ZipArchive.scala index 3b57721e89..0e69834d26 100644 --- a/src/reflect/scala/reflect/io/ZipArchive.scala +++ b/src/reflect/scala/reflect/io/ZipArchive.scala @@ -20,12 +20,12 @@ import scala.annotation.tailrec * @author Philippe Altherr (original version) * @author Paul Phillips (this one) * @version 2.0, - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ object ZipArchive { - def fromPath(path: String): FileZipArchive = fromFile(new JFile(path)) - def fromPath(path: Path): FileZipArchive = fromFile(path.toFile) + // def fromPath(path: String): FileZipArchive = fromFile(new JFile(path)) + // def fromPath(path: Path): FileZipArchive = fromFile(path.toFile) /** * @param file a File @@ -41,7 +41,7 @@ object ZipArchive { * @return A ZipArchive backed by the given url. */ def fromURL(url: URL): URLZipArchive = new URLZipArchive(url) - def fromURL(url: String): URLZipArchive = fromURL(new URL(url)) + // def fromURL(url: String): URLZipArchive = fromURL(new URL(url)) private def dirName(path: String) = splitPath(path, true) private def baseName(path: String) = splitPath(path, false) @@ -79,7 +79,7 @@ abstract class ZipArchive(override val file: JFile) extends AbstractFile with Eq else Iterator(f) } } - def deepIterator = walkIterator(iterator) + // def deepIterator = walkIterator(iterator) /** ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ sealed abstract class Entry(path: String) extends VirtualFile(baseName(path), path) { // have to keep this name for compat with sbt's compiler-interface diff --git a/src/reflect/scala/reflect/macros/TreeBuilder.scala b/src/reflect/scala/reflect/macros/TreeBuilder.scala index 204dc40858..fbbbe13201 100644 --- a/src/reflect/scala/reflect/macros/TreeBuilder.scala +++ b/src/reflect/scala/reflect/macros/TreeBuilder.scala @@ -11,7 +11,6 @@ abstract class TreeBuilder { val global: Universe import global._ - import definitions._ /** Builds a reference to value whose type is given stable prefix. * The type must be suitable for this. For example, it diff --git a/src/reflect/scala/reflect/runtime/JavaMirrors.scala b/src/reflect/scala/reflect/runtime/JavaMirrors.scala index 44fbd55162..07599e095d 100644 --- a/src/reflect/scala/reflect/runtime/JavaMirrors.scala +++ b/src/reflect/scala/reflect/runtime/JavaMirrors.scala @@ -22,7 +22,6 @@ import internal.Flags._ import ReflectionUtils.{staticSingletonInstance, innerSingletonInstance} import scala.language.existentials import scala.runtime.{ScalaRunTime, BoxesRunTime} -import scala.reflect.internal.util.Collections._ private[reflect] trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUniverse: SymbolTable => @@ -841,13 +840,13 @@ private[reflect] trait JavaMirrors extends internal.SymbolTable with api.JavaUni * @return A Scala field object that corresponds to `jfield`. * // ??? should we return the getter instead? */ - def fieldToScala(jfield: jField): TermSymbol = - toScala(fieldCache, jfield)(_ fieldToScala1 _) + // def fieldToScala(jfield: jField): TermSymbol = + // toScala(fieldCache, jfield)(_ fieldToScala1 _) - private def fieldToScala1(jfield: jField): TermSymbol = { - val owner = followStatic(classToScala(jfield.getDeclaringClass), jfield.getModifiers) - (lookup(owner, jfield.getName) suchThat (!_.isMethod) orElse jfieldAsScala(jfield)).asTerm - } + // private def fieldToScala1(jfield: jField): TermSymbol = { + // val owner = followStatic(classToScala(jfield.getDeclaringClass), jfield.getModifiers) + // (lookup(owner, jfield.getName) suchThat (!_.isMethod) orElse jfieldAsScala(jfield)).asTerm + // } /** * The Scala package corresponding to given Java package @@ -1115,9 +1114,9 @@ private[reflect] trait JavaMirrors extends internal.SymbolTable with api.JavaUni /** Optionally, the Java package corresponding to a given Scala package, or None if no such Java package exists. * @param pkg The Scala package */ - def packageToJavaOption(pkg: ModuleSymbol): Option[jPackage] = packageCache.toJavaOption(pkg) { - Option(jPackage.getPackage(pkg.fullName.toString)) - } + // def packageToJavaOption(pkg: ModuleSymbol): Option[jPackage] = packageCache.toJavaOption(pkg) { + // Option(jPackage.getPackage(pkg.fullName.toString)) + // } /** The Java class corresponding to given Scala class. * Note: This only works for diff --git a/src/reflect/scala/reflect/runtime/JavaUniverse.scala b/src/reflect/scala/reflect/runtime/JavaUniverse.scala index 0f70a676fa..a12e7d43d4 100644 --- a/src/reflect/scala/reflect/runtime/JavaUniverse.scala +++ b/src/reflect/scala/reflect/runtime/JavaUniverse.scala @@ -1,8 +1,6 @@ package scala.reflect package runtime -import internal.{SomePhase, NoPhase, Phase, TreeGen} - /** An implementation of [[scala.reflect.api.Universe]] for runtime reflection using JVM classloaders. * * Should not be instantiated directly, use [[scala.reflect.runtime.universe]] instead. @@ -11,7 +9,7 @@ import internal.{SomePhase, NoPhase, Phase, TreeGen} */ class JavaUniverse extends internal.SymbolTable with ReflectSetup with runtime.SymbolTable { self => - def picklerPhase = SomePhase + def picklerPhase = internal.SomePhase def forInteractive = false def forScaladoc = false @@ -26,4 +24,3 @@ class JavaUniverse extends internal.SymbolTable with ReflectSetup with runtime.S init() } - diff --git a/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala b/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala index 366b4319c3..b415abecb1 100644 --- a/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala +++ b/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala @@ -83,8 +83,8 @@ private[reflect] trait SynchronizedSymbols extends internal.Symbols { self: Symb override protected def createPackageObjectClassSymbol(pos: Position, newFlags: Long): PackageObjectClassSymbol = new PackageObjectClassSymbol(this, pos) with SynchronizedClassSymbol initFlags newFlags - override protected def createTermSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol = - new TermSymbol(this, pos, name) with SynchronizedTermSymbol initFlags newFlags + // override protected def createTermSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol = + // new TermSymbol(this, pos, name) with SynchronizedTermSymbol initFlags newFlags override protected def createMethodSymbol(name: TermName, pos: Position, newFlags: Long): MethodSymbol = new MethodSymbol(this, pos, name) with SynchronizedMethodSymbol initFlags newFlags diff --git a/src/reflect/scala/reflect/runtime/package.scala b/src/reflect/scala/reflect/runtime/package.scala index b97913daf0..eadbc0c52e 100644 --- a/src/reflect/scala/reflect/runtime/package.scala +++ b/src/reflect/scala/reflect/runtime/package.scala @@ -6,7 +6,7 @@ package scala.reflect package object runtime { /** The entry point into Scala runtime reflection. - * + * * To use Scala runtime reflection, simply use or import `scala.reflect.runtime.universe._` * * See [[scala.reflect.api.Universe]] or the -- cgit v1.2.3 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 +- .../scala/util/continuations/ControlContext.scala | 4 +- .../library/scala/util/continuations/package.scala | 6 +- src/detach/plugin/scala/tools/detach/Detach.scala | 2 +- src/partest/scala/tools/partest/CompilerTest.scala | 3 +- src/partest/scala/tools/partest/SecurityTest.scala | 22 +- src/partest/scala/tools/partest/TestUtil.scala | 14 +- .../partest/instrumented/Instrumentation.scala | 1 - .../tools/partest/nest/ConsoleFileManager.scala | 20 +- .../scala/tools/partest/nest/ConsoleRunner.scala | 2 +- .../scala/tools/partest/nest/FileManager.scala | 8 +- src/partest/scala/tools/partest/nest/NestUI.scala | 20 +- .../tools/partest/nest/ReflectiveRunner.scala | 9 +- .../scala/tools/partest/nest/RunnerManager.scala | 8 +- .../scala/tools/partest/nest/RunnerUtils.scala | 46 ++-- src/partest/scala/tools/partest/package.scala | 8 +- .../scala/tools/partest/utils/PrintMgr.scala | 104 ++++----- .../scala/reflect/internal/AnnotationInfos.scala | 11 +- .../scala/reflect/internal/BuildUtils.scala | 2 + .../reflect/internal/ClassfileConstants.scala | 12 +- .../scala/reflect/internal/Definitions.scala | 133 +++++------ .../reflect/internal/ExistentialsAndSkolems.scala | 1 + src/reflect/scala/reflect/internal/Importers.scala | 2 +- src/reflect/scala/reflect/internal/Names.scala | 64 +++--- src/reflect/scala/reflect/internal/Printers.scala | 4 +- src/reflect/scala/reflect/internal/Scopes.scala | 2 +- src/reflect/scala/reflect/internal/StdNames.scala | 242 ++++++++++----------- .../scala/reflect/internal/SymbolTable.scala | 3 +- src/reflect/scala/reflect/internal/Symbols.scala | 125 +++++------ src/reflect/scala/reflect/internal/TreeGen.scala | 12 +- src/reflect/scala/reflect/internal/TreeInfo.scala | 58 ++--- src/reflect/scala/reflect/internal/Trees.scala | 2 +- .../scala/reflect/internal/TypeDebugging.scala | 4 +- src/reflect/scala/reflect/internal/Types.scala | 196 ++++++++--------- .../reflect/internal/pickling/PickleBuffer.scala | 2 +- .../reflect/internal/pickling/PickleFormat.scala | 2 +- .../reflect/internal/pickling/UnPickler.scala | 14 +- .../scala/reflect/internal/util/Collections.scala | 54 ++--- .../scala/reflect/internal/util/HashSet.scala | 4 +- .../scala/reflect/internal/util/Origins.scala | 2 + .../scala/reflect/internal/util/Position.scala | 2 +- .../scala/reflect/internal/util/SourceFile.scala | 9 +- .../scala/reflect/internal/util/StringOps.scala | 46 ++-- .../scala/reflect/internal/util/TableDef.scala | 8 +- .../internal/util/TraceSymbolActivity.scala | 4 +- .../scala/reflect/internal/util/WeakHashSet.scala | 3 + src/reflect/scala/reflect/io/AbstractFile.scala | 12 +- src/reflect/scala/reflect/io/Directory.scala | 17 +- src/reflect/scala/reflect/io/File.scala | 104 ++++----- src/reflect/scala/reflect/io/Path.scala | 34 +-- src/reflect/scala/reflect/io/PlainFile.scala | 12 +- src/reflect/scala/reflect/io/Streamable.scala | 10 +- .../scala/reflect/io/VirtualDirectory.scala | 5 +- src/reflect/scala/reflect/io/VirtualFile.scala | 4 +- src/reflect/scala/reflect/io/ZipArchive.scala | 10 +- src/reflect/scala/reflect/macros/TreeBuilder.scala | 1 + .../scala/reflect/runtime/JavaMirrors.scala | 19 +- .../scala/reflect/runtime/JavaUniverse.scala | 5 +- .../reflect/runtime/SynchronizedSymbols.scala | 4 +- src/reflect/scala/reflect/runtime/package.scala | 2 +- 193 files changed, 2660 insertions(+), 2579 deletions(-) (limited to 'src/compiler/scala/tools') 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) diff --git a/src/continuations/library/scala/util/continuations/ControlContext.scala b/src/continuations/library/scala/util/continuations/ControlContext.scala index c196809da9..44a5b537b6 100644 --- a/src/continuations/library/scala/util/continuations/ControlContext.scala +++ b/src/continuations/library/scala/util/continuations/ControlContext.scala @@ -183,7 +183,7 @@ final class ControlContext[+A,-B,+C](val fun: (A => B, Exception => B) => C, val // need filter or other functions? - final def flatMapCatch[A1>:A,B1<:B,C1>:C<:B1](pf: PartialFunction[Exception, ControlContext[A1,B1,C1]]): ControlContext[A1,B1,C1] = { // called by codegen from SelectiveCPSTransform + final def flatMapCatch[A1>:A,B1<:B,C1>:C<:B1](pf: PartialFunction[Exception, ControlContext[A1,B1,C1]]): ControlContext[A1,B1,C1] = { if (fun eq null) this else { @@ -209,7 +209,7 @@ final class ControlContext[+A,-B,+C](val fun: (A => B, Exception => B) => C, val } } - final def mapFinally(f: () => Unit): ControlContext[A,B,C] = { // called in code generated by SelectiveCPSTransform + final def mapFinally(f: () => Unit): ControlContext[A,B,C] = { if (fun eq null) { try { f() diff --git a/src/continuations/library/scala/util/continuations/package.scala b/src/continuations/library/scala/util/continuations/package.scala index 573fae85e7..1b50956c93 100644 --- a/src/continuations/library/scala/util/continuations/package.scala +++ b/src/continuations/library/scala/util/continuations/package.scala @@ -166,7 +166,7 @@ package object continuations { throw new NoSuchMethodException("this code has to be compiled with the Scala continuations plugin enabled") } - def shiftUnitR[A,B](x: A): ControlContext[A,B,B] = { // called in code generated by SelectiveCPSTransform + def shiftUnitR[A,B](x: A): ControlContext[A,B,B] = { new ControlContext[A, B, B](null, x) } @@ -176,11 +176,11 @@ package object continuations { * a final result. * @see shift */ - def shiftR[A,B,C](fun: (A => B) => C): ControlContext[A,B,C] = { // called in code generated by SelectiveCPSTransform + def shiftR[A,B,C](fun: (A => B) => C): ControlContext[A,B,C] = { new ControlContext((f:A=>B,g:Exception=>B) => fun(f), null.asInstanceOf[A]) } - def reifyR[A,B,C](ctx: => ControlContext[A,B,C]): ControlContext[A,B,C] = { // called in code generated by SelectiveCPSTransform + def reifyR[A,B,C](ctx: => ControlContext[A,B,C]): ControlContext[A,B,C] = { ctx } diff --git a/src/detach/plugin/scala/tools/detach/Detach.scala b/src/detach/plugin/scala/tools/detach/Detach.scala index 499a97b761..73f6cde58c 100644 --- a/src/detach/plugin/scala/tools/detach/Detach.scala +++ b/src/detach/plugin/scala/tools/detach/Detach.scala @@ -73,7 +73,7 @@ abstract class Detach extends PluginComponent } private val serializableAnnotationInfo = - AnnotationInfo(requiredClass[scala.annotation.serializable].tpe, List(), List()) + AnnotationInfo(SerializableAttr.tpe, List(), List()) /* private val throwsAnnotationInfo = { val RemoteExceptionClass = definitions.getClass("java.rmi.RemoteException") diff --git a/src/partest/scala/tools/partest/CompilerTest.scala b/src/partest/scala/tools/partest/CompilerTest.scala index bb0732dcc6..d73d99bc89 100644 --- a/src/partest/scala/tools/partest/CompilerTest.scala +++ b/src/partest/scala/tools/partest/CompilerTest.scala @@ -21,7 +21,7 @@ abstract class CompilerTest extends DirectTest { lazy val global: Global = newCompiler() lazy val units = compilationUnits(global)(sources: _ *) import global._ - import definitions.{ compilerTypeFromTag } + import definitions._ override def extraSettings = "-usejavacp -d " + testOutput.path @@ -32,6 +32,7 @@ abstract class CompilerTest extends DirectTest { def sources: List[String] = List(code) // Utility functions + class MkType(sym: Symbol) { def apply[M](implicit t: ru.TypeTag[M]): Type = if (sym eq NoSymbol) NoType diff --git a/src/partest/scala/tools/partest/SecurityTest.scala b/src/partest/scala/tools/partest/SecurityTest.scala index 8d57e7e38d..2d6f61d0b1 100644 --- a/src/partest/scala/tools/partest/SecurityTest.scala +++ b/src/partest/scala/tools/partest/SecurityTest.scala @@ -11,8 +11,8 @@ import java.util._ abstract class SecurityTest extends App { def throwIt(x: Any) = throw new AccessControlException("" + x) - // def readPerm(p: PropertyPermission) = p.getActions contains "read" - // def writePerm(p: PropertyPermission) = p.getActions contains "write" + def readPerm(p: PropertyPermission) = p.getActions contains "read" + def writePerm(p: PropertyPermission) = p.getActions contains "write" def propertyCheck(p: PropertyPermission): Unit = throwIt(p) def check(perm: Permission): Unit = perm match { @@ -20,13 +20,13 @@ abstract class SecurityTest extends App { case _ => () } - // lazy val sm = new SecurityManager { - // // these two are the choke points for all permissions checks - // override def checkPermission(perm: Permission): Unit = check(perm) - // override def checkPermission(perm: Permission, context: Object): Unit = check(perm) - // } - // def securityOn(): Boolean = { - // try { System.setSecurityManager(sm) ; true } - // catch { case _: SecurityException => false } - // } + lazy val sm = new SecurityManager { + // these two are the choke points for all permissions checks + override def checkPermission(perm: Permission): Unit = check(perm) + override def checkPermission(perm: Permission, context: Object): Unit = check(perm) + } + def securityOn(): Boolean = { + try { System.setSecurityManager(sm) ; true } + catch { case _: SecurityException => false } + } } diff --git a/src/partest/scala/tools/partest/TestUtil.scala b/src/partest/scala/tools/partest/TestUtil.scala index bd5dc39498..9bfd444180 100644 --- a/src/partest/scala/tools/partest/TestUtil.scala +++ b/src/partest/scala/tools/partest/TestUtil.scala @@ -24,13 +24,13 @@ trait TestUtil { } def nanos(body: => Unit): Long = alsoNanos(body)._1 - // def verifySpeed(body1: => Unit, body2: => Unit, acceptableMultiple: Double) = { - // val t1 = nanos(body1).toDouble - // val t2 = nanos(body2).toDouble - // val mult = if (t1 > t2) t1 / t2 else t2 / t1 + def verifySpeed(body1: => Unit, body2: => Unit, acceptableMultiple: Double) = { + val t1 = nanos(body1).toDouble + val t2 = nanos(body2).toDouble + val mult = if (t1 > t2) t1 / t2 else t2 / t1 - // assert(mult <= acceptableMultiple, "Performance difference too great: multiple = " + mult) - // } + assert(mult <= acceptableMultiple, "Performance difference too great: multiple = " + mult) + } def intercept[T <: Exception : ClassTag](code: => Unit): Unit = try { @@ -41,6 +41,6 @@ trait TestUtil { } } -// Used in tests. object TestUtil extends TestUtil { + } diff --git a/src/partest/scala/tools/partest/instrumented/Instrumentation.scala b/src/partest/scala/tools/partest/instrumented/Instrumentation.scala index 18dd740208..8a284b313b 100644 --- a/src/partest/scala/tools/partest/instrumented/Instrumentation.scala +++ b/src/partest/scala/tools/partest/instrumented/Instrumentation.scala @@ -78,7 +78,6 @@ object Instrumentation { !t.className.startsWith("scala/util/DynamicVariable") } - // Used in tests. def printStatistics(stats: Statistics = getStatistics, filter: MethodCallTrace => Boolean = standardFilter): Unit = { val stats = getStatistics println("Method call statistics:") diff --git a/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala b/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala index d8ae4b2403..75aed449a8 100644 --- a/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala +++ b/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala @@ -79,7 +79,7 @@ class ConsoleFileManager extends FileManager { testClassesDir = Path(testClasses.get).toCanonical.toDirectory NestUI.verbose("Running with classes in "+testClassesDir) - // latestFile = testClassesDir.parent / "bin" + latestFile = testClassesDir.parent / "bin" latestLibFile = testClassesDir / "library" latestActorsFile = testClassesDir / "library" / "actors" latestReflectFile = testClassesDir / "reflect" @@ -90,7 +90,7 @@ class ConsoleFileManager extends FileManager { else if (testBuild.isDefined) { val dir = Path(testBuild.get) NestUI.verbose("Running on "+dir) - // latestFile = dir / "bin" + latestFile = dir / "bin" latestLibFile = dir / "lib/scala-library.jar" latestActorsFile = dir / "lib/scala-actors.jar" latestReflectFile = dir / "lib/scala-reflect.jar" @@ -101,7 +101,7 @@ class ConsoleFileManager extends FileManager { else { def setupQuick() { NestUI.verbose("Running build/quick") - // latestFile = prefixFile("build/quick/bin") + latestFile = prefixFile("build/quick/bin") latestLibFile = prefixFile("build/quick/classes/library") latestActorsFile = prefixFile("build/quick/classes/library/actors") latestReflectFile = prefixFile("build/quick/classes/reflect") @@ -112,7 +112,7 @@ class ConsoleFileManager extends FileManager { def setupInst() { NestUI.verbose("Running dist (installed)") val p = testParent.getParentFile - // latestFile = prefixFileWith(p, "bin") + latestFile = prefixFileWith(p, "bin") latestLibFile = prefixFileWith(p, "lib/scala-library.jar") latestActorsFile = prefixFileWith(p, "lib/scala-actors.jar") latestReflectFile = prefixFileWith(p, "lib/scala-reflect.jar") @@ -122,7 +122,7 @@ class ConsoleFileManager extends FileManager { def setupDist() { NestUI.verbose("Running dists/latest") - // latestFile = prefixFile("dists/latest/bin") + latestFile = prefixFile("dists/latest/bin") latestLibFile = prefixFile("dists/latest/lib/scala-library.jar") latestActorsFile = prefixFile("dists/latest/lib/scala-actors.jar") latestReflectFile = prefixFile("dists/latest/lib/scala-reflect.jar") @@ -132,7 +132,7 @@ class ConsoleFileManager extends FileManager { def setupPack() { NestUI.verbose("Running build/pack") - // latestFile = prefixFile("build/pack/bin") + latestFile = prefixFile("build/pack/bin") latestLibFile = prefixFile("build/pack/lib/scala-library.jar") latestActorsFile = prefixFile("build/pack/lib/scala-actors.jar") latestReflectFile = prefixFile("build/pack/lib/scala-reflect.jar") @@ -175,7 +175,7 @@ class ConsoleFileManager extends FileManager { var LATEST_PARTEST: String = "" var LATEST_ACTORS: String = "" - // var latestFile: File = _ + var latestFile: File = _ var latestLibFile: File = _ var latestActorsFile: File = _ var latestReflectFile: File = _ @@ -187,7 +187,7 @@ class ConsoleFileManager extends FileManager { // initialize above fields findLatest() - // var testFiles: List[io.Path] = Nil + var testFiles: List[io.Path] = Nil def getFiles(kind: String, cond: Path => Boolean): List[File] = { def ignoreDir(p: Path) = List("svn", "obj") exists (p hasExtension _) @@ -197,7 +197,9 @@ class ConsoleFileManager extends FileManager { if (dir.isDirectory) NestUI.verbose("look in %s for tests" format dir) else NestUI.failure("Directory '%s' not found" format dir) - val files = dir.list filterNot ignoreDir filter cond toList + val files = + if (testFiles.nonEmpty) testFiles filter (_.parent isSame dir) + else dir.list filterNot ignoreDir filter cond toList ( if (failed) files filter (x => logFileExists(x, kind)) else files ) map (_.jfile) } diff --git a/src/partest/scala/tools/partest/nest/ConsoleRunner.scala b/src/partest/scala/tools/partest/nest/ConsoleRunner.scala index 35bce01684..d23ee81e4d 100644 --- a/src/partest/scala/tools/partest/nest/ConsoleRunner.scala +++ b/src/partest/scala/tools/partest/nest/ConsoleRunner.scala @@ -51,7 +51,7 @@ class ConsoleRunner extends DirectRunner { private val testSetArgs = testSets map ("--" + _.kind) private val testSetArgMap = testSetArgs zip testSets toMap - // def denotesTestSet(arg: String) = testSetArgs contains arg + def denotesTestSet(arg: String) = testSetArgs contains arg private def printVersion() { NestUI outline (versionMsg + "\n") } diff --git a/src/partest/scala/tools/partest/nest/FileManager.scala b/src/partest/scala/tools/partest/nest/FileManager.scala index 9e2a34a34e..21fd314552 100644 --- a/src/partest/scala/tools/partest/nest/FileManager.scala +++ b/src/partest/scala/tools/partest/nest/FileManager.scala @@ -74,15 +74,15 @@ trait FileManager extends FileUtil { var timeout = PartestDefaults.timeout // how can 15 minutes not be enough? What are you doing, run/lisp.scala? // You complete in 11 seconds on my machine. - // var oneTestTimeout = 60 * 60 * 1000 + var oneTestTimeout = 60 * 60 * 1000 /** Only when --debug is given. */ lazy val testTimings = new mutable.HashMap[String, Long] def recordTestTiming(name: String, milliseconds: Long) = synchronized { testTimings(name) = milliseconds } - // def showTestTimings() { - // testTimings.toList sortBy (-_._2) foreach { case (k, v) => println("%s: %s".format(k, v)) } - // } + def showTestTimings() { + testTimings.toList sortBy (-_._2) foreach { case (k, v) => println("%s: %s".format(k, v)) } + } def getLogFile(dir: File, fileBase: String, kind: String): File = new File(dir, fileBase + "-" + kind + ".log") diff --git a/src/partest/scala/tools/partest/nest/NestUI.scala b/src/partest/scala/tools/partest/nest/NestUI.scala index 00aa27bd34..70db6d0ed1 100644 --- a/src/partest/scala/tools/partest/nest/NestUI.scala +++ b/src/partest/scala/tools/partest/nest/NestUI.scala @@ -54,9 +54,9 @@ object NestUI { } def warning(msg: String) = print(_warning + msg + _default) - // def warning(msg: String, wr: PrintWriter) = synchronized { - // wr.print(_warning + msg + _default) - // } + def warning(msg: String, wr: PrintWriter) = synchronized { + wr.print(_warning + msg + _default) + } def normal(msg: String) = print(_default + msg) def normal(msg: String, wr: PrintWriter) = synchronized { @@ -104,7 +104,7 @@ object NestUI { } var _verbose = false - // var _debug = false + var _debug = false def verbose(msg: String) { if (_verbose) { @@ -112,10 +112,10 @@ object NestUI { println(msg) } } - // def debug(msg: String) { - // if (isPartestDebug) { - // outline("debug: ") - // println(msg) - // } - // } + def debug(msg: String) { + if (isPartestDebug) { + outline("debug: ") + println(msg) + } + } } diff --git a/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala b/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala index 4b0ed1f82a..5cb8589d66 100644 --- a/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala +++ b/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala @@ -3,6 +3,8 @@ * @author Philipp Haller */ +// $Id$ + package scala.tools.partest package nest @@ -10,6 +12,7 @@ import scala.tools.nsc.Properties.{ setProp, propOrEmpty } import scala.tools.nsc.util.ClassPath import scala.tools.nsc.io import io.Path +import RunnerUtils._ import java.net.URLClassLoader /* This class is used to load an instance of DirectRunner using @@ -25,12 +28,6 @@ class ReflectiveRunner { // was used to start the runner. val sepRunnerClassName = "scala.tools.partest.nest.ConsoleRunner" - private def searchPath(option: String, as: List[String]): Option[String] = as match { - case `option` :: r :: _ => Some(r) - case _ :: rest => searchPath(option, rest) - case Nil => None - } - def main(args: String) { val argList = (args.split("\\s")).toList diff --git a/src/partest/scala/tools/partest/nest/RunnerManager.scala b/src/partest/scala/tools/partest/nest/RunnerManager.scala index 2651088018..548c5abbd9 100644 --- a/src/partest/scala/tools/partest/nest/RunnerManager.scala +++ b/src/partest/scala/tools/partest/nest/RunnerManager.scala @@ -291,10 +291,10 @@ class RunnerManager(kind: String, val fileManager: FileManager, params: TestRunP ((swr, wr)) } - // def fail(what: Any) = { - // NestUI.verbose("scalac: compilation of "+what+" failed\n") - // false - // } + def fail(what: Any) = { + NestUI.verbose("scalac: compilation of "+what+" failed\n") + false + } def diffCheck(testFile: File, diff: String) = { testDiff = diff testDiff == "" diff --git a/src/partest/scala/tools/partest/nest/RunnerUtils.scala b/src/partest/scala/tools/partest/nest/RunnerUtils.scala index 8a47989b7c..6707a9338a 100644 --- a/src/partest/scala/tools/partest/nest/RunnerUtils.scala +++ b/src/partest/scala/tools/partest/nest/RunnerUtils.scala @@ -1,29 +1,29 @@ -// /* NEST (New Scala Test) -// * Copyright 2007-2013 LAMP/EPFL -// * @author Philipp Haller -// */ +/* NEST (New Scala Test) + * Copyright 2007-2013 LAMP/EPFL + * @author Philipp Haller + */ -// // $Id$ +// $Id$ -// package scala.tools.partest -// package nest +package scala.tools.partest +package nest -// object RunnerUtils { -// def splitArgs(str: String) = str split "\\s" filterNot (_ == "") toList +object RunnerUtils { + def splitArgs(str: String) = str split "\\s" filterNot (_ == "") toList -// def searchPath(option: String, as: List[String]): Option[String] = as match { -// case `option` :: r :: _ => Some(r) -// case _ :: rest => searchPath(option, rest) -// case Nil => None -// } + def searchPath(option: String, as: List[String]): Option[String] = as match { + case `option` :: r :: _ => Some(r) + case _ :: rest => searchPath(option, rest) + case Nil => None + } -// def searchAndRemovePath(option: String, as: List[String]) = (as indexOf option) match { -// case -1 => (None, as) -// case idx => (Some(as(idx + 1)), (as take idx) ::: (as drop (idx + 2))) -// } + def searchAndRemovePath(option: String, as: List[String]) = (as indexOf option) match { + case -1 => (None, as) + case idx => (Some(as(idx + 1)), (as take idx) ::: (as drop (idx + 2))) + } -// def searchAndRemoveOption(option: String, as: List[String]) = (as indexOf option) match { -// case -1 => (false, as) -// case idx => (true, (as take idx) ::: (as drop (idx + 1))) -// } -// } + def searchAndRemoveOption(option: String, as: List[String]) = (as indexOf option) match { + case -1 => (false, as) + case idx => (true, (as take idx) ::: (as drop (idx + 1))) + } +} diff --git a/src/partest/scala/tools/partest/package.scala b/src/partest/scala/tools/partest/package.scala index fa0c88a2b2..58cc7d5b0b 100644 --- a/src/partest/scala/tools/partest/package.scala +++ b/src/partest/scala/tools/partest/package.scala @@ -13,9 +13,9 @@ import java.util.concurrent.Callable package partest { class TestState { - // def isOk = this eq TestState.Ok - // def isFail = this eq TestState.Fail - // def isTimeout = this eq TestState.Timeout + def isOk = this eq TestState.Ok + def isFail = this eq TestState.Fail + def isTimeout = this eq TestState.Timeout } object TestState { val Ok = new TestState @@ -43,7 +43,7 @@ package object partest { def callable[T](body: => T): Callable[T] = new Callable[T] { override def call() = body } - // def path2String(path: String) = file2String(new JFile(path)) + def path2String(path: String) = file2String(new JFile(path)) def file2String(f: JFile) = try SFile(f).slurp(scala.io.Codec.UTF8) catch { case _: FileNotFoundException => "" } diff --git a/src/partest/scala/tools/partest/utils/PrintMgr.scala b/src/partest/scala/tools/partest/utils/PrintMgr.scala index 56fdcda2ea..d25be87c1e 100644 --- a/src/partest/scala/tools/partest/utils/PrintMgr.scala +++ b/src/partest/scala/tools/partest/utils/PrintMgr.scala @@ -1,52 +1,52 @@ -// /* __ *\ -// ** ________ ___ / / ___ Scala Parallel Testing ** -// ** / __/ __// _ | / / / _ | (c) 2007-2013, LAMP/EPFL ** -// ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -// ** /____/\___/_/ |_/____/_/ | | ** -// ** |/ ** -// \* */ - -// // $Id$ - -// package scala.tools.partest -// package utils - -// /** -// * @author Thomas Hofer -// */ -// object PrintMgr { - -// val NONE = 0 -// val SOME = 1 -// val MANY = 2 - -// var outline = "" -// var success = "" -// var failure = "" -// var warning = "" -// var default = "" - -// def initialization(number: Int) = number match { -// case MANY => -// outline = Console.BOLD + Console.BLACK -// success = Console.BOLD + Console.GREEN -// failure = Console.BOLD + Console.RED -// warning = Console.BOLD + Console.YELLOW -// default = Console.RESET -// case SOME => -// outline = Console.BOLD + Console.BLACK -// success = Console.RESET -// failure = Console.BOLD + Console.BLACK -// warning = Console.BOLD + Console.BLACK -// default = Console.RESET -// case _ => -// } - -// def printOutline(msg: String) = print(outline + msg + default) - -// def printSuccess(msg: String) = print(success + msg + default) - -// def printFailure(msg: String) = print(failure + msg + default) - -// def printWarning(msg: String) = print(warning + msg + default) -// } +/* __ *\ +** ________ ___ / / ___ Scala Parallel Testing ** +** / __/ __// _ | / / / _ | (c) 2007-2013, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +// $Id$ + +package scala.tools.partest +package utils + +/** + * @author Thomas Hofer + */ +object PrintMgr { + + val NONE = 0 + val SOME = 1 + val MANY = 2 + + var outline = "" + var success = "" + var failure = "" + var warning = "" + var default = "" + + def initialization(number: Int) = number match { + case MANY => + outline = Console.BOLD + Console.BLACK + success = Console.BOLD + Console.GREEN + failure = Console.BOLD + Console.RED + warning = Console.BOLD + Console.YELLOW + default = Console.RESET + case SOME => + outline = Console.BOLD + Console.BLACK + success = Console.RESET + failure = Console.BOLD + Console.BLACK + warning = Console.BOLD + Console.BLACK + default = Console.RESET + case _ => + } + + def printOutline(msg: String) = print(outline + msg + default) + + def printSuccess(msg: String) = print(success + msg + default) + + def printFailure(msg: String) = print(failure + msg + default) + + def printWarning(msg: String) = print(warning + msg + default) +} diff --git a/src/reflect/scala/reflect/internal/AnnotationInfos.scala b/src/reflect/scala/reflect/internal/AnnotationInfos.scala index 82be2fa04a..7c12b5979d 100644 --- a/src/reflect/scala/reflect/internal/AnnotationInfos.scala +++ b/src/reflect/scala/reflect/internal/AnnotationInfos.scala @@ -6,6 +6,7 @@ package scala.reflect package internal +import util._ import pickling.ByteCodecs import scala.annotation.tailrec import scala.collection.immutable.ListMap @@ -288,8 +289,8 @@ trait AnnotationInfos extends api.Annotations { self: SymbolTable => def refsSymbol(sym: Symbol) = hasArgWhich(_.symbol == sym) /** Change all ident's with Symbol "from" to instead use symbol "to" */ - // def substIdentSyms(from: Symbol, to: Symbol) = - // AnnotationInfo(atp, args map (_ substituteSymbols (List(from), List(to))), assocs) setPos pos + def substIdentSyms(from: Symbol, to: Symbol) = + AnnotationInfo(atp, args map (_ substituteSymbols (List(from), List(to))), assocs) setPos pos def stringArg(index: Int) = constantAtIndex(index) map (_.stringValue) def intArg(index: Int) = constantAtIndex(index) map (_.intValue) @@ -324,14 +325,14 @@ trait AnnotationInfos extends api.Annotations { self: SymbolTable => implicit val AnnotationTag = ClassTag[AnnotationInfo](classOf[AnnotationInfo]) object UnmappableAnnotation extends CompleteAnnotationInfo(NoType, Nil, Nil) - + /** Extracts symbol of thrown exception from AnnotationInfo. - * + * * Supports both “old-style” `@throws(classOf[Exception])` * as well as “new-stye” `@throws[Exception]("cause")` annotations. */ object ThrownException { - def unapply(ann: AnnotationInfo): Option[Symbol] = + def unapply(ann: AnnotationInfo): Option[Symbol] = ann match { case AnnotationInfo(tpe, _, _) if tpe.typeSymbol != ThrowsClass => None diff --git a/src/reflect/scala/reflect/internal/BuildUtils.scala b/src/reflect/scala/reflect/internal/BuildUtils.scala index 9da6ad652a..9f41f0336e 100644 --- a/src/reflect/scala/reflect/internal/BuildUtils.scala +++ b/src/reflect/scala/reflect/internal/BuildUtils.scala @@ -1,6 +1,8 @@ package scala.reflect package internal +import Flags._ + trait BuildUtils { self: SymbolTable => class BuildImpl extends BuildApi { diff --git a/src/reflect/scala/reflect/internal/ClassfileConstants.scala b/src/reflect/scala/reflect/internal/ClassfileConstants.scala index c8af1732a9..b1462e9709 100644 --- a/src/reflect/scala/reflect/internal/ClassfileConstants.scala +++ b/src/reflect/scala/reflect/internal/ClassfileConstants.scala @@ -381,10 +381,10 @@ object ClassfileConstants { def toScalaClassFlags(flags: Int): Long = FlagTranslation classFlags flags def toScalaFieldFlags(flags: Int): Long = FlagTranslation fieldFlags flags - // @deprecated("Use another method in this object", "2.10.0") - // def toScalaFlags(flags: Int, isClass: Boolean = false, isField: Boolean = false): Long = ( - // if (isClass) toScalaClassFlags(flags) - // else if (isField) toScalaFieldFlags(flags) - // else toScalaMethodFlags(flags) - // ) + @deprecated("Use another method in this object", "2.10.0") + def toScalaFlags(flags: Int, isClass: Boolean = false, isField: Boolean = false): Long = ( + if (isClass) toScalaClassFlags(flags) + else if (isField) toScalaFieldFlags(flags) + else toScalaMethodFlags(flags) + ) } diff --git a/src/reflect/scala/reflect/internal/Definitions.scala b/src/reflect/scala/reflect/internal/Definitions.scala index 8ecb189c27..1f751cde38 100644 --- a/src/reflect/scala/reflect/internal/Definitions.scala +++ b/src/reflect/scala/reflect/internal/Definitions.scala @@ -9,6 +9,7 @@ package internal import scala.annotation.{ switch, meta } import scala.collection.{ mutable, immutable } import Flags._ +import PartialFunction._ import scala.reflect.api.{Universe => ApiUniverse} trait Definitions extends api.StandardDefinitions { @@ -148,7 +149,7 @@ trait Definitions extends api.StandardDefinitions { FloatClass, DoubleClass ) - // def ScalaValueClassCompanions: List[Symbol] = ScalaValueClasses map (_.companionSymbol) + def ScalaValueClassCompanions: List[Symbol] = ScalaValueClasses map (_.companionSymbol) def ScalaPrimitiveValueClasses: List[ClassSymbol] = ScalaValueClasses } @@ -157,7 +158,7 @@ trait Definitions extends api.StandardDefinitions { def isDefinitionsInitialized = isInitialized // symbols related to packages - // var emptypackagescope: Scope = null //debug + var emptypackagescope: Scope = null //debug @deprecated("Moved to rootMirror.RootPackage", "2.10.0") val RootPackage: ModuleSymbol = rootMirror.RootPackage @@ -180,7 +181,7 @@ trait Definitions extends api.StandardDefinitions { lazy val RuntimePackage = getRequiredPackage("scala.runtime") lazy val RuntimePackageClass = RuntimePackage.moduleClass.asClass - // lazy val JavaLangEnumClass = requiredClass[java.lang.Enum[_]] + lazy val JavaLangEnumClass = requiredClass[java.lang.Enum[_]] // convenient one-argument parameter lists lazy val anyparam = List(AnyClass.tpe) @@ -261,7 +262,7 @@ trait Definitions extends api.StandardDefinitions { || tp =:= AnyRefClass.tpe ) /** Does this type have a parent which is none of Any, AnyVal, or AnyRef? */ - // def hasNonTrivialParent(tp: Type) = tp.parents exists (t => !isTrivialTopType(tp)) + def hasNonTrivialParent(tp: Type) = tp.parents exists (t => !isTrivialTopType(tp)) private def fixupAsAnyTrait(tpe: Type): Type = tpe match { case ClassInfoType(parents, decls, clazz) => @@ -357,7 +358,7 @@ trait Definitions extends api.StandardDefinitions { lazy val UnqualifiedOwners = UnqualifiedModules.toSet ++ UnqualifiedModules.map(_.moduleClass) lazy val PredefModule = requiredModule[scala.Predef.type] - // lazy val PredefModuleClass = PredefModule.moduleClass + lazy val PredefModuleClass = PredefModule.moduleClass def Predef_classOf = getMemberMethod(PredefModule, nme.classOf) // def Predef_identity = getMemberMethod(PredefModule, nme.identity) @@ -381,7 +382,7 @@ trait Definitions extends api.StandardDefinitions { lazy val SpecializableModule = requiredModule[Specializable] lazy val GroupOfSpecializable = getMemberClass(SpecializableModule, tpnme.Group) - // lazy val ConsoleModule = requiredModule[scala.Console.type] + lazy val ConsoleModule = requiredModule[scala.Console.type] lazy val ScalaRunTimeModule = requiredModule[scala.runtime.ScalaRunTime.type] lazy val SymbolModule = requiredModule[scala.Symbol.type] lazy val Symbol_apply = getMemberMethod(SymbolModule, nme.apply) @@ -391,9 +392,9 @@ trait Definitions extends api.StandardDefinitions { def arrayLengthMethod = getMemberMethod(ScalaRunTimeModule, nme.array_length) def arrayCloneMethod = getMemberMethod(ScalaRunTimeModule, nme.array_clone) def ensureAccessibleMethod = getMemberMethod(ScalaRunTimeModule, nme.ensureAccessible) - // def scalaRuntimeSameElements = getMemberMethod(ScalaRunTimeModule, nme.sameElements) + def scalaRuntimeSameElements = getMemberMethod(ScalaRunTimeModule, nme.sameElements) def arrayClassMethod = getMemberMethod(ScalaRunTimeModule, nme.arrayClass) - // def arrayElementClassMethod = getMemberMethod(ScalaRunTimeModule, nme.arrayElementClass) + def arrayElementClassMethod = getMemberMethod(ScalaRunTimeModule, nme.arrayElementClass) // classes with special meanings lazy val StringAddClass = requiredClass[scala.runtime.StringAdd] @@ -456,10 +457,10 @@ trait Definitions extends api.StandardDefinitions { case _ => tp } - // def isPrimitiveArray(tp: Type) = tp match { - // case TypeRef(_, ArrayClass, arg :: Nil) => isPrimitiveValueClass(arg.typeSymbol) - // case _ => false - // } + def isPrimitiveArray(tp: Type) = tp match { + case TypeRef(_, ArrayClass, arg :: Nil) => isPrimitiveValueClass(arg.typeSymbol) + case _ => false + } def isReferenceArray(tp: Type) = tp match { case TypeRef(_, ArrayClass, arg :: Nil) => arg <:< AnyRefClass.tpe case _ => false @@ -469,11 +470,11 @@ trait Definitions extends api.StandardDefinitions { case _ => false } - // lazy val MatchingStrategyClass = getRequiredClass("scala.MatchingStrategy") + lazy val MatchingStrategyClass = getRequiredClass("scala.MatchingStrategy") // collections classes lazy val ConsClass = requiredClass[scala.collection.immutable.::[_]] - // lazy val IterableClass = requiredClass[scala.collection.Iterable[_]] + lazy val IterableClass = requiredClass[scala.collection.Iterable[_]] lazy val IteratorClass = requiredClass[scala.collection.Iterator[_]] lazy val ListClass = requiredClass[scala.collection.immutable.List[_]] lazy val SeqClass = requiredClass[scala.collection.Seq[_]] @@ -484,8 +485,8 @@ trait Definitions extends api.StandardDefinitions { lazy val List_apply = getMemberMethod(ListModule, nme.apply) lazy val NilModule = requiredModule[scala.collection.immutable.Nil.type] lazy val SeqModule = requiredModule[scala.collection.Seq.type] - // lazy val IteratorModule = requiredModule[scala.collection.Iterator.type] - // lazy val Iterator_apply = getMemberMethod(IteratorModule, nme.apply) + lazy val IteratorModule = requiredModule[scala.collection.Iterator.type] + lazy val Iterator_apply = getMemberMethod(IteratorModule, nme.apply) // arrays and their members lazy val ArrayModule = requiredModule[scala.Array.type] @@ -500,9 +501,9 @@ trait Definitions extends api.StandardDefinitions { // reflection / structural types lazy val SoftReferenceClass = requiredClass[java.lang.ref.SoftReference[_]] - // lazy val WeakReferenceClass = requiredClass[java.lang.ref.WeakReference[_]] + lazy val WeakReferenceClass = requiredClass[java.lang.ref.WeakReference[_]] lazy val MethodClass = getClassByName(sn.MethodAsObject) - // def methodClass_setAccessible = getMemberMethod(MethodClass, nme.setAccessible) + def methodClass_setAccessible = getMemberMethod(MethodClass, nme.setAccessible) lazy val EmptyMethodCacheClass = requiredClass[scala.runtime.EmptyMethodCache] lazy val MethodCacheClass = requiredClass[scala.runtime.MethodCache] def methodCache_find = getMemberMethod(MethodCacheClass, nme.find_) @@ -526,7 +527,7 @@ trait Definitions extends api.StandardDefinitions { lazy val ExprClass = if (ExprsClass != NoSymbol) getMemberClass(ExprsClass, tpnme.Expr) else NoSymbol def ExprSplice = if (ExprsClass != NoSymbol) getMemberMethod(ExprClass, nme.splice) else NoSymbol def ExprValue = if (ExprsClass != NoSymbol) getMemberMethod(ExprClass, nme.value) else NoSymbol - // lazy val ExprModule = if (ExprsClass != NoSymbol) getMemberModule(ExprsClass, nme.Expr) else NoSymbol + lazy val ExprModule = if (ExprsClass != NoSymbol) getMemberModule(ExprsClass, nme.Expr) else NoSymbol lazy val ClassTagModule = requiredModule[scala.reflect.ClassTag[_]] lazy val ClassTagClass = requiredClass[scala.reflect.ClassTag[_]] @@ -552,7 +553,7 @@ trait Definitions extends api.StandardDefinitions { def MacroContextPrefix = if (MacroContextClass != NoSymbol) getMemberMethod(MacroContextClass, nme.prefix) else NoSymbol def MacroContextPrefixType = if (MacroContextClass != NoSymbol) getTypeMember(MacroContextClass, tpnme.PrefixType) else NoSymbol def MacroContextUniverse = if (MacroContextClass != NoSymbol) getMemberMethod(MacroContextClass, nme.universe) else NoSymbol - // def MacroContextMirror = if (MacroContextClass != NoSymbol) getMemberMethod(MacroContextClass, nme.mirror) else NoSymbol + def MacroContextMirror = if (MacroContextClass != NoSymbol) getMemberMethod(MacroContextClass, nme.mirror) else NoSymbol lazy val MacroImplAnnotation = requiredClass[scala.reflect.macros.internal.macroImpl] lazy val StringContextClass = requiredClass[scala.StringContext] @@ -584,12 +585,12 @@ trait Definitions extends api.StandardDefinitions { // The given class has a main method. def hasJavaMainMethod(sym: Symbol): Boolean = (sym.tpe member nme.main).alternatives exists isJavaMainMethod - // def hasJavaMainMethod(path: String): Boolean = - // hasJavaMainMethod(getModuleIfDefined(path)) + def hasJavaMainMethod(path: String): Boolean = + hasJavaMainMethod(getModuleIfDefined(path)) - // def isOptionType(tp: Type) = tp.typeSymbol isSubClass OptionClass - // def isSomeType(tp: Type) = tp.typeSymbol eq SomeClass - // def isNoneType(tp: Type) = tp.typeSymbol eq NoneModule + def isOptionType(tp: Type) = tp.typeSymbol isSubClass OptionClass + def isSomeType(tp: Type) = tp.typeSymbol eq SomeClass + def isNoneType(tp: Type) = tp.typeSymbol eq NoneModule // Product, Tuple, Function, AbstractFunction private def mkArityArray(name: String, arity: Int, countFrom: Int): Array[ClassSymbol] = { @@ -612,7 +613,7 @@ trait Definitions extends api.StandardDefinitions { /** Creators for TupleN, ProductN, FunctionN. */ def tupleType(elems: List[Type]) = aritySpecificType(TupleClass, elems) - // def productType(elems: List[Type]) = aritySpecificType(ProductClass, elems) + def productType(elems: List[Type]) = aritySpecificType(ProductClass, elems) def functionType(formals: List[Type], restpe: Type) = aritySpecificType(FunctionClass, formals, restpe) def abstractFunctionType(formals: List[Type], restpe: Type) = aritySpecificType(AbstractFunctionClass, formals, restpe) @@ -631,10 +632,10 @@ trait Definitions extends api.StandardDefinitions { else nme.genericWrapArray } - // @deprecated("Use isTupleType", "2.10.0") - // def isTupleTypeOrSubtype(tp: Type) = isTupleType(tp) + @deprecated("Use isTupleType", "2.10.0") + def isTupleTypeOrSubtype(tp: Type) = isTupleType(tp) - // def tupleField(n: Int, j: Int) = getMemberValue(TupleClass(n), nme.productAccessorName(j)) + def tupleField(n: Int, j: Int) = getMemberValue(TupleClass(n), nme.productAccessorName(j)) // NOTE: returns true for NoSymbol since it's included in the TupleClass array -- is this intensional? def isTupleSymbol(sym: Symbol) = TupleClass contains unspecializedSymbol(sym) def isProductNClass(sym: Symbol) = ProductClass contains sym @@ -683,10 +684,10 @@ trait Definitions extends api.StandardDefinitions { // def Product_productElementName = getMemberMethod(ProductRootClass, nme.productElementName) def productProj(z:Symbol, j: Int): TermSymbol = getMemberValue(z, nme.productAccessorName(j)) - // def productProj(n: Int, j: Int): TermSymbol = productProj(ProductClass(n), j) + def productProj(n: Int, j: Int): TermSymbol = productProj(ProductClass(n), j) /** returns true if this type is exactly ProductN[T1,...,Tn], not some subclass */ - // def isExactProductType(tp: Type): Boolean = isProductNClass(tp.typeSymbol) + def isExactProductType(tp: Type): Boolean = isProductNClass(tp.typeSymbol) /** if tpe <: ProductN[T1,...,TN], returns List(T1,...,TN) else Nil */ def getProductArgs(tpe: Type): List[Type] = tpe.baseClasses find isProductNClass match { @@ -704,7 +705,7 @@ trait Definitions extends api.StandardDefinitions { case tp => tp } - // def functionApply(n: Int) = getMemberMethod(FunctionClass(n), nme.apply) + def functionApply(n: Int) = getMemberMethod(FunctionClass(n), nme.apply) def abstractFunctionForFunctionType(tp: Type) = if (isFunctionType(tp)) abstractFunctionType(tp.typeArgs.init, tp.typeArgs.last) @@ -723,7 +724,7 @@ trait Definitions extends api.StandardDefinitions { (sym eq PartialFunctionClass) || (sym eq AbstractPartialFunctionClass) } - // def isSeqType(tp: Type) = elementType(SeqClass, tp.normalize) != NoType + def isSeqType(tp: Type) = elementType(SeqClass, tp.normalize) != NoType def elementType(container: Symbol, tp: Type): Type = tp match { case TypeRef(_, `container`, arg :: Nil) => arg @@ -737,10 +738,10 @@ trait Definitions extends api.StandardDefinitions { def optionType(tp: Type) = appliedType(OptionClass, tp) def scalaRepeatedType(arg: Type) = appliedType(RepeatedParamClass, arg) def seqType(arg: Type) = appliedType(SeqClass, arg) - // def someType(tp: Type) = appliedType(SomeClass, tp) + def someType(tp: Type) = appliedType(SomeClass, tp) - // def StringArray = arrayType(StringClass.tpe) - // lazy val ObjectArray = arrayType(ObjectClass.tpe) + def StringArray = arrayType(StringClass.tpe) + lazy val ObjectArray = arrayType(ObjectClass.tpe) def ClassType(arg: Type) = if (phase.erasedTypes || forMSIL) ClassClass.tpe @@ -753,8 +754,8 @@ trait Definitions extends api.StandardDefinitions { // - .linkedClassOfClass: the ClassSymbol of the enumeration (class E) sym.owner.linkedClassOfClass.tpe - // def vmClassType(arg: Type): Type = ClassType(arg) - // def vmSignature(sym: Symbol, info: Type): String = signature(info) // !!! + def vmClassType(arg: Type): Type = ClassType(arg) + def vmSignature(sym: Symbol, info: Type): String = signature(info) // !!! /** Given a class symbol C with type parameters T1, T2, ... Tn * which have upper/lower bounds LB1/UB1, LB1/UB2, ..., LBn/UBn, @@ -767,14 +768,14 @@ trait Definitions extends api.StandardDefinitions { /** Given type U, creates a Type representing Class[_ <: U]. */ - // def boundedClassType(upperBound: Type) = - // appliedTypeAsUpperBounds(ClassClass.typeConstructor, List(upperBound)) + def boundedClassType(upperBound: Type) = + appliedTypeAsUpperBounds(ClassClass.typeConstructor, List(upperBound)) /** To avoid unchecked warnings on polymorphic classes, translate * a Foo[T] into a Foo[_] for use in the pattern matcher. */ - // @deprecated("Use classExistentialType", "2.10.0") - // def typeCaseType(clazz: Symbol): Type = classExistentialType(clazz) + @deprecated("Use classExistentialType", "2.10.0") + def typeCaseType(clazz: Symbol): Type = classExistentialType(clazz) // // .NET backend @@ -782,7 +783,7 @@ trait Definitions extends api.StandardDefinitions { lazy val ComparatorClass = getRequiredClass("scala.runtime.Comparator") // System.ValueType - // lazy val ValueTypeClass: ClassSymbol = getClassByName(sn.ValueType) + lazy val ValueTypeClass: ClassSymbol = getClassByName(sn.ValueType) // System.MulticastDelegate lazy val DelegateClass: ClassSymbol = getClassByName(sn.Delegate) var Delegate_scalaCallers: List[Symbol] = List() // Syncnote: No protection necessary yet as only for .NET where reflection is not supported. @@ -875,11 +876,11 @@ trait Definitions extends api.StandardDefinitions { x :: removeRedundantObjects(xs) } /** Order a list of types with non-trait classes before others. */ - // def classesFirst(tps: List[Type]): List[Type] = { - // val (classes, others) = tps partition (t => t.typeSymbol.isClass && !t.typeSymbol.isTrait) - // if (classes.isEmpty || others.isEmpty || (tps startsWith classes)) tps - // else classes ::: others - // } + def classesFirst(tps: List[Type]): List[Type] = { + val (classes, others) = tps partition (t => t.typeSymbol.isClass && !t.typeSymbol.isTrait) + if (classes.isEmpty || others.isEmpty || (tps startsWith classes)) tps + else classes ::: others + } /** The following transformations applied to a list of parents. * If any parent is a class/trait, all parents which normalize to * Object are discarded. Otherwise, all parents which normalize @@ -907,10 +908,10 @@ trait Definitions extends api.StandardDefinitions { def parentsString(parents: List[Type]) = normalizedParents(parents) mkString " with " - // def typeParamsString(tp: Type) = tp match { - // case PolyType(tparams, _) => tparams map (_.defString) mkString ("[", ",", "]") - // case _ => "" - // } + def typeParamsString(tp: Type) = tp match { + case PolyType(tparams, _) => tparams map (_.defString) mkString ("[", ",", "]") + case _ => "" + } def valueParamsString(tp: Type) = tp match { case MethodType(params, _) => params map (_.defString) mkString ("(", ",", ")") case _ => "" @@ -947,12 +948,12 @@ trait Definitions extends api.StandardDefinitions { lazy val BoxedNumberClass = getClassByName(sn.BoxedNumber) lazy val BoxedCharacterClass = getClassByName(sn.BoxedCharacter) lazy val BoxedBooleanClass = getClassByName(sn.BoxedBoolean) - // lazy val BoxedByteClass = requiredClass[java.lang.Byte] - // lazy val BoxedShortClass = requiredClass[java.lang.Short] - // lazy val BoxedIntClass = requiredClass[java.lang.Integer] - // lazy val BoxedLongClass = requiredClass[java.lang.Long] - // lazy val BoxedFloatClass = requiredClass[java.lang.Float] - // lazy val BoxedDoubleClass = requiredClass[java.lang.Double] + lazy val BoxedByteClass = requiredClass[java.lang.Byte] + lazy val BoxedShortClass = requiredClass[java.lang.Short] + lazy val BoxedIntClass = requiredClass[java.lang.Integer] + lazy val BoxedLongClass = requiredClass[java.lang.Long] + lazy val BoxedFloatClass = requiredClass[java.lang.Float] + lazy val BoxedDoubleClass = requiredClass[java.lang.Double] lazy val Boxes_isNumberOrBool = getDecl(BoxesRunTimeClass, nme.isBoxedNumberOrBoolean) lazy val Boxes_isNumber = getDecl(BoxesRunTimeClass, nme.isBoxedNumber) @@ -973,7 +974,7 @@ trait Definitions extends api.StandardDefinitions { lazy val ImplicitNotFoundClass = requiredClass[scala.annotation.implicitNotFound] lazy val MigrationAnnotationClass = requiredClass[scala.annotation.migration] lazy val ScalaStrictFPAttr = requiredClass[scala.annotation.strictfp] - // lazy val SerializableAttr = requiredClass[scala.annotation.serializable] // @serializable is deprecated + lazy val SerializableAttr = requiredClass[scala.annotation.serializable] // @serializable is deprecated lazy val SwitchClass = requiredClass[scala.annotation.switch] lazy val TailrecClass = requiredClass[scala.annotation.tailrec] lazy val VarargsClass = requiredClass[scala.annotation.varargs] @@ -1008,7 +1009,7 @@ trait Definitions extends api.StandardDefinitions { lazy val ParamTargetClass = requiredClass[meta.param] lazy val SetterTargetClass = requiredClass[meta.setter] lazy val ClassTargetClass = requiredClass[meta.companionClass] - // lazy val ObjectTargetClass = requiredClass[meta.companionObject] + lazy val ObjectTargetClass = requiredClass[meta.companionObject] lazy val MethodTargetClass = requiredClass[meta.companionMethod] // TODO: module, moduleClass? package, packageObject? lazy val LanguageFeatureAnnot = requiredClass[meta.languageFeature] @@ -1053,7 +1054,7 @@ trait Definitions extends api.StandardDefinitions { def getLanguageFeature(name: String, owner: Symbol = languageFeatureModule): Symbol = getMember(owner, newTypeName(name)) def termMember(owner: Symbol, name: String): Symbol = owner.info.member(newTermName(name)) - // def typeMember(owner: Symbol, name: String): Symbol = owner.info.member(newTypeName(name)) + def typeMember(owner: Symbol, name: String): Symbol = owner.info.member(newTypeName(name)) def findNamedMember(fullName: Name, root: Symbol): Symbol = { val segs = nme.segments(fullName.toString, fullName.isTermName) @@ -1120,8 +1121,8 @@ trait Definitions extends api.StandardDefinitions { def getDeclIfDefined(owner: Symbol, name: Name): Symbol = owner.info.nonPrivateDecl(name) - // def packageExists(packageName: String): Boolean = - // getModuleIfDefined(packageName).isPackage + def packageExists(packageName: String): Boolean = + getModuleIfDefined(packageName).isPackage private def newAlias(owner: Symbol, name: TypeName, alias: Type): AliasTypeSymbol = owner.newAliasType(name) setInfoAndEnter alias @@ -1154,7 +1155,7 @@ trait Definitions extends api.StandardDefinitions { newPolyMethod(1, owner, name, flags)(tparams => (Some(Nil), createFn(tparams.head))) } - // lazy val boxedClassValues = boxedClass.values.toSet[Symbol] + lazy val boxedClassValues = boxedClass.values.toSet[Symbol] lazy val isUnbox = unboxMethod.values.toSet[Symbol] lazy val isBox = boxMethod.values.toSet[Symbol] @@ -1214,8 +1215,8 @@ trait Definitions extends api.StandardDefinitions { /** Is symbol a value class? */ def isPrimitiveValueClass(sym: Symbol) = ScalaValueClasses contains sym - // def isNonUnitValueClass(sym: Symbol) = isPrimitiveValueClass(sym) && (sym != UnitClass) - // def isSpecializableClass(sym: Symbol) = isPrimitiveValueClass(sym) || (sym == AnyRefClass) + def isNonUnitValueClass(sym: Symbol) = isPrimitiveValueClass(sym) && (sym != UnitClass) + def isSpecializableClass(sym: Symbol) = isPrimitiveValueClass(sym) || (sym == AnyRefClass) def isPrimitiveValueType(tp: Type) = isPrimitiveValueClass(tp.typeSymbol) /** Is symbol a boxed value class, e.g. java.lang.Integer? */ diff --git a/src/reflect/scala/reflect/internal/ExistentialsAndSkolems.scala b/src/reflect/scala/reflect/internal/ExistentialsAndSkolems.scala index 2a0fe9d19a..59c027868e 100644 --- a/src/reflect/scala/reflect/internal/ExistentialsAndSkolems.scala +++ b/src/reflect/scala/reflect/internal/ExistentialsAndSkolems.scala @@ -7,6 +7,7 @@ package scala.reflect package internal import scala.collection.{ mutable, immutable } +import util._ /** The name of this trait defines the eventual intent better than * it does the initial contents. diff --git a/src/reflect/scala/reflect/internal/Importers.scala b/src/reflect/scala/reflect/internal/Importers.scala index 592523c639..ea8d6078ff 100644 --- a/src/reflect/scala/reflect/internal/Importers.scala +++ b/src/reflect/scala/reflect/internal/Importers.scala @@ -316,7 +316,7 @@ trait Importers extends api.Importers { self: SymbolTable => def importName(name: from.Name): Name = if (name.isTypeName) newTypeName(name.toString) else newTermName(name.toString) def importTypeName(name: from.TypeName): TypeName = importName(name).toTypeName - // def importTermName(name: from.TermName): TermName = importName(name).toTermName + def importTermName(name: from.TermName): TermName = importName(name).toTermName def importModifiers(mods: from.Modifiers): Modifiers = new Modifiers(mods.flags, importName(mods.privateWithin), mods.annotations map importTree) diff --git a/src/reflect/scala/reflect/internal/Names.scala b/src/reflect/scala/reflect/internal/Names.scala index 7d98823c7e..9193674f3e 100644 --- a/src/reflect/scala/reflect/internal/Names.scala +++ b/src/reflect/scala/reflect/internal/Names.scala @@ -135,8 +135,8 @@ trait Names extends api.Names with LowPriorityNames { def newTypeName(bs: Array[Byte], offset: Int, len: Int): TypeName = newTermName(bs, offset, len).toTypeName - // def nameChars: Array[Char] = chrs - // @deprecated("", "2.9.0") def view(s: String): TermName = newTermName(s) + def nameChars: Array[Char] = chrs + @deprecated("", "2.9.0") def view(s: String): TermName = newTermName(s) // Classes ---------------------------------------------------------------------- @@ -186,22 +186,22 @@ trait Names extends api.Names with LowPriorityNames { scala.compat.Platform.arraycopy(chrs, index, cs, offset, len) /** @return the ascii representation of this name */ - // final def toChars: Array[Char] = { - // val cs = new Array[Char](len) - // copyChars(cs, 0) - // cs - // } + final def toChars: Array[Char] = { + val cs = new Array[Char](len) + copyChars(cs, 0) + cs + } /** Write to UTF8 representation of this name to given character array. * Start copying to index `to`. Return index of next free byte in array. * Array must have enough remaining space for all bytes * (i.e. maximally 3*length bytes). */ - // final def copyUTF8(bs: Array[Byte], offset: Int): Int = { - // val bytes = Codec.toUTF8(chrs, index, len) - // scala.compat.Platform.arraycopy(bytes, 0, bs, offset, bytes.length) - // offset + bytes.length - // } + final def copyUTF8(bs: Array[Byte], offset: Int): Int = { + val bytes = Codec.toUTF8(chrs, index, len) + scala.compat.Platform.arraycopy(bytes, 0, bs, offset, bytes.length) + offset + bytes.length + } /** @return the hash value of this name */ final override def hashCode(): Int = index @@ -283,7 +283,7 @@ trait Names extends api.Names with LowPriorityNames { */ final def lastPos(c: Char): Int = lastPos(c, len - 1) - // final def lastPos(s: String): Int = lastPos(s, len - s.length) + final def lastPos(s: String): Int = lastPos(s, len - s.length) /** Returns the index of the last occurrence of char c in this * name from start, -1 if not found. @@ -305,18 +305,18 @@ trait Names extends api.Names with LowPriorityNames { * @param start ... * @return the index of the last occurrence of s */ - // final def lastPos(s: String, start: Int): Int = { - // var i = lastPos(s.charAt(0), start) - // while (i >= 0) { - // var j = 1; - // while (s.charAt(j) == chrs(index + i + j)) { - // j += 1 - // if (j == s.length()) return i; - // } - // i = lastPos(s.charAt(0), i - 1) - // } - // -s.length() - // } + final def lastPos(s: String, start: Int): Int = { + var i = lastPos(s.charAt(0), start) + while (i >= 0) { + var j = 1; + while (s.charAt(j) == chrs(index + i + j)) { + j += 1 + if (j == s.length()) return i; + } + i = lastPos(s.charAt(0), i - 1) + } + -s.length() + } /** Does this name start with prefix? */ final def startsWith(prefix: Name): Boolean = startsWith(prefix, 0) @@ -379,7 +379,7 @@ trait Names extends api.Names with LowPriorityNames { if (idx == length) -1 else idx } def lastIndexOf(ch: Char) = lastPos(ch) - // def lastIndexOf(ch: Char, fromIndex: Int) = lastPos(ch, fromIndex) + def lastIndexOf(ch: Char, fromIndex: Int) = lastPos(ch, fromIndex) /** Replace all occurrences of `from` by `to` in * name; result is always a term name. @@ -428,12 +428,12 @@ trait Names extends api.Names with LowPriorityNames { def append(ch: Char) = newName("" + this + ch) def append(suffix: String) = newName("" + this + suffix) def append(suffix: Name) = newName("" + this + suffix) - // def prepend(ch: Char) = newName("" + ch + this) + def prepend(ch: Char) = newName("" + ch + this) def prepend(prefix: String) = newName("" + prefix + this) - // def prepend(prefix: Name) = newName("" + prefix + this) + def prepend(prefix: Name) = newName("" + prefix + this) def decodedName: ThisNameType = newName(decode) - // def isOperatorName: Boolean = decode != toString + def isOperatorName: Boolean = decode != toString def longString: String = nameKind + " " + decode def debugString = { val s = decode ; if (isTypeName) s + "!" else s } } @@ -445,7 +445,7 @@ trait Names extends api.Names with LowPriorityNames { def stripSuffix(suffix: Name): T = if (name endsWith suffix) dropRight(suffix.length) else name def dropRight(n: Int): T = name.subName(0, name.length - n).asInstanceOf[T] def drop(n: Int): T = name.subName(n, name.length).asInstanceOf[T] - // def nonEmpty: Boolean = name.length > 0 + def nonEmpty: Boolean = name.length > 0 } implicit val NameTag = ClassTag[Name](classOf[Name]) @@ -489,7 +489,7 @@ trait Names extends api.Names with LowPriorityNames { type ThisNameType = TermName protected[this] def thisName: TermName = this - val next: TermName = termHashtable(hash) + var next: TermName = termHashtable(hash) termHashtable(hash) = this def isTermName: Boolean = true def isTypeName: Boolean = false @@ -518,7 +518,7 @@ trait Names extends api.Names with LowPriorityNames { type ThisNameType = TypeName protected[this] def thisName: TypeName = this - val next: TypeName = typeHashtable(hash) + var next: TypeName = typeHashtable(hash) typeHashtable(hash) = this def isTermName: Boolean = false def isTypeName: Boolean = true diff --git a/src/reflect/scala/reflect/internal/Printers.scala b/src/reflect/scala/reflect/internal/Printers.scala index 58e3aff46f..31f9cb7e59 100644 --- a/src/reflect/scala/reflect/internal/Printers.scala +++ b/src/reflect/scala/reflect/internal/Printers.scala @@ -475,8 +475,8 @@ trait Printers extends api.Printers { self: SymbolTable => } def newRawTreePrinter(writer: PrintWriter): RawTreePrinter = new RawTreePrinter(writer) - // def newRawTreePrinter(stream: OutputStream): RawTreePrinter = newRawTreePrinter(new PrintWriter(stream)) - // def newRawTreePrinter(): RawTreePrinter = newRawTreePrinter(new PrintWriter(ConsoleWriter)) + def newRawTreePrinter(stream: OutputStream): RawTreePrinter = newRawTreePrinter(new PrintWriter(stream)) + def newRawTreePrinter(): RawTreePrinter = newRawTreePrinter(new PrintWriter(ConsoleWriter)) // provides footnotes for types and mirrors import scala.collection.mutable.{Map, WeakHashMap, SortedSet} diff --git a/src/reflect/scala/reflect/internal/Scopes.scala b/src/reflect/scala/reflect/internal/Scopes.scala index 31907772cb..950e30dbc5 100644 --- a/src/reflect/scala/reflect/internal/Scopes.scala +++ b/src/reflect/scala/reflect/internal/Scopes.scala @@ -343,7 +343,7 @@ trait Scopes extends api.Scopes { self: SymbolTable => */ def iterator: Iterator[Symbol] = toList.iterator - // def containsSymbol(s: Symbol) = lookupAll(s.name) contains s + def containsSymbol(s: Symbol) = lookupAll(s.name) contains s override def foreach[U](p: Symbol => U): Unit = toList foreach p diff --git a/src/reflect/scala/reflect/internal/StdNames.scala b/src/reflect/scala/reflect/internal/StdNames.scala index 7947a1a1e1..5e7f5777b2 100644 --- a/src/reflect/scala/reflect/internal/StdNames.scala +++ b/src/reflect/scala/reflect/internal/StdNames.scala @@ -104,7 +104,7 @@ trait StdNames { val IMPORT: NameType = "" val MODULE_SUFFIX_NAME: NameType = MODULE_SUFFIX_STRING val MODULE_VAR_SUFFIX: NameType = "$module" - // val NAME_JOIN_NAME: NameType = NAME_JOIN_STRING + val NAME_JOIN_NAME: NameType = NAME_JOIN_STRING val PACKAGE: NameType = "package" val ROOT: NameType = "" val SPECIALIZED_SUFFIX: NameType = "$sp" @@ -121,8 +121,8 @@ trait StdNames { final val Short: NameType = "Short" final val Unit: NameType = "Unit" - // final val ScalaValueNames: scala.List[NameType] = - // scala.List(Byte, Char, Short, Int, Long, Float, Double, Boolean, Unit) + final val ScalaValueNames: scala.List[NameType] = + scala.List(Byte, Char, Short, Int, Long, Float, Double, Boolean, Unit) // some types whose companions we utilize final val AnyRef: NameType = "AnyRef" @@ -130,7 +130,7 @@ trait StdNames { final val List: NameType = "List" final val Seq: NameType = "Seq" final val Symbol: NameType = "Symbol" - // final val ClassTag: NameType = "ClassTag" + final val ClassTag: NameType = "ClassTag" final val WeakTypeTag: NameType = "WeakTypeTag" final val TypeTag : NameType = "TypeTag" final val Expr: NameType = "Expr" @@ -220,12 +220,12 @@ trait StdNames { final val Any: NameType = "Any" final val AnyVal: NameType = "AnyVal" - // final val ExprApi: NameType = "ExprApi" + final val ExprApi: NameType = "ExprApi" final val Mirror: NameType = "Mirror" final val Nothing: NameType = "Nothing" final val Null: NameType = "Null" final val Object: NameType = "Object" - // final val PartialFunction: NameType = "PartialFunction" + final val PartialFunction: NameType = "PartialFunction" final val PrefixType: NameType = "PrefixType" final val Product: NameType = "Product" final val Serializable: NameType = "Serializable" @@ -239,7 +239,7 @@ trait StdNames { final val Group: NameType = "Group" final val Tree: NameType = "Tree" final val Type : NameType = "Type" - // final val TypeTree: NameType = "TypeTree" + final val TypeTree: NameType = "TypeTree" // Annotation simple names, used in Namer final val BeanPropertyAnnot: NameType = "BeanProperty" @@ -249,13 +249,13 @@ trait StdNames { // Classfile Attributes final val AnnotationDefaultATTR: NameType = "AnnotationDefault" final val BridgeATTR: NameType = "Bridge" - // final val ClassfileAnnotationATTR: NameType = "RuntimeInvisibleAnnotations" // RetentionPolicy.CLASS. Currently not used (Apr 2009). + final val ClassfileAnnotationATTR: NameType = "RuntimeInvisibleAnnotations" // RetentionPolicy.CLASS. Currently not used (Apr 2009). final val CodeATTR: NameType = "Code" final val ConstantValueATTR: NameType = "ConstantValue" final val DeprecatedATTR: NameType = "Deprecated" final val ExceptionsATTR: NameType = "Exceptions" final val InnerClassesATTR: NameType = "InnerClasses" - // final val LineNumberTableATTR: NameType = "LineNumberTable" + final val LineNumberTableATTR: NameType = "LineNumberTable" final val LocalVariableTableATTR: NameType = "LocalVariableTable" final val RuntimeAnnotationATTR: NameType = "RuntimeVisibleAnnotations" // RetentionPolicy.RUNTIME final val RuntimeParamAnnotationATTR: NameType = "RuntimeVisibleParameterAnnotations" // RetentionPolicy.RUNTIME (annotations on parameters) @@ -284,9 +284,9 @@ trait StdNames { val EXCEPTION_RESULT_PREFIX = "exceptionResult" val EXPAND_SEPARATOR_STRING = "$$" val INTERPRETER_IMPORT_WRAPPER = "$iw" - // val INTERPRETER_LINE_PREFIX = "line" - // val INTERPRETER_VAR_PREFIX = "res" - // val INTERPRETER_WRAPPER_SUFFIX = "$object" + val INTERPRETER_LINE_PREFIX = "line" + val INTERPRETER_VAR_PREFIX = "res" + val INTERPRETER_WRAPPER_SUFFIX = "$object" val LOCALDUMMY_PREFIX = " true - // case _ => false - // } + def isDeprecatedIdentifierName(name: Name) = name.toTermName match { + case nme.`then` | nme.`macro` => true + case _ => false + } def isOpAssignmentName(name: Name) = name match { case raw.NE | raw.LE | raw.GE | EMPTY => false @@ -461,14 +461,14 @@ trait StdNames { // If the name ends with $nn where nn are // all digits, strip the $ and the digits. // Otherwise return the argument. - // def stripAnonNumberSuffix(name: Name): Name = { - // var pos = name.length - // while (pos > 0 && name.charAt(pos - 1).isDigit) - // pos -= 1 + def stripAnonNumberSuffix(name: Name): Name = { + var pos = name.length + while (pos > 0 && name.charAt(pos - 1).isDigit) + pos -= 1 - // if (pos <= 0 || pos == name.length || name.charAt(pos - 1) != '$') name - // else name.subName(0, pos - 1) - // } + if (pos <= 0 || pos == name.length || name.charAt(pos - 1) != '$') name + else name.subName(0, pos - 1) + } def stripModuleSuffix(name: Name): Name = ( if (isModuleName(name)) name dropRight MODULE_SUFFIX_STRING.length else name @@ -484,8 +484,8 @@ trait StdNames { final val Nil: NameType = "Nil" final val Predef: NameType = "Predef" - // final val ScalaRunTime: NameType = "ScalaRunTime" - // final val Some: NameType = "Some" + final val ScalaRunTime: NameType = "ScalaRunTime" + final val Some: NameType = "Some" val _1 : NameType = "_1" val _2 : NameType = "_2" @@ -581,14 +581,14 @@ trait StdNames { val Annotation: NameType = "Annotation" val Any: NameType = "Any" val AnyVal: NameType = "AnyVal" - // val AppliedTypeTree: NameType = "AppliedTypeTree" - // val Apply: NameType = "Apply" + val AppliedTypeTree: NameType = "AppliedTypeTree" + val Apply: NameType = "Apply" val ArrayAnnotArg: NameType = "ArrayAnnotArg" - // val Constant: NameType = "Constant" + val Constant: NameType = "Constant" val ConstantType: NameType = "ConstantType" val EmptyPackage: NameType = "EmptyPackage" val EmptyPackageClass: NameType = "EmptyPackageClass" - // val ExistentialTypeTree: NameType = "ExistentialTypeTree" + val ExistentialTypeTree: NameType = "ExistentialTypeTree" val Flag : NameType = "Flag" val Ident: NameType = "Ident" val Import: NameType = "Import" @@ -597,10 +597,10 @@ trait StdNames { val Modifiers: NameType = "Modifiers" val NestedAnnotArg: NameType = "NestedAnnotArg" val NoFlags: NameType = "NoFlags" - // val NoPrefix: NameType = "NoPrefix" + val NoPrefix: NameType = "NoPrefix" val NoSymbol: NameType = "NoSymbol" val Nothing: NameType = "Nothing" - // val NoType: NameType = "NoType" + val NoType: NameType = "NoType" val Null: NameType = "Null" val Object: NameType = "Object" val RootPackage: NameType = "RootPackage" @@ -609,17 +609,17 @@ trait StdNames { val StringContext: NameType = "StringContext" val This: NameType = "This" val ThisType: NameType = "ThisType" - // val Tree : NameType = "Tree" + val Tree : NameType = "Tree" val Tuple2: NameType = "Tuple2" val TYPE_ : NameType = "TYPE" - // val TypeApply: NameType = "TypeApply" + val TypeApply: NameType = "TypeApply" val TypeRef: NameType = "TypeRef" val TypeTree: NameType = "TypeTree" val UNIT : NameType = "UNIT" val add_ : NameType = "add" val annotation: NameType = "annotation" val anyValClass: NameType = "anyValClass" - // val append: NameType = "append" + val append: NameType = "append" val apply: NameType = "apply" val applyDynamic: NameType = "applyDynamic" val applyDynamicNamed: NameType = "applyDynamicNamed" @@ -627,34 +627,34 @@ trait StdNames { val args : NameType = "args" val argv : NameType = "argv" val arrayClass: NameType = "arrayClass" - // val arrayElementClass: NameType = "arrayElementClass" - // val arrayValue: NameType = "arrayValue" + val arrayElementClass: NameType = "arrayElementClass" + val arrayValue: NameType = "arrayValue" val array_apply : NameType = "array_apply" val array_clone : NameType = "array_clone" val array_length : NameType = "array_length" val array_update : NameType = "array_update" - // val arraycopy: NameType = "arraycopy" - // val asTerm: NameType = "asTerm" + val arraycopy: NameType = "arraycopy" + val asTerm: NameType = "asTerm" val asModule: NameType = "asModule" - // val asMethod: NameType = "asMethod" + val asMethod: NameType = "asMethod" val asType: NameType = "asType" - // val asClass: NameType = "asClass" + val asClass: NameType = "asClass" val asInstanceOf_ : NameType = "asInstanceOf" val asInstanceOf_Ob : NameType = "$asInstanceOf" - // val assert_ : NameType = "assert" - // val assume_ : NameType = "assume" + val assert_ : NameType = "assert" + val assume_ : NameType = "assume" val box: NameType = "box" val build : NameType = "build" val bytes: NameType = "bytes" val canEqual_ : NameType = "canEqual" val checkInitialized: NameType = "checkInitialized" - // val ClassManifestFactory: NameType = "ClassManifestFactory" + val ClassManifestFactory: NameType = "ClassManifestFactory" val classOf: NameType = "classOf" val clone_ : NameType = if (forMSIL) "MemberwiseClone" else "clone" // sn.OClone causes checkinit failure val conforms: NameType = "conforms" val copy: NameType = "copy" val currentMirror: NameType = "currentMirror" - // val definitions: NameType = "definitions" + val definitions: NameType = "definitions" val delayedInit: NameType = "delayedInit" val delayedInitArg: NameType = "delayedInit$body" val drop: NameType = "drop" @@ -667,7 +667,7 @@ trait StdNames { val equalsNumObject : NameType = "equalsNumObject" val equals_ : NameType = if (forMSIL) "Equals" else "equals" val error: NameType = "error" - // val eval: NameType = "eval" + val eval: NameType = "eval" val ex: NameType = "ex" val experimental: NameType = "experimental" val f: NameType = "f" @@ -678,17 +678,17 @@ trait StdNames { val flagsFromBits : NameType = "flagsFromBits" val flatMap: NameType = "flatMap" val foreach: NameType = "foreach" - // val genericArrayOps: NameType = "genericArrayOps" + val genericArrayOps: NameType = "genericArrayOps" val get: NameType = "get" - // val getOrElse: NameType = "getOrElse" - // val hasNext: NameType = "hasNext" + val getOrElse: NameType = "getOrElse" + val hasNext: NameType = "hasNext" val hashCode_ : NameType = if (forMSIL) "GetHashCode" else "hashCode" val hash_ : NameType = "hash" - // val head: NameType = "head" - // val identity: NameType = "identity" + val head: NameType = "head" + val identity: NameType = "identity" val implicitly: NameType = "implicitly" val in: NameType = "in" - // val info: NameType = "info" + val info: NameType = "info" val inlinedEquals: NameType = "inlinedEquals" val isArray: NameType = "isArray" val isDefinedAt: NameType = "isDefinedAt" @@ -700,57 +700,57 @@ trait StdNames { val lang: NameType = "lang" val length: NameType = "length" val lengthCompare: NameType = "lengthCompare" - // val liftedTree: NameType = "liftedTree" - // val `macro` : NameType = "macro" - // val macroThis : NameType = "_this" + val liftedTree: NameType = "liftedTree" + val `macro` : NameType = "macro" + val macroThis : NameType = "_this" val macroContext : NameType = "c" val main: NameType = "main" - // val manifest: NameType = "manifest" - // val ManifestFactory: NameType = "ManifestFactory" + val manifest: NameType = "manifest" + val ManifestFactory: NameType = "ManifestFactory" val manifestToTypeTag: NameType = "manifestToTypeTag" val map: NameType = "map" val materializeClassTag: NameType = "materializeClassTag" val materializeWeakTypeTag: NameType = "materializeWeakTypeTag" val materializeTypeTag: NameType = "materializeTypeTag" - // val mirror : NameType = "mirror" + val mirror : NameType = "mirror" val moduleClass : NameType = "moduleClass" - // val name: NameType = "name" + val name: NameType = "name" val ne: NameType = "ne" val newArray: NameType = "newArray" val newFreeTerm: NameType = "newFreeTerm" val newFreeType: NameType = "newFreeType" val newNestedSymbol: NameType = "newNestedSymbol" val newScopeWith: NameType = "newScopeWith" - // val next: NameType = "next" + val next: NameType = "next" val nmeNewTermName: NameType = "newTermName" val nmeNewTypeName: NameType = "newTypeName" - // val normalize: NameType = "normalize" + val normalize: NameType = "normalize" val notifyAll_ : NameType = "notifyAll" val notify_ : NameType = "notify" val null_ : NameType = "null" - // val ofDim: NameType = "ofDim" - // val origin: NameType = "origin" + val ofDim: NameType = "ofDim" + val origin: NameType = "origin" val prefix : NameType = "prefix" val productArity: NameType = "productArity" val productElement: NameType = "productElement" val productIterator: NameType = "productIterator" val productPrefix: NameType = "productPrefix" val readResolve: NameType = "readResolve" - // val reflect : NameType = "reflect" + val reflect : NameType = "reflect" val reify : NameType = "reify" val rootMirror : NameType = "rootMirror" - // val runOrElse: NameType = "runOrElse" + val runOrElse: NameType = "runOrElse" val runtime: NameType = "runtime" val runtimeClass: NameType = "runtimeClass" val runtimeMirror: NameType = "runtimeMirror" - // val sameElements: NameType = "sameElements" + val sameElements: NameType = "sameElements" val scala_ : NameType = "scala" val selectDynamic: NameType = "selectDynamic" val selectOverloadedMethod: NameType = "selectOverloadedMethod" val selectTerm: NameType = "selectTerm" val selectType: NameType = "selectType" val self: NameType = "self" - // val setAccessible: NameType = "setAccessible" + val setAccessible: NameType = "setAccessible" val setAnnotations: NameType = "setAnnotations" val setSymbol: NameType = "setSymbol" val setType: NameType = "setType" @@ -760,15 +760,15 @@ trait StdNames { val staticModule : NameType = "staticModule" val staticPackage : NameType = "staticPackage" val synchronized_ : NameType = "synchronized" - // val tail: NameType = "tail" - // val `then` : NameType = "then" + val tail: NameType = "tail" + val `then` : NameType = "then" val this_ : NameType = "this" val thisPrefix : NameType = "thisPrefix" - // val throw_ : NameType = "throw" + val throw_ : NameType = "throw" val toArray: NameType = "toArray" - // val toList: NameType = "toList" + val toList: NameType = "toList" val toObjectArray : NameType = "toObjectArray" - // val toSeq: NameType = "toSeq" + val toSeq: NameType = "toSeq" val toString_ : NameType = if (forMSIL) "ToString" else "toString" val toTypeConstructor: NameType = "toTypeConstructor" val tpe : NameType = "tpe" @@ -788,14 +788,14 @@ trait StdNames { val view_ : NameType = "view" val wait_ : NameType = "wait" val withFilter: NameType = "withFilter" - // val wrap: NameType = "wrap" - // val zip: NameType = "zip" + val wrap: NameType = "wrap" + val zip: NameType = "zip" - // val synthSwitch: NameType = "$synthSwitch" + val synthSwitch: NameType = "$synthSwitch" // unencoded operators object raw { - // final val AMP : NameType = "&" + final val AMP : NameType = "&" final val BANG : NameType = "!" final val BAR : NameType = "|" final val DOLLAR: NameType = "$" @@ -804,7 +804,7 @@ trait StdNames { final val MINUS: NameType = "-" final val NE: NameType = "!=" final val PLUS : NameType = "+" - // final val SLASH: NameType = "/" + final val SLASH: NameType = "/" final val STAR : NameType = "*" final val TILDE: NameType = "~" @@ -860,14 +860,14 @@ trait StdNames { // Grouped here so Cleanup knows what tests to perform. val CommonOpNames = Set[Name](OR, XOR, AND, EQ, NE) - // val ConversionNames = Set[Name](toByte, toChar, toDouble, toFloat, toInt, toLong, toShort) + val ConversionNames = Set[Name](toByte, toChar, toDouble, toFloat, toInt, toLong, toShort) val BooleanOpNames = Set[Name](ZOR, ZAND, UNARY_!) ++ CommonOpNames - // val NumberOpNames = ( - // Set[Name](ADD, SUB, MUL, DIV, MOD, LSL, LSR, ASR, LT, LE, GE, GT) - // ++ Set(UNARY_+, UNARY_-, UNARY_!) - // ++ ConversionNames - // ++ CommonOpNames - // ) + val NumberOpNames = ( + Set[Name](ADD, SUB, MUL, DIV, MOD, LSL, LSR, ASR, LT, LE, GE, GT) + ++ Set(UNARY_+, UNARY_-, UNARY_!) + ++ ConversionNames + ++ CommonOpNames + ) val add: NameType = "add" val complement: NameType = "complement" @@ -999,7 +999,7 @@ trait StdNames { object fulltpnme extends TypeNames { val RuntimeNothing: NameType = "scala.runtime.Nothing$" val RuntimeNull: NameType = "scala.runtime.Null$" - // val JavaLangEnum: NameType = "java.lang.Enum" + val JavaLangEnum: NameType = "java.lang.Enum" } /** Java binary names, like scala/runtime/Nothing$. @@ -1015,15 +1015,15 @@ trait StdNames { object nme extends TermNames { - // def isModuleVarName(name: Name): Boolean = - // stripAnonNumberSuffix(name) endsWith MODULE_VAR_SUFFIX + def isModuleVarName(name: Name): Boolean = + stripAnonNumberSuffix(name) endsWith MODULE_VAR_SUFFIX def moduleVarName(name: TermName): TermName = newTermNameCached("" + name + MODULE_VAR_SUFFIX) def getCause = sn.GetCause def getClass_ = sn.GetClass - // def getComponentType = sn.GetComponentType + def getComponentType = sn.GetComponentType def getMethod_ = sn.GetMethod def invoke_ = sn.Invoke @@ -1036,14 +1036,14 @@ trait StdNames { val reflMethodCacheName: NameType = "reflMethod$Cache" val reflMethodName: NameType = "reflMethod$Method" - // private val reflectionCacheNames = Set[NameType]( - // reflPolyCacheName, - // reflClassCacheName, - // reflParamsCacheName, - // reflMethodCacheName, - // reflMethodName - // ) - // def isReflectionCacheName(name: Name) = reflectionCacheNames exists (name startsWith _) + private val reflectionCacheNames = Set[NameType]( + reflPolyCacheName, + reflClassCacheName, + reflParamsCacheName, + reflMethodCacheName, + reflMethodName + ) + def isReflectionCacheName(name: Name) = reflectionCacheNames exists (name startsWith _) @deprecated("Use a method in tpnme", "2.10.0") def dropSingletonName(name: Name): TypeName = tpnme.dropSingletonName(name) @deprecated("Use a method in tpnme", "2.10.0") def singletonName(name: Name): TypeName = tpnme.singletonName(name) @@ -1056,28 +1056,28 @@ trait StdNames { protected val stringToTypeName = null protected implicit def createNameType(s: String): TypeName = newTypeNameCached(s) - // val BeanProperty : TypeName - // val BooleanBeanProperty : TypeName + val BeanProperty : TypeName + val BooleanBeanProperty : TypeName val BoxedBoolean : TypeName val BoxedCharacter : TypeName val BoxedNumber : TypeName - // val Class : TypeName + val Class : TypeName val Delegate : TypeName val IOOBException : TypeName // IndexOutOfBoundsException val InvTargetException : TypeName // InvocationTargetException - // val JavaSerializable : TypeName + val JavaSerializable : TypeName val MethodAsObject : TypeName val NPException : TypeName // NullPointerException val Object : TypeName - // val String : TypeName + val String : TypeName val Throwable : TypeName val ValueType : TypeName - // val ForName : TermName + val ForName : TermName val GetCause : TermName val GetClass : TermName val GetClassLoader : TermName - // val GetComponentType : TermName + val GetComponentType : TermName val GetMethod : TermName val Invoke : TermName val JavaLang : TermName @@ -1152,22 +1152,22 @@ trait StdNames { final val BoxedLong: TypeName = "java.lang.Long" final val BoxedNumber: TypeName = "java.lang.Number" final val BoxedShort: TypeName = "java.lang.Short" - // final val Class: TypeName = "java.lang.Class" + final val Class: TypeName = "java.lang.Class" final val Delegate: TypeName = tpnme.NO_NAME final val IOOBException: TypeName = "java.lang.IndexOutOfBoundsException" final val InvTargetException: TypeName = "java.lang.reflect.InvocationTargetException" final val MethodAsObject: TypeName = "java.lang.reflect.Method" final val NPException: TypeName = "java.lang.NullPointerException" final val Object: TypeName = "java.lang.Object" - // final val String: TypeName = "java.lang.String" + final val String: TypeName = "java.lang.String" final val Throwable: TypeName = "java.lang.Throwable" final val ValueType: TypeName = tpnme.NO_NAME - // final val ForName: TermName = newTermName("forName") + final val ForName: TermName = newTermName("forName") final val GetCause: TermName = newTermName("getCause") final val GetClass: TermName = newTermName("getClass") final val GetClassLoader: TermName = newTermName("getClassLoader") - // final val GetComponentType: TermName = newTermName("getComponentType") + final val GetComponentType: TermName = newTermName("getComponentType") final val GetMethod: TermName = newTermName("getMethod") final val Invoke: TermName = newTermName("invoke") final val JavaLang: TermName = newTermName("java.lang") @@ -1185,28 +1185,28 @@ trait StdNames { } private class MSILNames extends SymbolNames { - // final val BeanProperty: TypeName = tpnme.NO_NAME - // final val BooleanBeanProperty: TypeName = tpnme.NO_NAME + final val BeanProperty: TypeName = tpnme.NO_NAME + final val BooleanBeanProperty: TypeName = tpnme.NO_NAME final val BoxedBoolean: TypeName = "System.IConvertible" final val BoxedCharacter: TypeName = "System.IConvertible" final val BoxedNumber: TypeName = "System.IConvertible" - // final val Class: TypeName = "System.Type" + final val Class: TypeName = "System.Type" final val Delegate: TypeName = "System.MulticastDelegate" final val IOOBException: TypeName = "System.IndexOutOfRangeException" final val InvTargetException: TypeName = "System.Reflection.TargetInvocationException" - // final val JavaSerializable: TypeName = tpnme.NO_NAME + final val JavaSerializable: TypeName = tpnme.NO_NAME final val MethodAsObject: TypeName = "System.Reflection.MethodInfo" final val NPException: TypeName = "System.NullReferenceException" final val Object: TypeName = "System.Object" - // final val String: TypeName = "System.String" + final val String: TypeName = "System.String" final val Throwable: TypeName = "System.Exception" final val ValueType: TypeName = "System.ValueType" - // final val ForName: TermName = newTermName("GetType") + final val ForName: TermName = newTermName("GetType") final val GetCause: TermName = newTermName("InnerException") /* System.Reflection.TargetInvocationException.InnerException */ final val GetClass: TermName = newTermName("GetType") final lazy val GetClassLoader: TermName = throw new UnsupportedOperationException("Scala reflection is not supported on this platform"); - // final val GetComponentType: TermName = newTermName("GetElementType") + final val GetComponentType: TermName = newTermName("GetElementType") final val GetMethod: TermName = newTermName("GetMethod") final val Invoke: TermName = newTermName("Invoke") final val JavaLang: TermName = newTermName("System") @@ -1223,13 +1223,13 @@ trait StdNames { ) } - // private class J2SENames extends JavaNames { - // final val BeanProperty: TypeName = "scala.beans.BeanProperty" - // final val BooleanBeanProperty: TypeName = "scala.beans.BooleanBeanProperty" - // final val JavaSerializable: TypeName = "java.io.Serializable" - // } + private class J2SENames extends JavaNames { + final val BeanProperty: TypeName = "scala.beans.BeanProperty" + final val BooleanBeanProperty: TypeName = "scala.beans.BooleanBeanProperty" + final val JavaSerializable: TypeName = "java.io.Serializable" + } lazy val sn: SymbolNames = if (forMSIL) new MSILNames - else new JavaNames { } + else new J2SENames } diff --git a/src/reflect/scala/reflect/internal/SymbolTable.scala b/src/reflect/scala/reflect/internal/SymbolTable.scala index c72fb96611..fb1bf9ed9d 100644 --- a/src/reflect/scala/reflect/internal/SymbolTable.scala +++ b/src/reflect/scala/reflect/internal/SymbolTable.scala @@ -184,7 +184,7 @@ abstract class SymbolTable extends macros.Universe final def phaseId(period: Period): Phase#Id = period & 0xFF /** The period at the start of run that includes `period`. */ - // final def startRun(period: Period): Period = period & 0xFFFFFF00 + final def startRun(period: Period): Period = period & 0xFFFFFF00 /** The current period. */ final def currentPeriod: Period = { @@ -298,6 +298,7 @@ abstract class SymbolTable extends macros.Universe object perRunCaches { import java.lang.ref.WeakReference + import scala.runtime.ScalaRunTime.stringOf import scala.collection.generic.Clearable // Weak references so the garbage collector will take care of diff --git a/src/reflect/scala/reflect/internal/Symbols.scala b/src/reflect/scala/reflect/internal/Symbols.scala index 89c3659b2e..eec780470e 100644 --- a/src/reflect/scala/reflect/internal/Symbols.scala +++ b/src/reflect/scala/reflect/internal/Symbols.scala @@ -19,7 +19,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => protected var ids = 0 - // val emptySymbolArray = new Array[Symbol](0) + val emptySymbolArray = new Array[Symbol](0) protected def nextId() = { ids += 1; ids } @@ -256,8 +256,8 @@ trait Symbols extends api.Symbols { self: SymbolTable => (m, c) } - // final def newPackageSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol = - // newTermSymbol(name, pos, newFlags).asInstanceOf[ModuleSymbol] + final def newPackageSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol = + newTermSymbol(name, pos, newFlags).asInstanceOf[ModuleSymbol] final def newModuleClassSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleClassSymbol = newClassSymbol(name, pos, newFlags).asInstanceOf[ModuleClassSymbol] @@ -323,8 +323,8 @@ trait Symbols extends api.Symbols { self: SymbolTable => /** Synthetic value parameters when parameter symbols are not available */ - // final def newSyntheticValueParamss(argtypess: List[List[Type]]): List[List[TermSymbol]] = - // argtypess map (xs => newSyntheticValueParams(xs, freshNamer)) + final def newSyntheticValueParamss(argtypess: List[List[Type]]): List[List[TermSymbol]] = + argtypess map (xs => newSyntheticValueParams(xs, freshNamer)) /** Synthetic value parameters when parameter symbols are not available. * Calling this method multiple times will re-use the same parameter names. @@ -341,7 +341,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => final def newSyntheticValueParam(argtype: Type, name: TermName = nme.syntheticParamName(1)): TermSymbol = newValueParameter(name, owner.pos.focus, SYNTHETIC) setInfo argtype - // def newSyntheticTypeParam(): TypeSymbol = newSyntheticTypeParam("T0", 0L) + def newSyntheticTypeParam(): TypeSymbol = newSyntheticTypeParam("T0", 0L) def newSyntheticTypeParam(name: String, newFlags: Long): TypeSymbol = newTypeParameter(newTypeName(name), NoPosition, newFlags) setInfo TypeBounds.empty def newSyntheticTypeParams(num: Int): List[TypeSymbol] = (0 until num).toList map (n => newSyntheticTypeParam("T" + n, 0L)) @@ -407,11 +407,11 @@ trait Symbols extends api.Symbols { self: SymbolTable => /** Create a new getter for current symbol (which must be a field) */ - // final def newGetter: MethodSymbol = ( - // owner.newMethod(nme.getterName(name.toTermName), NoPosition, getterFlags(flags)) - // setPrivateWithin privateWithin - // setInfo MethodType(Nil, tpe) - // ) + final def newGetter: MethodSymbol = ( + owner.newMethod(nme.getterName(name.toTermName), NoPosition, getterFlags(flags)) + setPrivateWithin privateWithin + setInfo MethodType(Nil, tpe) + ) final def newErrorSymbol(name: Name): Symbol = name match { case x: TypeName => newErrorClass(x) @@ -528,14 +528,14 @@ trait Symbols extends api.Symbols { self: SymbolTable => */ def isContravariant = false def isCovariant = false - // def isExistentialQuantified = false + def isExistentialQuantified = false def isExistentialSkolem = false def isExistentiallyBound = false def isGADTSkolem = false def isTypeParameter = false def isTypeParameterOrSkolem = false def isTypeSkolem = false - // def isTypeMacro = false + def isTypeMacro = false def isInvariant = !isCovariant && !isContravariant /** Qualities of Terms, always false for TypeSymbols. @@ -719,14 +719,14 @@ trait Symbols extends api.Symbols { self: SymbolTable => = hasAnnotation(DeprecatedInheritanceAttr) def deprecatedInheritanceMessage = getAnnotation(DeprecatedInheritanceAttr) flatMap (_ stringArg 0) - // def deprecatedInheritanceVersion - // = getAnnotation(DeprecatedInheritanceAttr) flatMap (_ stringArg 1) + def deprecatedInheritanceVersion + = getAnnotation(DeprecatedInheritanceAttr) flatMap (_ stringArg 1) def hasDeprecatedOverridingAnnotation = hasAnnotation(DeprecatedOverridingAttr) def deprecatedOverridingMessage = getAnnotation(DeprecatedOverridingAttr) flatMap (_ stringArg 0) - // def deprecatedOverridingVersion - // = getAnnotation(DeprecatedOverridingAttr) flatMap (_ stringArg 1) + def deprecatedOverridingVersion + = getAnnotation(DeprecatedOverridingAttr) flatMap (_ stringArg 1) // !!! when annotation arguments are not literal strings, but any sort of // assembly of strings, there is a fair chance they will turn up here not as @@ -806,7 +806,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => final def isStaticOwner: Boolean = isPackageClass || isModuleClass && isStatic - // def isTopLevelModule = hasFlag(MODULE) && owner.isPackageClass + def isTopLevelModule = hasFlag(MODULE) && owner.isPackageClass /** A helper function for isEffectivelyFinal. */ private def isNotOverridden = ( @@ -844,7 +844,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => */ def isLocalClass = false - // def isStableClass = false + def isStableClass = false /* code for fixing nested objects override final def isModuleClass: Boolean = @@ -869,8 +869,8 @@ trait Symbols extends api.Symbols { self: SymbolTable => final def isPossibleInRefinement = !isConstructor && !isOverridingSymbol /** Is this symbol a member of class `clazz`? */ - // def isMemberOf(clazz: Symbol) = - // clazz.info.member(name).alternatives contains this + def isMemberOf(clazz: Symbol) = + clazz.info.member(name).alternatives contains this /** A a member of class `base` is incomplete if * (1) it is declared deferred or @@ -972,14 +972,6 @@ trait Symbols extends api.Symbols { self: SymbolTable => def ownerChain: List[Symbol] = this :: owner.ownerChain def originalOwnerChain: List[Symbol] = this :: originalOwner.getOrElse(this, rawowner).originalOwnerChain - // All the symbols overridden by this symbol and this symbol at the head, - // or Nil if this is NoSymbol. - def overrideChain = ( - if (this eq NoSymbol) Nil - else if (!owner.isClass) this :: Nil - else this :: allOverriddenSymbols - ) - // Non-classes skip self and return rest of owner chain; overridden in ClassSymbol. def enclClassChain: List[Symbol] = owner.enclClassChain @@ -1089,8 +1081,8 @@ trait Symbols extends api.Symbols { self: SymbolTable => protected def createImplClassSymbol(name: TypeName, pos: Position, newFlags: Long): ClassSymbol = new ClassSymbol(this, pos, name) with ImplClassSymbol initFlags newFlags - // protected def createTermSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol = - // new TermSymbol(this, pos, name) initFlags newFlags + protected def createTermSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol = + new TermSymbol(this, pos, name) initFlags newFlags protected def createMethodSymbol(name: TermName, pos: Position, newFlags: Long): MethodSymbol = new MethodSymbol(this, pos, name) initFlags newFlags @@ -1454,12 +1446,12 @@ trait Symbols extends api.Symbols { self: SymbolTable => !isInitialized && (flags & LOCKED) == 0 && shouldTriggerCompleter(this, if (infos ne null) infos.info else null, isFlagRelated, mask) /** Was symbol's type updated during given phase? */ - // final def isUpdatedAt(pid: Phase#Id): Boolean = { - // assert(isCompilerUniverse) - // var infos = this.infos - // while ((infos ne null) && phaseId(infos.validFrom) != pid + 1) infos = infos.prev - // infos ne null - // } + final def isUpdatedAt(pid: Phase#Id): Boolean = { + assert(isCompilerUniverse) + var infos = this.infos + while ((infos ne null) && phaseId(infos.validFrom) != pid + 1) infos = infos.prev + infos ne null + } /** Was symbol's type updated during given phase? */ final def hasTypeAt(pid: Phase#Id): Boolean = { @@ -1952,10 +1944,10 @@ trait Symbols extends api.Symbols { self: SymbolTable => (this.rawInfo ne NoType) && (this.effectiveOwner == that.effectiveOwner) && ( !this.effectiveOwner.isPackageClass - || (this.associatedFile eq null) - || (that.associatedFile eq null) - || (this.associatedFile.path == that.associatedFile.path) // Cheap possibly wrong check, then expensive normalization - || (this.associatedFile.canonicalPath == that.associatedFile.canonicalPath) + || (this.sourceFile eq null) + || (that.sourceFile eq null) + || (this.sourceFile.path == that.sourceFile.path) // Cheap possibly wrong check, then expensive normalization + || (this.sourceFile.canonicalPath == that.sourceFile.canonicalPath) ) ) @@ -2082,10 +2074,9 @@ trait Symbols extends api.Symbols { self: SymbolTable => if (isClassConstructor) NoSymbol else matchingSymbol(ofclazz, ofclazz.thisType) /** Returns all symbols overriden by this symbol. */ - final def allOverriddenSymbols: List[Symbol] = ( - if ((this eq NoSymbol) || !owner.isClass) Nil + final def allOverriddenSymbols: List[Symbol] = + if (!owner.isClass) Nil else owner.ancestors map overriddenSymbol filter (_ != NoSymbol) - ) /** Equivalent to allOverriddenSymbols.nonEmpty, but more efficient. */ // !!! When if ever will this answer differ from .isOverride? @@ -2096,7 +2087,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => ) /** Equivalent to allOverriddenSymbols.head (or NoSymbol if no overrides) but more efficient. */ def nextOverriddenSymbol: Symbol = { - if ((this ne NoSymbol) && owner.isClass) owner.ancestors foreach { base => + if (owner.isClass) owner.ancestors foreach { base => val sym = overriddenSymbol(base) if (sym != NoSymbol) return sym @@ -2217,10 +2208,10 @@ trait Symbols extends api.Symbols { self: SymbolTable => private def sourceFileOnly(file: AbstractFile): AbstractFile = if ((file eq null) || (file.path endsWith ".class")) null else file - // private def binaryFileOnly(file: AbstractFile): AbstractFile = - // if ((file eq null) || !(file.path endsWith ".class")) null else file + private def binaryFileOnly(file: AbstractFile): AbstractFile = + if ((file eq null) || !(file.path endsWith ".class")) null else file - // final def binaryFile: AbstractFile = binaryFileOnly(associatedFile) + final def binaryFile: AbstractFile = binaryFileOnly(associatedFile) final def sourceFile: AbstractFile = sourceFileOnly(associatedFile) /** Overridden in ModuleSymbols to delegate to the module class. */ @@ -2245,7 +2236,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => // ------ toString ------------------------------------------------------------------- /** A tag which (in the ideal case) uniquely identifies class symbols */ - // final def tag: Int = fullName.## + final def tag: Int = fullName.## /** The simple name of this Symbol */ final def simpleName: Name = name @@ -2714,7 +2705,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => final def asNameType(n: Name) = n.toTypeName override def isNonClassType = true - // override def isTypeMacro = hasFlag(MACRO) + override def isTypeMacro = hasFlag(MACRO) override def resolveOverloadedFlag(flag: Long) = flag match { case TRAIT => "" // DEFAULTPARAM @@ -2732,7 +2723,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => override def isAbstractType = this hasFlag DEFERRED override def isContravariant = this hasFlag CONTRAVARIANT override def isCovariant = this hasFlag COVARIANT - // override def isExistentialQuantified = isExistentiallyBound && !isSkolem + override def isExistentialQuantified = isExistentiallyBound && !isSkolem override def isExistentiallyBound = this hasFlag EXISTENTIAL override def isTypeParameter = isTypeParameterOrSkolem && !isSkolem override def isTypeParameterOrSkolem = this hasFlag PARAM @@ -2863,7 +2854,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => override def isTypeSkolem = this hasFlag PARAM override def isAbstractType = this hasFlag DEFERRED - // override def isExistentialQuantified = false + override def isExistentialQuantified = false override def existentialBound = if (isAbstractType) this.info else super.existentialBound /** If typeskolem comes from a type parameter, that parameter, otherwise skolem itself */ @@ -2949,21 +2940,21 @@ trait Symbols extends api.Symbols { self: SymbolTable => || isLocal || !owner.isPackageClass && owner.isLocalClass ) - // override def isStableClass = (this hasFlag STABLE) || checkStable() - - // private def checkStable() = { - // def hasNoAbstractTypeMember(clazz: Symbol): Boolean = - // (clazz hasFlag STABLE) || { - // var e = clazz.info.decls.elems - // while ((e ne null) && !(e.sym.isAbstractType && info.member(e.sym.name) == e.sym)) - // e = e.next - // e == null - // } - // (info.baseClasses forall hasNoAbstractTypeMember) && { - // setFlag(STABLE) - // true - // } - // } + override def isStableClass = (this hasFlag STABLE) || checkStable() + + private def checkStable() = { + def hasNoAbstractTypeMember(clazz: Symbol): Boolean = + (clazz hasFlag STABLE) || { + var e = clazz.info.decls.elems + while ((e ne null) && !(e.sym.isAbstractType && info.member(e.sym.name) == e.sym)) + e = e.next + e == null + } + (info.baseClasses forall hasNoAbstractTypeMember) && { + setFlag(STABLE) + true + } + } override def enclClassChain = this :: owner.enclClassChain diff --git a/src/reflect/scala/reflect/internal/TreeGen.scala b/src/reflect/scala/reflect/internal/TreeGen.scala index 6c8ba047d6..6ce93d93b2 100644 --- a/src/reflect/scala/reflect/internal/TreeGen.scala +++ b/src/reflect/scala/reflect/internal/TreeGen.scala @@ -11,10 +11,10 @@ abstract class TreeGen extends macros.TreeBuilder { def rootScalaDot(name: Name) = Select(rootId(nme.scala_) setSymbol ScalaPackage, name) def scalaDot(name: Name) = Select(Ident(nme.scala_) setSymbol ScalaPackage, name) def scalaAnnotationDot(name: Name) = Select(scalaDot(nme.annotation), name) - // def scalaAnyRefConstr = scalaDot(tpnme.AnyRef) setSymbol AnyRefClass - // def scalaUnitConstr = scalaDot(tpnme.Unit) setSymbol UnitClass - // def productConstr = scalaDot(tpnme.Product) setSymbol ProductRootClass - // def serializableConstr = scalaDot(tpnme.Serializable) setSymbol SerializableClass + def scalaAnyRefConstr = scalaDot(tpnme.AnyRef) setSymbol AnyRefClass + def scalaUnitConstr = scalaDot(tpnme.Unit) setSymbol UnitClass + def productConstr = scalaDot(tpnme.Product) setSymbol ProductRootClass + def serializableConstr = scalaDot(tpnme.Serializable) setSymbol SerializableClass def scalaFunctionConstr(argtpes: List[Tree], restpe: Tree, abstractFun: Boolean = false): Tree = { val cls = if (abstractFun) @@ -248,8 +248,8 @@ abstract class TreeGen extends macros.TreeBuilder { Literal(Constant(tp)) setType ConstantType(Constant(tp)) /** Builds a list with given head and tail. */ - // def mkNewCons(head: Tree, tail: Tree): Tree = - // New(Apply(mkAttributedRef(ConsClass), List(head, tail))) + def mkNewCons(head: Tree, tail: Tree): Tree = + New(Apply(mkAttributedRef(ConsClass), List(head, tail))) /** Builds a list with given head and tail. */ def mkNil: Tree = mkAttributedRef(NilModule) diff --git a/src/reflect/scala/reflect/internal/TreeInfo.scala b/src/reflect/scala/reflect/internal/TreeInfo.scala index 2b1292e145..7ae7cf1821 100644 --- a/src/reflect/scala/reflect/internal/TreeInfo.scala +++ b/src/reflect/scala/reflect/internal/TreeInfo.scala @@ -135,8 +135,8 @@ abstract class TreeInfo { @deprecated("Use isExprSafeToInline instead", "2.10.0") def isPureExpr(tree: Tree) = isExprSafeToInline(tree) - // def zipMethodParamsAndArgs(params: List[Symbol], args: List[Tree]): List[(Symbol, Tree)] = - // mapMethodParamsAndArgs(params, args)((param, arg) => ((param, arg))) + def zipMethodParamsAndArgs(params: List[Symbol], args: List[Tree]): List[(Symbol, Tree)] = + mapMethodParamsAndArgs(params, args)((param, arg) => ((param, arg))) def mapMethodParamsAndArgs[R](params: List[Symbol], args: List[Tree])(f: (Symbol, Tree) => R): List[R] = { val b = List.newBuilder[R] @@ -186,25 +186,25 @@ abstract class TreeInfo { * * Also accounts for varargs. */ - // private def applyMethodParameters(fn: Tree): List[Symbol] = { - // val depth = applyDepth(fn) - // // There could be applies which go beyond the parameter list(s), - // // being applied to the result of the method call. - // // !!! Note that this still doesn't seem correct, although it should - // // be closer than what it replaced. - // if (depth < fn.symbol.paramss.size) fn.symbol.paramss(depth) - // else if (fn.symbol.paramss.isEmpty) Nil - // else fn.symbol.paramss.last - // } - - // def zipMethodParamsAndArgs(t: Tree): List[(Symbol, Tree)] = t match { - // case Apply(fn, args) => zipMethodParamsAndArgs(applyMethodParameters(fn), args) - // case _ => Nil - // } - // def foreachMethodParamAndArg(t: Tree)(f: (Symbol, Tree) => Unit): Unit = t match { - // case Apply(fn, args) => foreachMethodParamAndArg(applyMethodParameters(fn), args)(f) - // case _ => - // } + private def applyMethodParameters(fn: Tree): List[Symbol] = { + val depth = applyDepth(fn) + // There could be applies which go beyond the parameter list(s), + // being applied to the result of the method call. + // !!! Note that this still doesn't seem correct, although it should + // be closer than what it replaced. + if (depth < fn.symbol.paramss.size) fn.symbol.paramss(depth) + else if (fn.symbol.paramss.isEmpty) Nil + else fn.symbol.paramss.last + } + + def zipMethodParamsAndArgs(t: Tree): List[(Symbol, Tree)] = t match { + case Apply(fn, args) => zipMethodParamsAndArgs(applyMethodParameters(fn), args) + case _ => Nil + } + def foreachMethodParamAndArg(t: Tree)(f: (Symbol, Tree) => Unit): Unit = t match { + case Apply(fn, args) => foreachMethodParamAndArg(applyMethodParameters(fn), args)(f) + case _ => + } /** Is symbol potentially a getter of a variable? */ @@ -354,10 +354,10 @@ abstract class TreeInfo { case x: Ident => !x.isBackquoted && nme.isVariableName(x.name) case _ => false } - // def isDeprecatedIdentifier(tree: Tree): Boolean = tree match { - // case x: Ident => !x.isBackquoted && nme.isDeprecatedIdentifierName(x.name) - // case _ => false - // } + def isDeprecatedIdentifier(tree: Tree): Boolean = tree match { + case x: Ident => !x.isBackquoted && nme.isDeprecatedIdentifierName(x.name) + case _ => false + } /** The first constructor definitions in `stats` */ def firstConstructor(stats: List[Tree]): Tree = stats find { @@ -417,10 +417,10 @@ abstract class TreeInfo { def isLeftAssoc(operator: Name) = operator.nonEmpty && (operator.endChar != ':') /** Is tree a `this` node which belongs to `enclClass`? */ - // def isSelf(tree: Tree, enclClass: Symbol): Boolean = tree match { - // case This(_) => tree.symbol == enclClass - // case _ => false - // } + def isSelf(tree: Tree, enclClass: Symbol): Boolean = tree match { + case This(_) => tree.symbol == enclClass + case _ => false + } /** a Match(Typed(_, tpt), _) must be translated into a switch if isSwitchAnnotation(tpt.tpe) */ def isSwitchAnnotation(tpe: Type) = tpe hasAnnotation definitions.SwitchClass diff --git a/src/reflect/scala/reflect/internal/Trees.scala b/src/reflect/scala/reflect/internal/Trees.scala index c93750165d..ed08226ec7 100644 --- a/src/reflect/scala/reflect/internal/Trees.scala +++ b/src/reflect/scala/reflect/internal/Trees.scala @@ -847,7 +847,7 @@ trait Trees extends api.Trees { self: SymbolTable => /** Is the tree Predef, scala.Predef, or _root_.scala.Predef? */ def isReferenceToPredef(t: Tree) = isReferenceToScalaMember(t, nme.Predef) - // def isReferenceToAnyVal(t: Tree) = isReferenceToScalaMember(t, tpnme.AnyVal) + def isReferenceToAnyVal(t: Tree) = isReferenceToScalaMember(t, tpnme.AnyVal) // --- modifiers implementation --------------------------------------- diff --git a/src/reflect/scala/reflect/internal/TypeDebugging.scala b/src/reflect/scala/reflect/internal/TypeDebugging.scala index 9c2457e402..68b4fa69a1 100644 --- a/src/reflect/scala/reflect/internal/TypeDebugging.scala +++ b/src/reflect/scala/reflect/internal/TypeDebugging.scala @@ -9,6 +9,8 @@ package internal trait TypeDebugging { self: SymbolTable => + import definitions._ + // @M toString that is safe during debugging (does not normalize, ...) object typeDebug { private def to_s(x: Any): String = x match { @@ -18,7 +20,7 @@ trait TypeDebugging { case x: Product => x.productIterator mkString ("(", ", ", ")") case _ => "" + x } - // def ptIndent(x: Any) = ("" + x).replaceAll("\\n", " ") + def ptIndent(x: Any) = ("" + x).replaceAll("\\n", " ") def ptBlock(label: String, pairs: (String, Any)*): String = { if (pairs.isEmpty) label + "{ }" else { diff --git a/src/reflect/scala/reflect/internal/Types.scala b/src/reflect/scala/reflect/internal/Types.scala index 0f92388993..42a9d9e456 100644 --- a/src/reflect/scala/reflect/internal/Types.scala +++ b/src/reflect/scala/reflect/internal/Types.scala @@ -167,10 +167,10 @@ trait Types extends api.Types { self: SymbolTable => log = Nil } finally unlock() } - // def size = { - // lock() - // try log.size finally unlock() - // } + def size = { + lock() + try log.size finally unlock() + } // `block` should not affect constraints on typevars def undo[T](block: => T): T = { @@ -184,18 +184,18 @@ trait Types extends api.Types { self: SymbolTable => } // if `block` evaluates to false, it should not affect constraints on typevars - // def undoUnless(block: => Boolean): Boolean = { - // lock() - // try { - // val before = log - // var result = false + def undoUnless(block: => Boolean): Boolean = { + lock() + try { + val before = log + var result = false - // try result = block - // finally if (!result) undoTo(before) + try result = block + finally if (!result) undoTo(before) - // result - // } finally unlock() - // } + result + } finally unlock() + } } /** A map from lists to compound types that have the given list as parents. @@ -292,7 +292,7 @@ trait Types extends api.Types { self: SymbolTable => abstract class TypeApiImpl extends TypeApi { this: Type => def declaration(name: Name): Symbol = decl(name) - // def nonPrivateDeclaration(name: Name): Symbol = nonPrivateDecl(name) + def nonPrivateDeclaration(name: Name): Symbol = nonPrivateDecl(name) def declarations = decls def typeArguments = typeArgs def erasure = this match { @@ -522,7 +522,7 @@ trait Types extends api.Types { self: SymbolTable => /** If this is a TypeRef `clazz`[`T`], return the argument `T` * otherwise return this type */ - // def remove(clazz: Symbol): Type = this + def remove(clazz: Symbol): Type = this /** For a curried/nullary method or poly type its non-method result type, * the type itself for all other types */ @@ -663,13 +663,13 @@ trait Types extends api.Types { self: SymbolTable => /** All members with the given flags, excluding bridges. */ - // def membersWithFlags(requiredFlags: Long): Scope = - // membersBasedOnFlags(BridgeFlags, requiredFlags) + def membersWithFlags(requiredFlags: Long): Scope = + membersBasedOnFlags(BridgeFlags, requiredFlags) /** All non-private members with the given flags, excluding bridges. */ - // def nonPrivateMembersWithFlags(requiredFlags: Long): Scope = - // membersBasedOnFlags(BridgeAndPrivateFlags, requiredFlags) + def nonPrivateMembersWithFlags(requiredFlags: Long): Scope = + membersBasedOnFlags(BridgeAndPrivateFlags, requiredFlags) /** The non-private member with given name, admitting members with given flags `admit`. * "Admitting" refers to the fact that members with a PRIVATE, BRIDGE, or VBRIDGE @@ -806,7 +806,7 @@ trait Types extends api.Types { self: SymbolTable => else substThis(from, to).substSym(symsFrom, symsTo) /** Returns all parts of this type which satisfy predicate `p` */ - // def filter(p: Type => Boolean): List[Type] = new FilterTypeCollector(p) collect this + def filter(p: Type => Boolean): List[Type] = new FilterTypeCollector(p) collect this def withFilter(p: Type => Boolean) = new FilterMapForeach(p) class FilterMapForeach(p: Type => Boolean) extends FilterTypeCollector(p){ @@ -837,7 +837,7 @@ trait Types extends api.Types { self: SymbolTable => def contains(sym: Symbol): Boolean = new ContainsCollector(sym).collect(this) /** Does this type contain a reference to this type */ - // def containsTp(tp: Type): Boolean = new ContainsTypeCollector(tp).collect(this) + def containsTp(tp: Type): Boolean = new ContainsTypeCollector(tp).collect(this) /** Is this type a subtype of that type? */ def <:<(that: Type): Boolean = { @@ -900,9 +900,9 @@ trait Types extends api.Types { self: SymbolTable => ); /** Does this type implement symbol `sym` with same or stronger type? */ - // def specializes(sym: Symbol): Boolean = - // if (explainSwitch) explain("specializes", specializesSym, this, sym) - // else specializesSym(this, sym) + def specializes(sym: Symbol): Boolean = + if (explainSwitch) explain("specializes", specializesSym, this, sym) + else specializesSym(this, sym) /** Is this type close enough to that type so that members * with the two type would override each other? @@ -1243,7 +1243,7 @@ trait Types extends api.Types { self: SymbolTable => /** Remove any annotations from this type and from any * types embedded in this type. */ - // def stripAnnotations = StripAnnotationsMap(this) + def stripAnnotations = StripAnnotationsMap(this) /** Set the self symbol of an annotated type, or do nothing * otherwise. */ @@ -2917,14 +2917,14 @@ trait Types extends api.Types { self: SymbolTable => } // Not used yet. - // object HasTypeParams { - // def unapply(tp: Type): Option[(List[Symbol], Type)] = tp match { - // case AnnotatedType(_, tp, _) => unapply(tp) - // case ExistentialType(tparams, qtpe) => Some((tparams, qtpe)) - // case PolyType(tparams, restpe) => Some((tparams, restpe)) - // case _ => None - // } - // } + object HasTypeParams { + def unapply(tp: Type): Option[(List[Symbol], Type)] = tp match { + case AnnotatedType(_, tp, _) => unapply(tp) + case ExistentialType(tparams, qtpe) => Some((tparams, qtpe)) + case PolyType(tparams, restpe) => Some((tparams, restpe)) + case _ => None + } + } //@M // a TypeVar used to be a case class with only an origin and a constr @@ -3019,7 +3019,7 @@ trait Types extends api.Types { self: SymbolTable => require(params.nonEmpty, this) override def isHigherKinded = true - // override protected def typeVarString = params.map(_.name).mkString("[", ", ", "]=>" + originName) + override protected def typeVarString = params.map(_.name).mkString("[", ", ", "]=>" + originName) } /** Precondition: zipped params/args nonEmpty. (Size equivalence enforced structurally.) @@ -3035,9 +3035,9 @@ trait Types extends api.Types { self: SymbolTable => override def params: List[Symbol] = zippedArgs map (_._1) override def typeArgs: List[Type] = zippedArgs map (_._2) - // override protected def typeVarString = ( - // zippedArgs map { case (p, a) => p.name + "=" + a } mkString (origin + "[", ", ", "]") - // ) + override protected def typeVarString = ( + zippedArgs map { case (p, a) => p.name + "=" + a } mkString (origin + "[", ", ", "]") + ) } trait UntouchableTypeVar extends TypeVar { @@ -3357,7 +3357,7 @@ trait Types extends api.Types { self: SymbolTable => ).flatten map (s => s.decodedName + tparamsOfSym(s)) mkString "#" } private def levelString = if (settings.explaintypes.value) level else "" - // protected def typeVarString = originName + protected def typeVarString = originName override def safeToString = ( if ((constr eq null) || (constr.inst eq null)) "TVar<" + originName + "=null>" else if (constr.inst ne NoType) "=?" + constr.inst @@ -3714,18 +3714,18 @@ trait Types extends api.Types { self: SymbolTable => * list given is List(AnyRefClass), the resulting type would be * e.g. Set[_ <: AnyRef] rather than Set[AnyRef] . */ - // def appliedTypeAsUpperBounds(tycon: Type, args: List[Type]): Type = { - // tycon match { - // case TypeRef(pre, sym, _) if sameLength(sym.typeParams, args) => - // val eparams = typeParamsToExistentials(sym) - // val bounds = args map (TypeBounds upper _) - // foreach2(eparams, bounds)(_ setInfo _) - - // newExistentialType(eparams, typeRef(pre, sym, eparams map (_.tpe))) - // case _ => - // appliedType(tycon, args) - // } - // } + def appliedTypeAsUpperBounds(tycon: Type, args: List[Type]): Type = { + tycon match { + case TypeRef(pre, sym, _) if sameLength(sym.typeParams, args) => + val eparams = typeParamsToExistentials(sym) + val bounds = args map (TypeBounds upper _) + foreach2(eparams, bounds)(_ setInfo _) + + newExistentialType(eparams, typeRef(pre, sym, eparams map (_.tpe))) + case _ => + appliedType(tycon, args) + } + } /** A creator and extractor for type parameterizations that strips empty type parameter lists. * Use this factory method to indicate the type has kind * (it's a polymorphic value) @@ -3829,16 +3829,16 @@ trait Types extends api.Types { self: SymbolTable => } /** Substitutes the empty scope for any non-empty decls in the type. */ - // object dropAllRefinements extends TypeMap { - // def apply(tp: Type): Type = tp match { - // case rt @ RefinedType(parents, decls) if !decls.isEmpty => - // mapOver(copyRefinedType(rt, parents, EmptyScope)) - // case ClassInfoType(parents, decls, clazz) if !decls.isEmpty => - // mapOver(ClassInfoType(parents, EmptyScope, clazz)) - // case _ => - // mapOver(tp) - // } - // } + object dropAllRefinements extends TypeMap { + def apply(tp: Type): Type = tp match { + case rt @ RefinedType(parents, decls) if !decls.isEmpty => + mapOver(copyRefinedType(rt, parents, EmptyScope)) + case ClassInfoType(parents, decls, clazz) if !decls.isEmpty => + mapOver(ClassInfoType(parents, EmptyScope, clazz)) + case _ => + mapOver(tp) + } + } /** Type with all top-level occurrences of abstract types replaced by their bounds */ def abstractTypesToBounds(tp: Type): Type = tp match { // @M don't normalize here (compiler loops on pos/bug1090.scala ) @@ -4855,14 +4855,14 @@ trait Types extends api.Types { self: SymbolTable => } } - // object StripAnnotationsMap extends TypeMap { - // def apply(tp: Type): Type = tp match { - // case AnnotatedType(_, atp, _) => - // mapOver(atp) - // case tp => - // mapOver(tp) - // } - // } + object StripAnnotationsMap extends TypeMap { + def apply(tp: Type): Type = tp match { + case AnnotatedType(_, atp, _) => + mapOver(atp) + case tp => + mapOver(tp) + } + } /** A map to convert every occurrence of a wildcard type to a fresh * type variable */ @@ -4925,7 +4925,7 @@ trait Types extends api.Types { self: SymbolTable => /** A map to implement the `filter` method. */ class FilterTypeCollector(p: Type => Boolean) extends TypeCollector[List[Type]](Nil) { - // def withFilter(q: Type => Boolean) = new FilterTypeCollector(tp => p(tp) && q(tp)) + def withFilter(q: Type => Boolean) = new FilterTypeCollector(tp => p(tp) && q(tp)) override def collect(tp: Type) = super.collect(tp).reverse @@ -5868,7 +5868,7 @@ trait Types extends api.Types { self: SymbolTable => * useful as documentation; it is likely that !isNonValueType(tp) * will serve better than isValueType(tp). */ - // def isValueType(tp: Type) = isValueElseNonValue(tp) + def isValueType(tp: Type) = isValueElseNonValue(tp) /** SLS 3.3, Non-Value Types * Is the given type definitely a non-value type, as defined in SLS 3.3? @@ -5879,7 +5879,7 @@ trait Types extends api.Types { self: SymbolTable => * not designated non-value types because there is code which depends on using * them as type arguments, but their precise status is unclear. */ - // def isNonValueType(tp: Type) = !isValueElseNonValue(tp) + def isNonValueType(tp: Type) = !isValueElseNonValue(tp) def isNonRefinementClassType(tpe: Type) = tpe match { case SingleType(_, sym) => sym.isModuleClass @@ -5928,7 +5928,7 @@ trait Types extends api.Types { self: SymbolTable => corresponds3(tps1, tps2, tparams map (_.variance))(isSubArg) } - // def differentOrNone(tp1: Type, tp2: Type) = if (tp1 eq tp2) NoType else tp1 + def differentOrNone(tp1: Type, tp2: Type) = if (tp1 eq tp2) NoType else tp1 /** Does type `tp1` conform to `tp2`? */ private def isSubType2(tp1: Type, tp2: Type, depth: Int): Boolean = { @@ -6136,14 +6136,14 @@ trait Types extends api.Types { self: SymbolTable => /** Are `tps1` and `tps2` lists of equal length such that all elements * of `tps1` conform to corresponding elements of `tps2`? */ - // def isSubTypes(tps1: List[Type], tps2: List[Type]): Boolean = (tps1 corresponds tps2)(_ <:< _) + def isSubTypes(tps1: List[Type], tps2: List[Type]): Boolean = (tps1 corresponds tps2)(_ <:< _) /** Does type `tp` implement symbol `sym` with same or * stronger type? Exact only if `sym` is a member of some * refinement type, otherwise we might return false negatives. */ - // def specializesSym(tp: Type, sym: Symbol): Boolean = - // specializesSym(tp, sym, AnyDepth) + def specializesSym(tp: Type, sym: Symbol): Boolean = + specializesSym(tp, sym, AnyDepth) def specializesSym(tp: Type, sym: Symbol, depth: Int): Boolean = tp.typeSymbol == NothingClass || @@ -6586,10 +6586,10 @@ trait Types extends api.Types { self: SymbolTable => case _ => t } - // def elimRefinement(t: Type) = t match { - // case RefinedType(parents, decls) if !decls.isEmpty => intersectionType(parents) - // case _ => t - // } + def elimRefinement(t: Type) = t match { + case RefinedType(parents, decls) if !decls.isEmpty => intersectionType(parents) + case _ => t + } /** Eliminate from list of types all elements which are a subtype * of some other element of the list. */ @@ -6634,15 +6634,15 @@ trait Types extends api.Types { self: SymbolTable => (annotationsLub(lub(ts map (_.withoutAnnotations)), ts), true) else (lub(ts), false) - // def weakGlb(ts: List[Type]) = { - // if (ts.nonEmpty && (ts forall isNumericValueType)) { - // val nglb = numericGlb(ts) - // if (nglb != NoType) (nglb, true) - // else (glb(ts), false) - // } else if (ts exists typeHasAnnotations) { - // (annotationsGlb(glb(ts map (_.withoutAnnotations)), ts), true) - // } else (glb(ts), false) - // } + def weakGlb(ts: List[Type]) = { + if (ts.nonEmpty && (ts forall isNumericValueType)) { + val nglb = numericGlb(ts) + if (nglb != NoType) (nglb, true) + else (glb(ts), false) + } else if (ts exists typeHasAnnotations) { + (annotationsGlb(glb(ts map (_.withoutAnnotations)), ts), true) + } else (glb(ts), false) + } def numericLub(ts: List[Type]) = ts reduceLeft ((t1, t2) => @@ -6650,11 +6650,11 @@ trait Types extends api.Types { self: SymbolTable => else if (isNumericSubType(t2, t1)) t1 else IntClass.tpe) - // def numericGlb(ts: List[Type]) = - // ts reduceLeft ((t1, t2) => - // if (isNumericSubType(t1, t2)) t1 - // else if (isNumericSubType(t2, t1)) t2 - // else NoType) + def numericGlb(ts: List[Type]) = + ts reduceLeft ((t1, t2) => + if (isNumericSubType(t1, t2)) t1 + else if (isNumericSubType(t2, t1)) t2 + else NoType) def isWeakSubType(tp1: Type, tp2: Type) = tp1.deconst.normalize match { @@ -7017,8 +7017,8 @@ trait Types extends api.Types { self: SymbolTable => // Without this, the matchesType call would lead to type variables on both // sides of a subtyping/equality judgement, which can lead to recursive types // being constructed. See pos/t0851 for a situation where this happens. - // def suspendingTypeVarsInType[T](tp: Type)(op: => T): T = - // suspendingTypeVars(typeVarsInType(tp))(op) + def suspendingTypeVarsInType[T](tp: Type)(op: => T): T = + suspendingTypeVars(typeVarsInType(tp))(op) @inline final def suspendingTypeVars[T](tvs: List[TypeVar])(op: => T): T = { val saved = tvs map (_.suspended) @@ -7257,7 +7257,7 @@ trait Types extends api.Types { self: SymbolTable => /** Members which can be imported into other scopes. */ - // def importableMembers(clazz: Symbol): Scope = importableMembers(clazz.info) + def importableMembers(clazz: Symbol): Scope = importableMembers(clazz.info) def importableMembers(pre: Type): Scope = pre.members filter isImportable def objToAny(tp: Type): Type = @@ -7353,7 +7353,7 @@ trait Types extends api.Types { self: SymbolTable => object TypesStats { import BaseTypeSeqsStats._ val rawTypeCount = Statistics.newCounter ("#raw type creations") - // val asSeenFromCount = Statistics.newCounter ("#asSeenFrom ops") + val asSeenFromCount = Statistics.newCounter ("#asSeenFrom ops") val subtypeCount = Statistics.newCounter ("#subtype ops") val sametypeCount = Statistics.newCounter ("#sametype ops") val lubCount = Statistics.newCounter ("#toplevel lubs/glbs") diff --git a/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala b/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala index 4dfeb913ce..6170fcbb90 100644 --- a/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala +++ b/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala @@ -95,7 +95,7 @@ class PickleBuffer(data: Array[Byte], from: Int, to: Int) { // -- Basic input routines -------------------------------------------- /** Peek at the current byte without moving the read index */ - // def peekByte(): Int = bytes(readIndex) + def peekByte(): Int = bytes(readIndex) /** Read a byte */ def readByte(): Int = { diff --git a/src/reflect/scala/reflect/internal/pickling/PickleFormat.scala b/src/reflect/scala/reflect/internal/pickling/PickleFormat.scala index 1f522e8ee3..94b2f77ff9 100644 --- a/src/reflect/scala/reflect/internal/pickling/PickleFormat.scala +++ b/src/reflect/scala/reflect/internal/pickling/PickleFormat.scala @@ -115,7 +115,7 @@ object PickleFormat { */ val MajorVersion = 5 val MinorVersion = 0 - // def VersionString = "V" + MajorVersion + "." + MinorVersion + def VersionString = "V" + MajorVersion + "." + MinorVersion final val TERMname = 1 final val TYPEname = 2 diff --git a/src/reflect/scala/reflect/internal/pickling/UnPickler.scala b/src/reflect/scala/reflect/internal/pickling/UnPickler.scala index 76a4af850c..c82546b552 100644 --- a/src/reflect/scala/reflect/internal/pickling/UnPickler.scala +++ b/src/reflect/scala/reflect/internal/pickling/UnPickler.scala @@ -186,8 +186,8 @@ abstract class UnPickler /*extends scala.reflect.generic.UnPickler*/ { case _ => errorBadSignature("bad name tag: " + tag) } } - // protected def readTermName(): TermName = readName().toTermName - // protected def readTypeName(): TypeName = readName().toTypeName + protected def readTermName(): TermName = readName().toTermName + protected def readTypeName(): TypeName = readName().toTypeName private def readEnd() = readNat() + readIndex /** Read a symbol */ @@ -793,7 +793,7 @@ abstract class UnPickler /*extends scala.reflect.generic.UnPickler*/ { protected def readTreeRef(): Tree = at(readNat(), readTree) protected def readTypeNameRef(): TypeName = readNameRef().toTypeName - // protected def readTermNameRef(): TermName = readNameRef().toTermName + protected def readTermNameRef(): TermName = readNameRef().toTermName protected def readTemplateRef(): Template = readTreeRef() match { @@ -829,10 +829,10 @@ abstract class UnPickler /*extends scala.reflect.generic.UnPickler*/ { protected def errorBadSignature(msg: String) = throw new RuntimeException("malformed Scala signature of " + classRoot.name + " at " + readIndex + "; " + msg) - // protected def errorMissingRequirement(name: Name, owner: Symbol): Symbol = - // mirrorThatLoaded(owner).missingHook(owner, name) orElse MissingRequirementError.signal( - // s"bad reference while unpickling $filename: ${name.longString} not found in ${owner.tpe.widen}" - // ) + protected def errorMissingRequirement(name: Name, owner: Symbol): Symbol = + mirrorThatLoaded(owner).missingHook(owner, name) orElse MissingRequirementError.signal( + s"bad reference while unpickling $filename: ${name.longString} not found in ${owner.tpe.widen}" + ) def inferMethodAlternative(fun: Tree, argtpes: List[Type], restpe: Type) {} // can't do it; need a compiler for that. diff --git a/src/reflect/scala/reflect/internal/util/Collections.scala b/src/reflect/scala/reflect/internal/util/Collections.scala index 8d2ac3565e..2ba15e0776 100644 --- a/src/reflect/scala/reflect/internal/util/Collections.scala +++ b/src/reflect/scala/reflect/internal/util/Collections.scala @@ -40,8 +40,8 @@ trait Collections { mforeach(xss)(x => if ((res eq null) && p(x)) res = Some(x)) if (res eq null) None else res } - // final def mfilter[A](xss: List[List[A]])(p: A => Boolean) = - // for (xs <- xss; x <- xs; if p(x)) yield x + final def mfilter[A](xss: List[List[A]])(p: A => Boolean) = + for (xs <- xss; x <- xs; if p(x)) yield x final def map2[A, B, C](xs1: List[A], xs2: List[B])(f: (A, B) => C): List[C] = { val lb = new ListBuffer[C] @@ -78,18 +78,18 @@ trait Collections { lb.toList } - // final def distinctBy[A, B](xs: List[A])(f: A => B): List[A] = { - // val buf = new ListBuffer[A] - // val seen = mutable.Set[B]() - // xs foreach { x => - // val y = f(x) - // if (!seen(y)) { - // buf += x - // seen += y - // } - // } - // buf.toList - // } + final def distinctBy[A, B](xs: List[A])(f: A => B): List[A] = { + val buf = new ListBuffer[A] + val seen = mutable.Set[B]() + xs foreach { x => + val y = f(x) + if (!seen(y)) { + buf += x + seen += y + } + } + buf.toList + } @tailrec final def flattensToEmpty(xss: Seq[Seq[_]]): Boolean = { xss.isEmpty || xss.head.isEmpty && flattensToEmpty(xss.tail) @@ -189,18 +189,18 @@ trait Collections { } false } - // final def forall2[A, B](xs1: List[A], xs2: List[B])(f: (A, B) => Boolean): Boolean = { - // var ys1 = xs1 - // var ys2 = xs2 - // while (!ys1.isEmpty && !ys2.isEmpty) { - // if (!f(ys1.head, ys2.head)) - // return false - - // ys1 = ys1.tail - // ys2 = ys2.tail - // } - // true - // } + final def forall2[A, B](xs1: List[A], xs2: List[B])(f: (A, B) => Boolean): Boolean = { + var ys1 = xs1 + var ys2 = xs2 + while (!ys1.isEmpty && !ys2.isEmpty) { + if (!f(ys1.head, ys2.head)) + return false + + ys1 = ys1.tail + ys2 = ys2.tail + } + true + } final def forall3[A, B, C](xs1: List[A], xs2: List[B], xs3: List[C])(f: (A, B, C) => Boolean): Boolean = { var ys1 = xs1 var ys2 = xs2 @@ -223,5 +223,5 @@ trait Collections { } } -// object Collections extends Collections { } +object Collections extends Collections { } diff --git a/src/reflect/scala/reflect/internal/util/HashSet.scala b/src/reflect/scala/reflect/internal/util/HashSet.scala index e580315285..4135f3c469 100644 --- a/src/reflect/scala/reflect/internal/util/HashSet.scala +++ b/src/reflect/scala/reflect/internal/util/HashSet.scala @@ -6,8 +6,8 @@ package scala.reflect.internal.util object HashSet { - // def apply[T >: Null <: AnyRef](): HashSet[T] = this(16) - // def apply[T >: Null <: AnyRef](label: String): HashSet[T] = this(label, 16) + def apply[T >: Null <: AnyRef](): HashSet[T] = this(16) + def apply[T >: Null <: AnyRef](label: String): HashSet[T] = this(label, 16) def apply[T >: Null <: AnyRef](initialCapacity: Int): HashSet[T] = this("No Label", initialCapacity) def apply[T >: Null <: AnyRef](label: String, initialCapacity: Int): HashSet[T] = new HashSet[T](label, initialCapacity) diff --git a/src/reflect/scala/reflect/internal/util/Origins.scala b/src/reflect/scala/reflect/internal/util/Origins.scala index a2b9e24ebc..3259a12163 100644 --- a/src/reflect/scala/reflect/internal/util/Origins.scala +++ b/src/reflect/scala/reflect/internal/util/Origins.scala @@ -6,7 +6,9 @@ package scala.reflect package internal.util +import NameTransformer._ import scala.collection.{ mutable, immutable } +import Origins._ /** A debugging class for logging from whence a method is being called. * Say you wanted to discover who was calling phase_= in SymbolTable. diff --git a/src/reflect/scala/reflect/internal/util/Position.scala b/src/reflect/scala/reflect/internal/util/Position.scala index bbc95feaab..0725e9775b 100644 --- a/src/reflect/scala/reflect/internal/util/Position.scala +++ b/src/reflect/scala/reflect/internal/util/Position.scala @@ -128,7 +128,7 @@ abstract class Position extends scala.reflect.api.Position { self => def endOrPoint: Int = point @deprecated("use point instead", "2.9.0") - def offset: Option[Int] = if (isDefined) Some(point) else None // used by sbt + def offset: Option[Int] = if (isDefined) Some(point) else None /** The same position with a different start value (if a range) */ def withStart(off: Int): Position = this diff --git a/src/reflect/scala/reflect/internal/util/SourceFile.scala b/src/reflect/scala/reflect/internal/util/SourceFile.scala index 4d10372662..bc2d0ee4db 100644 --- a/src/reflect/scala/reflect/internal/util/SourceFile.scala +++ b/src/reflect/scala/reflect/internal/util/SourceFile.scala @@ -24,7 +24,7 @@ abstract class SourceFile { assert(offset < length, file + ": " + offset + " >= " + length) new OffsetPosition(this, offset) } - // def position(line: Int, column: Int) : Position = new OffsetPosition(this, lineToOffset(line) + column) + def position(line: Int, column: Int) : Position = new OffsetPosition(this, lineToOffset(line) + column) def offsetToLine(offset: Int): Int def lineToOffset(index : Int): Int @@ -37,8 +37,8 @@ abstract class SourceFile { def dbg(offset: Int) = (new OffsetPosition(this, offset)).dbgString def path = file.path - // def beginsWith(offset: Int, text: String): Boolean = - // (content drop offset) startsWith text + def beginsWith(offset: Int, text: String): Boolean = + (content drop offset) startsWith text def lineToString(index: Int): String = content drop lineToOffset(index) takeWhile (c => !isLineBreakChar(c.toChar)) mkString "" @@ -81,7 +81,7 @@ object ScriptSourceFile { } else 0 } - // def stripHeader(cs: Array[Char]): Array[Char] = cs drop headerLength(cs) + def stripHeader(cs: Array[Char]): Array[Char] = cs drop headerLength(cs) def apply(file: AbstractFile, content: Array[Char]) = { val underlying = new BatchSourceFile(file, content) @@ -91,6 +91,7 @@ object ScriptSourceFile { stripped } } +import ScriptSourceFile._ class ScriptSourceFile(underlying: BatchSourceFile, content: Array[Char], override val start: Int) extends BatchSourceFile(underlying.file, content) { override def isSelfContained = false diff --git a/src/reflect/scala/reflect/internal/util/StringOps.scala b/src/reflect/scala/reflect/internal/util/StringOps.scala index 3e8de65869..bc02ad1058 100644 --- a/src/reflect/scala/reflect/internal/util/StringOps.scala +++ b/src/reflect/scala/reflect/internal/util/StringOps.scala @@ -16,24 +16,24 @@ package scala.reflect.internal.util * @version 1.0 */ trait StringOps { - // def onull(s: String) = if (s == null) "" else s - def oempty(xs: String*) = xs filterNot (x => x == null || x == "") - def ojoin(xs: String*): String = oempty(xs: _*) mkString " " - // def ojoin(xs: Seq[String], sep: String): String = oempty(xs: _*) mkString sep - // def ojoinOr(xs: Seq[String], sep: String, orElse: String) = { - // val ys = oempty(xs: _*) - // if (ys.isEmpty) orElse else ys mkString sep - // } - // def trimTrailingSpace(s: String) = { - // if (s.length == 0 || !s.charAt(s.length - 1).isWhitespace) s - // else { - // var idx = s.length - 1 - // while (idx >= 0 && s.charAt(idx).isWhitespace) - // idx -= 1 + def onull(s: String) = if (s == null) "" else s + def oempty(xs: String*) = xs filterNot (x => x == null || x == "") + def ojoin(xs: String*): String = oempty(xs: _*) mkString " " + def ojoin(xs: Seq[String], sep: String): String = oempty(xs: _*) mkString sep + def ojoinOr(xs: Seq[String], sep: String, orElse: String) = { + val ys = oempty(xs: _*) + if (ys.isEmpty) orElse else ys mkString sep + } + def trimTrailingSpace(s: String) = { + if (s.length == 0 || !s.charAt(s.length - 1).isWhitespace) s + else { + var idx = s.length - 1 + while (idx >= 0 && s.charAt(idx).isWhitespace) + idx -= 1 - // s.substring(0, idx + 1) - // } - // } + s.substring(0, idx + 1) + } + } def longestCommonPrefix(xs: List[String]): String = { if (xs.isEmpty || xs.contains("")) "" else xs.head.head match { @@ -57,13 +57,13 @@ trait StringOps { def words(str: String): List[String] = decompose(str, ' ') - // def stripPrefixOpt(str: String, prefix: String): Option[String] = - // if (str startsWith prefix) Some(str drop prefix.length) - // else None + def stripPrefixOpt(str: String, prefix: String): Option[String] = + if (str startsWith prefix) Some(str drop prefix.length) + else None - // def stripSuffixOpt(str: String, suffix: String): Option[String] = - // if (str endsWith suffix) Some(str dropRight suffix.length) - // else None + def stripSuffixOpt(str: String, suffix: String): Option[String] = + if (str endsWith suffix) Some(str dropRight suffix.length) + else None def splitWhere(str: String, f: Char => Boolean, doDropIndex: Boolean = false): Option[(String, String)] = splitAt(str, str indexWhere f, doDropIndex) diff --git a/src/reflect/scala/reflect/internal/util/TableDef.scala b/src/reflect/scala/reflect/internal/util/TableDef.scala index 8208097d5c..8e2bcc2ff7 100644 --- a/src/reflect/scala/reflect/internal/util/TableDef.scala +++ b/src/reflect/scala/reflect/internal/util/TableDef.scala @@ -67,11 +67,11 @@ class TableDef[T](_cols: Column[T]*) { override def toString = allToSeq mkString "\n" } - // def formatterFor(rows: Seq[T]): T => String = { - // val formatStr = new Table(rows).rowFormat + def formatterFor(rows: Seq[T]): T => String = { + val formatStr = new Table(rows).rowFormat - // x => formatStr.format(colApply(x) : _*) - // } + x => formatStr.format(colApply(x) : _*) + } def table(rows: Seq[T]) = new Table(rows) diff --git a/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala b/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala index abedda8737..7ea8a75417 100644 --- a/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala +++ b/src/reflect/scala/reflect/internal/util/TraceSymbolActivity.scala @@ -12,10 +12,12 @@ trait TraceSymbolActivity { if (enabled && global.isCompilerUniverse) scala.sys addShutdownHook showAllSymbols() + private type Set[T] = scala.collection.immutable.Set[T] + val allSymbols = mutable.Map[Int, Symbol]() val allChildren = mutable.Map[Int, List[Int]]() withDefaultValue Nil val prevOwners = mutable.Map[Int, List[(Int, Phase)]]() withDefaultValue Nil - // val symsCaused = mutable.Map[Int, Int]() withDefaultValue 0 + val symsCaused = mutable.Map[Int, Int]() withDefaultValue 0 val allTrees = mutable.Set[Tree]() def recordSymbolsInTree(tree: Tree) { diff --git a/src/reflect/scala/reflect/internal/util/WeakHashSet.scala b/src/reflect/scala/reflect/internal/util/WeakHashSet.scala index 41e74f80e9..9882aad5e5 100644 --- a/src/reflect/scala/reflect/internal/util/WeakHashSet.scala +++ b/src/reflect/scala/reflect/internal/util/WeakHashSet.scala @@ -1,6 +1,9 @@ package scala.reflect.internal.util import scala.collection.mutable +import scala.collection.mutable.ArrayBuffer +import scala.collection.mutable.Builder +import scala.collection.mutable.SetBuilder import scala.collection.generic.Clearable import scala.runtime.AbstractFunction1 diff --git a/src/reflect/scala/reflect/io/AbstractFile.scala b/src/reflect/scala/reflect/io/AbstractFile.scala index de37176cd5..15befb67f1 100644 --- a/src/reflect/scala/reflect/io/AbstractFile.scala +++ b/src/reflect/scala/reflect/io/AbstractFile.scala @@ -14,9 +14,9 @@ import scala.collection.mutable.ArrayBuffer /** * An abstraction over files for use in the reflection/compiler libraries. - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' - * + * * @author Philippe Altherr * @version 1.0, 23/03/2004 */ @@ -85,7 +85,7 @@ object AbstractFile { * all other cases, the class SourceFile is used, which honors * global.settings.encoding.value. *

- * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ abstract class AbstractFile extends Iterable[AbstractFile] { @@ -195,9 +195,9 @@ abstract class AbstractFile extends Iterable[AbstractFile] { * @param directory ... * @return ... */ - // def lookupPath(path: String, directory: Boolean): AbstractFile = { - // lookup((f, p, dir) => f.lookupName(p, dir), path, directory) - // } + def lookupPath(path: String, directory: Boolean): AbstractFile = { + lookup((f, p, dir) => f.lookupName(p, dir), path, directory) + } /** Return an abstract file that does not check that `path` denotes * an existing file. diff --git a/src/reflect/scala/reflect/io/Directory.scala b/src/reflect/scala/reflect/io/Directory.scala index 3a21509457..c040d1eac5 100644 --- a/src/reflect/scala/reflect/io/Directory.scala +++ b/src/reflect/scala/reflect/io/Directory.scala @@ -14,12 +14,12 @@ import java.io.{ File => JFile } * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ object Directory { - import scala.util.Properties.{ userHome, userDir } + import scala.util.Properties.{ tmpDir, userHome, userDir } private def normalizePath(s: String) = Some(apply(Path(s).normalize)) def Current: Option[Directory] = if (userDir == "") None else normalizePath(userDir) - // def Home: Option[Directory] = if (userHome == "") None else normalizePath(userHome) - // def TmpDir: Option[Directory] = if (tmpDir == "") None else normalizePath(tmpDir) + def Home: Option[Directory] = if (userHome == "") None else normalizePath(userHome) + def TmpDir: Option[Directory] = if (tmpDir == "") None else normalizePath(tmpDir) def apply(path: Path): Directory = path.toDirectory @@ -30,19 +30,20 @@ object Directory { path.createDirectory() } } +import Path._ /** An abstraction for directories. * * @author Paul Phillips * @since 2.8 - * + * * ''Note: This is library is considered experimental and should not be used unless you know what you are doing.'' */ class Directory(jfile: JFile) extends Path(jfile) { override def toAbsolute: Directory = if (isAbsolute) this else super.toAbsolute.toDirectory override def toDirectory: Directory = this override def toFile: File = new File(jfile) - // override def isValid = jfile.isDirectory() || !jfile.exists() + override def isValid = jfile.isDirectory() || !jfile.exists() override def normalize: Directory = super.normalize.toDirectory /** An iterator over the contents of this directory. @@ -59,7 +60,7 @@ class Directory(jfile: JFile) extends Path(jfile) { override def walkFilter(cond: Path => Boolean): Iterator[Path] = list filter cond flatMap (_ walkFilter cond) - // def deepDirs: Iterator[Directory] = Path.onlyDirs(deepList()) + def deepDirs: Iterator[Directory] = Path.onlyDirs(deepList()) def deepFiles: Iterator[File] = Path.onlyFiles(deepList()) /** If optional depth argument is not given, will recurse @@ -73,6 +74,6 @@ class Directory(jfile: JFile) extends Path(jfile) { /** An iterator over the directories underneath this directory, * to the (optionally) given depth. */ - // def subdirs(depth: Int = 1): Iterator[Directory] = - // deepList(depth) collect { case x: Directory => x } + def subdirs(depth: Int = 1): Iterator[Directory] = + deepList(depth) collect { case x: Directory => x } } diff --git a/src/reflect/scala/reflect/io/File.scala b/src/reflect/scala/reflect/io/File.scala index 04e122af67..736ba5d51e 100644 --- a/src/reflect/scala/reflect/io/File.scala +++ b/src/reflect/scala/reflect/io/File.scala @@ -35,12 +35,12 @@ object File { type HasClose = { def close(): Unit } - // def closeQuietly(target: HasClose) { - // try target.close() catch { case e: IOException => } - // } - // def closeQuietly(target: JCloseable) { - // try target.close() catch { case e: IOException => } - // } + def closeQuietly(target: HasClose) { + try target.close() catch { case e: IOException => } + } + def closeQuietly(target: JCloseable) { + try target.close() catch { case e: IOException => } + } // this is a workaround for http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6503430 // we are using a static initializer to statically initialize a java class so we don't @@ -65,8 +65,8 @@ object File { // case _: IllegalArgumentException | _: IllegalStateException | _: IOException | _: SecurityException => () // } } -// import File._ -// import Path._ +import File._ +import Path._ /** An abstraction for files. For character data, a Codec * can be supplied at either creation time or when a method @@ -76,19 +76,19 @@ object File { * * @author Paul Phillips * @since 2.8 - * + * * ''Note: This is library is considered experimental and should not be used unless you know what you are doing.'' */ class File(jfile: JFile)(implicit constructorCodec: Codec) extends Path(jfile) with Streamable.Chars { override val creationCodec = constructorCodec - // def withCodec(codec: Codec): File = new File(jfile)(codec) + def withCodec(codec: Codec): File = new File(jfile)(codec) override def addExtension(ext: String): File = super.addExtension(ext).toFile override def toAbsolute: File = if (isAbsolute) this else super.toAbsolute.toFile override def toDirectory: Directory = new Directory(jfile) override def toFile: File = this override def normalize: File = super.normalize.toFile - // override def isValid = jfile.isFile() || !jfile.exists() + override def isValid = jfile.isFile() || !jfile.exists() override def length = super[Path].length override def walkFilter(cond: Path => Boolean): Iterator[Path] = if (cond(this)) Iterator.single(this) else Iterator.empty @@ -99,14 +99,14 @@ class File(jfile: JFile)(implicit constructorCodec: Codec) extends Path(jfile) w /** Obtains a OutputStream. */ def outputStream(append: Boolean = false) = new FileOutputStream(jfile, append) def bufferedOutput(append: Boolean = false) = new BufferedOutputStream(outputStream(append)) - // def printStream(append: Boolean = false) = new PrintStream(outputStream(append), true) + def printStream(append: Boolean = false) = new PrintStream(outputStream(append), true) /** Obtains an OutputStreamWriter wrapped around a FileOutputStream. * This should behave like a less broken version of java.io.FileWriter, * in that unlike the java version you can specify the encoding. */ - // def writer(): OutputStreamWriter = writer(false) - // def writer(append: Boolean): OutputStreamWriter = writer(append, creationCodec) + def writer(): OutputStreamWriter = writer(false) + def writer(append: Boolean): OutputStreamWriter = writer(append, creationCodec) def writer(append: Boolean, codec: Codec): OutputStreamWriter = new OutputStreamWriter(outputStream(append), codec.charSet) @@ -118,7 +118,7 @@ class File(jfile: JFile)(implicit constructorCodec: Codec) extends Path(jfile) w new BufferedWriter(writer(append, codec)) def printWriter(): PrintWriter = new PrintWriter(bufferedWriter(), true) - // def printWriter(append: Boolean): PrintWriter = new PrintWriter(bufferedWriter(append), true) + def printWriter(append: Boolean): PrintWriter = new PrintWriter(bufferedWriter(append), true) /** Creates a new file and writes all the Strings to it. */ def writeAll(strings: String*): Unit = { @@ -127,11 +127,11 @@ class File(jfile: JFile)(implicit constructorCodec: Codec) extends Path(jfile) w finally out.close() } - // def writeBytes(bytes: Array[Byte]): Unit = { - // val out = bufferedOutput() - // try out write bytes - // finally out.close() - // } + def writeBytes(bytes: Array[Byte]): Unit = { + val out = bufferedOutput() + try out write bytes + finally out.close() + } def appendAll(strings: String*): Unit = { val out = bufferedWriter(append = true) @@ -150,38 +150,38 @@ class File(jfile: JFile)(implicit constructorCodec: Codec) extends Path(jfile) w try Some(slurp()) catch { case _: IOException => None } - // def copyTo(destPath: Path, preserveFileDate: Boolean = false): Boolean = { - // val CHUNK = 1024 * 1024 * 16 // 16 MB - // val dest = destPath.toFile - // if (!isValid) fail("Source %s is not a valid file." format name) - // if (this.normalize == dest.normalize) fail("Source and destination are the same.") - // if (!dest.parent.exists) fail("Destination cannot be created.") - // if (dest.exists && !dest.canWrite) fail("Destination exists but is not writable.") - // if (dest.isDirectory) fail("Destination exists but is a directory.") - - // lazy val in_s = inputStream() - // lazy val out_s = dest.outputStream() - // lazy val in = in_s.getChannel() - // lazy val out = out_s.getChannel() - - // try { - // val size = in.size() - // var pos, count = 0L - // while (pos < size) { - // count = (size - pos) min CHUNK - // pos += out.transferFrom(in, pos, count) - // } - // } - // finally List[HasClose](out, out_s, in, in_s) foreach closeQuietly - - // if (this.length != dest.length) - // fail("Failed to completely copy %s to %s".format(name, dest.name)) - - // if (preserveFileDate) - // dest.lastModified = this.lastModified - - // true - // } + def copyTo(destPath: Path, preserveFileDate: Boolean = false): Boolean = { + val CHUNK = 1024 * 1024 * 16 // 16 MB + val dest = destPath.toFile + if (!isValid) fail("Source %s is not a valid file." format name) + if (this.normalize == dest.normalize) fail("Source and destination are the same.") + if (!dest.parent.exists) fail("Destination cannot be created.") + if (dest.exists && !dest.canWrite) fail("Destination exists but is not writable.") + if (dest.isDirectory) fail("Destination exists but is a directory.") + + lazy val in_s = inputStream() + lazy val out_s = dest.outputStream() + lazy val in = in_s.getChannel() + lazy val out = out_s.getChannel() + + try { + val size = in.size() + var pos, count = 0L + while (pos < size) { + count = (size - pos) min CHUNK + pos += out.transferFrom(in, pos, count) + } + } + finally List[HasClose](out, out_s, in, in_s) foreach closeQuietly + + if (this.length != dest.length) + fail("Failed to completely copy %s to %s".format(name, dest.name)) + + if (preserveFileDate) + dest.lastModified = this.lastModified + + true + } /** Reflection since we're into the java 6+ API. */ diff --git a/src/reflect/scala/reflect/io/Path.scala b/src/reflect/scala/reflect/io/Path.scala index 77b5065db1..36fdc04db4 100644 --- a/src/reflect/scala/reflect/io/Path.scala +++ b/src/reflect/scala/reflect/io/Path.scala @@ -27,7 +27,7 @@ import scala.language.implicitConversions * * @author Paul Phillips * @since 2.8 - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ object Path { @@ -65,11 +65,11 @@ object Path { def onlyDirs(xs: Iterator[Path]): Iterator[Directory] = xs filter (_.isDirectory) map (_.toDirectory) def onlyDirs(xs: List[Path]): List[Directory] = xs filter (_.isDirectory) map (_.toDirectory) def onlyFiles(xs: Iterator[Path]): Iterator[File] = xs filter (_.isFile) map (_.toFile) - // def onlyFiles(xs: List[Path]): List[File] = xs filter (_.isFile) map (_.toFile) + def onlyFiles(xs: List[Path]): List[File] = xs filter (_.isFile) map (_.toFile) def roots: List[Path] = java.io.File.listRoots().toList map Path.apply - // def apply(segments: Seq[String]): Path = apply(segments mkString java.io.File.separator) + def apply(segments: Seq[String]): Path = apply(segments mkString java.io.File.separator) def apply(path: String): Path = apply(new JFile(path)) def apply(jfile: JFile): Path = if (jfile.isFile) new File(jfile) @@ -84,7 +84,7 @@ import Path._ /** The Path constructor is private so we can enforce some * semantics regarding how a Path might relate to the world. - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ class Path private[io] (val jfile: JFile) { @@ -95,7 +95,7 @@ class Path private[io] (val jfile: JFile) { // contents of the filesystem are in agreement. All objects are // valid except File objects whose path points to a directory and // Directory objects whose path points to a file. - // def isValid: Boolean = true + def isValid: Boolean = true // conversions def toFile: File = new File(jfile) @@ -136,7 +136,7 @@ class Path private[io] (val jfile: JFile) { def name: String = jfile.getName() def path: String = jfile.getPath() def normalize: Path = Path(jfile.getAbsolutePath()) - // def isRootPath: Boolean = roots exists (_ isSame this) + def isRootPath: Boolean = roots exists (_ isSame this) def resolve(other: Path) = if (other.isAbsolute || isEmpty) other else /(other) def relativize(other: Path) = { @@ -153,7 +153,7 @@ class Path private[io] (val jfile: JFile) { } // derived from identity - // def root: Option[Path] = roots find (this startsWith _) + def root: Option[Path] = roots find (this startsWith _) def segments: List[String] = (path split separator).toList filterNot (_.length == 0) /** * @return The path of the parent directory, or root if path is already root @@ -213,22 +213,22 @@ class Path private[io] (val jfile: JFile) { def canRead = jfile.canRead() def canWrite = jfile.canWrite() def exists = jfile.exists() - // def notExists = try !jfile.exists() catch { case ex: SecurityException => false } + def notExists = try !jfile.exists() catch { case ex: SecurityException => false } def isFile = jfile.isFile() def isDirectory = jfile.isDirectory() def isAbsolute = jfile.isAbsolute() - // def isHidden = jfile.isHidden() + def isHidden = jfile.isHidden() def isEmpty = path.length == 0 // Information def lastModified = jfile.lastModified() - // def lastModified_=(time: Long) = jfile setLastModified time // should use setXXX function? + def lastModified_=(time: Long) = jfile setLastModified time // should use setXXX function? def length = jfile.length() // Boolean path comparisons def endsWith(other: Path) = segments endsWith other.segments - // def startsWith(other: Path) = segments startsWith other.segments + def startsWith(other: Path) = segments startsWith other.segments def isSame(other: Path) = toCanonical == other.toCanonical def isFresher(other: Path) = lastModified > other.lastModified @@ -248,7 +248,7 @@ class Path private[io] (val jfile: JFile) { // deletions def delete() = jfile.delete() - // def deleteIfExists() = if (jfile.exists()) delete() else false + def deleteIfExists() = if (jfile.exists()) delete() else false /** Deletes the path recursively. Returns false on failure. * Use with caution! @@ -270,11 +270,11 @@ class Path private[io] (val jfile: JFile) { length == 0 } - // def touch(modTime: Long = System.currentTimeMillis) = { - // createFile() - // if (isFile) - // lastModified = modTime - // } + def touch(modTime: Long = System.currentTimeMillis) = { + createFile() + if (isFile) + lastModified = modTime + } // todo // def copyTo(target: Path, options ...): Boolean diff --git a/src/reflect/scala/reflect/io/PlainFile.scala b/src/reflect/scala/reflect/io/PlainFile.scala index 6ee51d3d37..82b0568657 100644 --- a/src/reflect/scala/reflect/io/PlainFile.scala +++ b/src/reflect/scala/reflect/io/PlainFile.scala @@ -8,17 +8,17 @@ package scala.reflect package io import java.io.{ FileInputStream, FileOutputStream, IOException } - +import PartialFunction._ /** ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ object PlainFile { /** * If the specified File exists, returns an abstract file backed * by it. Otherwise, returns null. */ - // def fromPath(file: Path): PlainFile = - // if (file.isDirectory) new PlainDirectory(file.toDirectory) - // else if (file.isFile) new PlainFile(file) - // else null + def fromPath(file: Path): PlainFile = + if (file.isDirectory) new PlainDirectory(file.toDirectory) + else if (file.isFile) new PlainFile(file) + else null } /** ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ class PlainDirectory(givenPath: Directory) extends PlainFile(givenPath) { @@ -28,7 +28,7 @@ class PlainDirectory(givenPath: Directory) extends PlainFile(givenPath) { } /** This class implements an abstract file backed by a File. - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ class PlainFile(val givenPath: Path) extends AbstractFile { diff --git a/src/reflect/scala/reflect/io/Streamable.scala b/src/reflect/scala/reflect/io/Streamable.scala index 615f44acc5..61ec8a4c23 100644 --- a/src/reflect/scala/reflect/io/Streamable.scala +++ b/src/reflect/scala/reflect/io/Streamable.scala @@ -17,14 +17,14 @@ import Path.fail * * @author Paul Phillips * @since 2.8 - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ object Streamable { /** Traits which can be viewed as a sequence of bytes. Source types * which know their length should override def length: Long for more * efficient method implementations. - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ trait Bytes { @@ -69,7 +69,7 @@ object Streamable { } /** For objects which can be viewed as Chars. - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ trait Chars extends Bytes { @@ -81,7 +81,7 @@ object Streamable { */ def creationCodec: Codec = implicitly[Codec] - // def chars(): BufferedSource = chars(creationCodec) + def chars(): BufferedSource = chars(creationCodec) def chars(codec: Codec): BufferedSource = Source.fromInputStream(inputStream())(codec) def lines(): Iterator[String] = lines(creationCodec) @@ -89,7 +89,7 @@ object Streamable { /** Obtains an InputStreamReader wrapped around a FileInputStream. */ - // def reader(): InputStreamReader = reader(creationCodec) + def reader(): InputStreamReader = reader(creationCodec) def reader(codec: Codec): InputStreamReader = new InputStreamReader(inputStream, codec.charSet) /** Wraps a BufferedReader around the result of reader(). diff --git a/src/reflect/scala/reflect/io/VirtualDirectory.scala b/src/reflect/scala/reflect/io/VirtualDirectory.scala index 72ffff2aa9..78713c2ae0 100644 --- a/src/reflect/scala/reflect/io/VirtualDirectory.scala +++ b/src/reflect/scala/reflect/io/VirtualDirectory.scala @@ -11,7 +11,7 @@ import scala.collection.mutable * An in-memory directory. * * @author Lex Spoon - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ class VirtualDirectory(val name: String, maybeContainer: Option[VirtualDirectory]) @@ -26,8 +26,7 @@ extends AbstractFile { def container = maybeContainer.get def isDirectory = true - val lastModified: Long = System.currentTimeMillis - // var lastModified: Long = System.currentTimeMillis + var lastModified: Long = System.currentTimeMillis override def file = null override def input = sys.error("directories cannot be read") diff --git a/src/reflect/scala/reflect/io/VirtualFile.scala b/src/reflect/scala/reflect/io/VirtualFile.scala index 014e02c6cd..95f4429fad 100644 --- a/src/reflect/scala/reflect/io/VirtualFile.scala +++ b/src/reflect/scala/reflect/io/VirtualFile.scala @@ -14,7 +14,7 @@ import java.io.{ File => JFile } * * @author Philippe Altherr * @version 1.0, 23/03/2004 - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ class VirtualFile(val name: String, override val path: String) extends AbstractFile { @@ -65,7 +65,7 @@ class VirtualFile(val name: String, override val path: String) extends AbstractF /** Returns the time that this abstract file was last modified. */ private var _lastModified: Long = 0 def lastModified: Long = _lastModified - // def lastModified_=(x: Long) = _lastModified = x + def lastModified_=(x: Long) = _lastModified = x /** Returns all abstract subfiles of this abstract directory. */ def iterator: Iterator[AbstractFile] = { diff --git a/src/reflect/scala/reflect/io/ZipArchive.scala b/src/reflect/scala/reflect/io/ZipArchive.scala index 0e69834d26..3b57721e89 100644 --- a/src/reflect/scala/reflect/io/ZipArchive.scala +++ b/src/reflect/scala/reflect/io/ZipArchive.scala @@ -20,12 +20,12 @@ import scala.annotation.tailrec * @author Philippe Altherr (original version) * @author Paul Phillips (this one) * @version 2.0, - * + * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ object ZipArchive { - // def fromPath(path: String): FileZipArchive = fromFile(new JFile(path)) - // def fromPath(path: Path): FileZipArchive = fromFile(path.toFile) + def fromPath(path: String): FileZipArchive = fromFile(new JFile(path)) + def fromPath(path: Path): FileZipArchive = fromFile(path.toFile) /** * @param file a File @@ -41,7 +41,7 @@ object ZipArchive { * @return A ZipArchive backed by the given url. */ def fromURL(url: URL): URLZipArchive = new URLZipArchive(url) - // def fromURL(url: String): URLZipArchive = fromURL(new URL(url)) + def fromURL(url: String): URLZipArchive = fromURL(new URL(url)) private def dirName(path: String) = splitPath(path, true) private def baseName(path: String) = splitPath(path, false) @@ -79,7 +79,7 @@ abstract class ZipArchive(override val file: JFile) extends AbstractFile with Eq else Iterator(f) } } - // def deepIterator = walkIterator(iterator) + def deepIterator = walkIterator(iterator) /** ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' */ sealed abstract class Entry(path: String) extends VirtualFile(baseName(path), path) { // have to keep this name for compat with sbt's compiler-interface diff --git a/src/reflect/scala/reflect/macros/TreeBuilder.scala b/src/reflect/scala/reflect/macros/TreeBuilder.scala index fbbbe13201..204dc40858 100644 --- a/src/reflect/scala/reflect/macros/TreeBuilder.scala +++ b/src/reflect/scala/reflect/macros/TreeBuilder.scala @@ -11,6 +11,7 @@ abstract class TreeBuilder { val global: Universe import global._ + import definitions._ /** Builds a reference to value whose type is given stable prefix. * The type must be suitable for this. For example, it diff --git a/src/reflect/scala/reflect/runtime/JavaMirrors.scala b/src/reflect/scala/reflect/runtime/JavaMirrors.scala index 07599e095d..44fbd55162 100644 --- a/src/reflect/scala/reflect/runtime/JavaMirrors.scala +++ b/src/reflect/scala/reflect/runtime/JavaMirrors.scala @@ -22,6 +22,7 @@ import internal.Flags._ import ReflectionUtils.{staticSingletonInstance, innerSingletonInstance} import scala.language.existentials import scala.runtime.{ScalaRunTime, BoxesRunTime} +import scala.reflect.internal.util.Collections._ private[reflect] trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUniverse: SymbolTable => @@ -840,13 +841,13 @@ private[reflect] trait JavaMirrors extends internal.SymbolTable with api.JavaUni * @return A Scala field object that corresponds to `jfield`. * // ??? should we return the getter instead? */ - // def fieldToScala(jfield: jField): TermSymbol = - // toScala(fieldCache, jfield)(_ fieldToScala1 _) + def fieldToScala(jfield: jField): TermSymbol = + toScala(fieldCache, jfield)(_ fieldToScala1 _) - // private def fieldToScala1(jfield: jField): TermSymbol = { - // val owner = followStatic(classToScala(jfield.getDeclaringClass), jfield.getModifiers) - // (lookup(owner, jfield.getName) suchThat (!_.isMethod) orElse jfieldAsScala(jfield)).asTerm - // } + private def fieldToScala1(jfield: jField): TermSymbol = { + val owner = followStatic(classToScala(jfield.getDeclaringClass), jfield.getModifiers) + (lookup(owner, jfield.getName) suchThat (!_.isMethod) orElse jfieldAsScala(jfield)).asTerm + } /** * The Scala package corresponding to given Java package @@ -1114,9 +1115,9 @@ private[reflect] trait JavaMirrors extends internal.SymbolTable with api.JavaUni /** Optionally, the Java package corresponding to a given Scala package, or None if no such Java package exists. * @param pkg The Scala package */ - // def packageToJavaOption(pkg: ModuleSymbol): Option[jPackage] = packageCache.toJavaOption(pkg) { - // Option(jPackage.getPackage(pkg.fullName.toString)) - // } + def packageToJavaOption(pkg: ModuleSymbol): Option[jPackage] = packageCache.toJavaOption(pkg) { + Option(jPackage.getPackage(pkg.fullName.toString)) + } /** The Java class corresponding to given Scala class. * Note: This only works for diff --git a/src/reflect/scala/reflect/runtime/JavaUniverse.scala b/src/reflect/scala/reflect/runtime/JavaUniverse.scala index a12e7d43d4..0f70a676fa 100644 --- a/src/reflect/scala/reflect/runtime/JavaUniverse.scala +++ b/src/reflect/scala/reflect/runtime/JavaUniverse.scala @@ -1,6 +1,8 @@ package scala.reflect package runtime +import internal.{SomePhase, NoPhase, Phase, TreeGen} + /** An implementation of [[scala.reflect.api.Universe]] for runtime reflection using JVM classloaders. * * Should not be instantiated directly, use [[scala.reflect.runtime.universe]] instead. @@ -9,7 +11,7 @@ package runtime */ class JavaUniverse extends internal.SymbolTable with ReflectSetup with runtime.SymbolTable { self => - def picklerPhase = internal.SomePhase + def picklerPhase = SomePhase def forInteractive = false def forScaladoc = false @@ -24,3 +26,4 @@ class JavaUniverse extends internal.SymbolTable with ReflectSetup with runtime.S init() } + diff --git a/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala b/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala index b415abecb1..366b4319c3 100644 --- a/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala +++ b/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala @@ -83,8 +83,8 @@ private[reflect] trait SynchronizedSymbols extends internal.Symbols { self: Symb override protected def createPackageObjectClassSymbol(pos: Position, newFlags: Long): PackageObjectClassSymbol = new PackageObjectClassSymbol(this, pos) with SynchronizedClassSymbol initFlags newFlags - // override protected def createTermSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol = - // new TermSymbol(this, pos, name) with SynchronizedTermSymbol initFlags newFlags + override protected def createTermSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol = + new TermSymbol(this, pos, name) with SynchronizedTermSymbol initFlags newFlags override protected def createMethodSymbol(name: TermName, pos: Position, newFlags: Long): MethodSymbol = new MethodSymbol(this, pos, name) with SynchronizedMethodSymbol initFlags newFlags diff --git a/src/reflect/scala/reflect/runtime/package.scala b/src/reflect/scala/reflect/runtime/package.scala index eadbc0c52e..b97913daf0 100644 --- a/src/reflect/scala/reflect/runtime/package.scala +++ b/src/reflect/scala/reflect/runtime/package.scala @@ -6,7 +6,7 @@ package scala.reflect package object runtime { /** The entry point into Scala runtime reflection. - * + * * To use Scala runtime reflection, simply use or import `scala.reflect.runtime.universe._` * * See [[scala.reflect.api.Universe]] or the -- cgit v1.2.3 From f89394ee3b3f95d982382d6ee2c2b74af0c02113 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Tue, 13 Nov 2012 02:59:33 -0800 Subject: Removing ancient comments and pointless comments. Translating into backticks. Removed the "@param tree ..." blocks which have been taunting me for half a decade now. Removed commented-out blocks of code which had been sitting there for two years or more. --- src/compiler/scala/tools/nsc/PhaseAssembly.scala | 2 +- .../scala/tools/nsc/ast/parser/MarkupParsers.scala | 9 -- .../scala/tools/nsc/ast/parser/Parsers.scala | 2 +- .../tools/nsc/backend/WorklistAlgorithm.scala | 2 - .../tools/nsc/backend/icode/BasicBlocks.scala | 8 +- .../scala/tools/nsc/backend/icode/GenICode.scala | 24 +-- .../tools/nsc/backend/icode/ICodeCheckers.scala | 7 +- .../backend/icode/analysis/CopyPropagation.scala | 12 +- .../scala/tools/nsc/backend/jvm/GenJVM.scala | 8 - src/compiler/scala/tools/nsc/plugins/Plugin.scala | 2 +- .../tools/nsc/plugins/PluginDescription.scala | 2 +- .../tools/nsc/reporters/ConsoleReporter.scala | 8 - .../scala/tools/nsc/symtab/classfile/Pickler.scala | 2 - .../scala/tools/nsc/transform/ExplicitOuter.scala | 5 - src/compiler/scala/tools/nsc/transform/Mixin.scala | 12 +- .../scala/tools/nsc/transform/TailCalls.scala | 2 +- .../tools/nsc/typechecker/ConstantFolder.scala | 3 - .../scala/tools/nsc/typechecker/EtaExpansion.scala | 9 +- .../scala/tools/nsc/typechecker/Infer.scala | 31 ---- .../scala/tools/nsc/typechecker/Typers.scala | 168 +++------------------ .../scala/tools/nsc/typechecker/Variances.scala | 4 +- .../scala/collection/immutable/RedBlackTree.scala | 6 +- .../scala/concurrent/FutureTaskRunner.scala | 2 +- src/library/scala/xml/Elem.scala | 2 +- src/library/scala/xml/Node.scala | 10 +- src/reflect/scala/reflect/internal/Scopes.scala | 13 -- src/reflect/scala/reflect/internal/Symbols.scala | 7 +- src/reflect/scala/reflect/internal/Types.scala | 6 - .../reflect/internal/pickling/PickleBuffer.scala | 17 +-- .../reflect/internal/pickling/UnPickler.scala | 6 +- .../scala/reflect/internal/util/StringOps.scala | 7 - src/reflect/scala/reflect/io/AbstractFile.scala | 24 ++- src/reflect/scala/reflect/io/VirtualFile.scala | 11 -- 33 files changed, 77 insertions(+), 356 deletions(-) (limited to 'src/compiler/scala/tools') diff --git a/src/compiler/scala/tools/nsc/PhaseAssembly.scala b/src/compiler/scala/tools/nsc/PhaseAssembly.scala index bef81b6ff3..67dc1e3b66 100644 --- a/src/compiler/scala/tools/nsc/PhaseAssembly.scala +++ b/src/compiler/scala/tools/nsc/PhaseAssembly.scala @@ -182,7 +182,7 @@ trait PhaseAssembly { /** Remove all nodes in the given graph, that have no phase object * Make sure to clean up all edges when removing the node object - * Inform with warnings, if an external phase has a + * `Inform` with warnings, if an external phase has a * dependency on something that is dropped. */ def removeDanglingNodes() { diff --git a/src/compiler/scala/tools/nsc/ast/parser/MarkupParsers.scala b/src/compiler/scala/tools/nsc/ast/parser/MarkupParsers.scala index ab2afcb403..639780149e 100755 --- a/src/compiler/scala/tools/nsc/ast/parser/MarkupParsers.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/MarkupParsers.scala @@ -24,12 +24,6 @@ import scala.reflect.internal.Chars.{ SU, LF } // I rewrote most of these, but not as yet the library versions: so if you are // tempted to touch any of these, please be aware of that situation and try not // to let it get any worse. -- paulp - -/** This trait ... - * - * @author Burak Emir - * @version 1.0 - */ trait MarkupParsers { self: Parsers => @@ -216,9 +210,6 @@ trait MarkupParsers { /** Returns true if it encounters an end tag (without consuming it), * appends trees to ts as side-effect. - * - * @param ts ... - * @return ... */ private def content_LT(ts: ArrayBuffer[Tree]): Boolean = { if (ch == '/') diff --git a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala index efcde1f74f..c934f34398 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala @@ -94,7 +94,7 @@ trait ParsersCommon extends ScannersCommon { *
    *
  1. * Places all pattern variables in Bind nodes. In a pattern, for - * identifiers x:
    + *      identifiers `x`:
      *                 x  => x @ _
      *               x:T  => x @ (_ : T)
    *
  2. diff --git a/src/compiler/scala/tools/nsc/backend/WorklistAlgorithm.scala b/src/compiler/scala/tools/nsc/backend/WorklistAlgorithm.scala index 49dc105c79..45ca39fee4 100644 --- a/src/compiler/scala/tools/nsc/backend/WorklistAlgorithm.scala +++ b/src/compiler/scala/tools/nsc/backend/WorklistAlgorithm.scala @@ -31,8 +31,6 @@ trait WorklistAlgorithm { * Run the iterative algorithm until the worklist remains empty. * The initializer is run once before the loop starts and should * initialize the worklist. - * - * @param initWorklist ... */ def run(initWorklist: => Unit) = { initWorklist diff --git a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala index b62d5cb4e4..7c7777f761 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala @@ -122,7 +122,7 @@ trait BasicBlocks { def closed: Boolean = hasFlag(CLOSED) def closed_=(b: Boolean) = if (b) setFlag(CLOSED) else resetFlag(CLOSED) - /** When set, the emit methods will be ignored. */ + /** When set, the `emit` methods will be ignored. */ def ignore: Boolean = hasFlag(IGNORING) def ignore_=(b: Boolean) = if (b) setFlag(IGNORING) else resetFlag(IGNORING) @@ -260,7 +260,7 @@ trait BasicBlocks { } } - /** Replaces oldInstr with is. It does not update + /** Replaces `oldInstr` with `is`. It does not update * the position field in the newly inserted instructions, so it behaves * differently than the one-instruction versions of this function. * @@ -289,8 +289,6 @@ trait BasicBlocks { } /** Removes instructions found at the given positions. - * - * @param positions ... */ def removeInstructionsAt(positions: Int*) { assert(closed, this) @@ -311,8 +309,6 @@ trait BasicBlocks { } /** Replaces all instructions found in the map. - * - * @param map ... */ def subst(map: Map[Instruction, Instruction]): Unit = if (!closed) diff --git a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala index 720896d0b3..e2436d0e90 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala @@ -14,8 +14,7 @@ import scala.tools.nsc.symtab._ import scala.annotation.switch import PartialFunction._ -/** This class ... - * +/** * @author Iulian Dragos * @version 1.0 */ @@ -159,8 +158,6 @@ abstract class GenICode extends SubComponent { * and not produce any value. Use genLoad for expressions which leave * a value on top of the stack. * - * @param tree ... - * @param ctx ... * @return a new context. This is necessary for control flow instructions * which may change the current basic block. */ @@ -263,11 +260,6 @@ abstract class GenICode extends SubComponent { } /** Generate primitive array operations. - * - * @param tree ... - * @param ctx ... - * @param code ... - * @return ... */ private def genArrayOp(tree: Tree, ctx: Context, code: Int, expectedType: TypeKind): (Context, TypeKind) = { import scalaPrimitives._ @@ -1386,10 +1378,6 @@ abstract class GenICode extends SubComponent { // } /** Generate string concatenation. - * - * @param tree ... - * @param ctx ... - * @return ... */ def genStringConcat(tree: Tree, ctx: Context): Context = { liftStringConcat(tree) match { @@ -1703,8 +1691,6 @@ abstract class GenICode extends SubComponent { * If the block consists of a single unconditional jump, prune * it by replacing the instructions in the predecessor to jump * directly to the JUMP target of the block. - * - * @param method ... */ def prune(method: IMethod) = { var changed = false @@ -1968,10 +1954,6 @@ abstract class GenICode extends SubComponent { } /** Prepare a new context upon entry into a method. - * - * @param m ... - * @param d ... - * @return ... */ def enterMethod(m: IMethod, d: DefDef): Context = { val ctx1 = new Context(this) setMethod(m) @@ -2071,14 +2053,14 @@ abstract class GenICode extends SubComponent { * It returns the resulting context, with the same active handlers as * before the call. Use it like: * - * ctx.Try( ctx => { + * ` ctx.Try( ctx => { * ctx.bb.emit(...) // protected block * }, (ThrowableClass, * ctx => { * ctx.bb.emit(...); // exception handler * }), (AnotherExceptionClass, * ctx => {... - * } )) + * } ))` */ def Try(body: Context => Context, handlers: List[(Symbol, TypeKind, Context => Context)], diff --git a/src/compiler/scala/tools/nsc/backend/icode/ICodeCheckers.scala b/src/compiler/scala/tools/nsc/backend/icode/ICodeCheckers.scala index 221652723d..95913c7768 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/ICodeCheckers.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/ICodeCheckers.scala @@ -48,7 +48,7 @@ abstract class ICodeCheckers { * @author Iulian Dragos * @version 1.0, 06/09/2005 * - * @todo Better checks for MONITOR_ENTER/EXIT + * @todo Better checks for `MONITOR_ENTER/EXIT` * Better checks for local var initializations * * @todo Iulian says: I think there's some outdated logic in the checker. @@ -413,10 +413,7 @@ abstract class ICodeCheckers { } /** Checks that the object passed as receiver has a method - * method and that it is callable from the current method. - * - * @param receiver ... - * @param method ... + * `method` and that it is callable from the current method. */ def checkMethod(receiver: TypeKind, method: Symbol) = receiver match { 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 53111d0ade..4a5844531a 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala @@ -463,14 +463,9 @@ abstract class CopyPropagation { } } - /** Update the state s after the call to method. + /** Update the state `s` after the call to `method`. * The stack elements are dropped and replaced by the result of the call. * If the method is impure, all bindings to record fields are cleared. - * - * @param state ... - * @param method ... - * @param static ... - * @return ... */ final def simulateCall(state: copyLattice.State, method: Symbol, static: Boolean): copyLattice.State = { val out = new copyLattice.State(state.bindings, state.stack); @@ -554,10 +549,7 @@ abstract class CopyPropagation { bindings } - /** Is symbol m a pure method? - * - * @param m ... - * @return ... + /** Is symbol `m` a pure method? */ final def isPureMethod(m: Symbol): Boolean = m.isGetter // abstract getters are still pure, as we 'know' diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala index 06f94ef46c..31a4554d97 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala @@ -1153,9 +1153,6 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with var linearization: List[BasicBlock] = Nil var isModuleInitialized = false - /** - * @param m ... - */ def genCode(m: IMethod) { val jcode = jmethod.getCode.asInstanceOf[JExtendedCode] @@ -1605,11 +1602,6 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with } } - - /** - * @param primitive ... - * @param pos ... - */ def genPrimitive(primitive: Primitive, pos: Position) { primitive match { case Negation(kind) => diff --git a/src/compiler/scala/tools/nsc/plugins/Plugin.scala b/src/compiler/scala/tools/nsc/plugins/Plugin.scala index 6c64ea907f..093f8285e1 100644 --- a/src/compiler/scala/tools/nsc/plugins/Plugin.scala +++ b/src/compiler/scala/tools/nsc/plugins/Plugin.scala @@ -71,7 +71,7 @@ object Plugin { } /** Try to load a plugin description from the specified - * file, returning None if it does not work. + * file, returning `None` if it does not work. */ private def loadDescription(jarfile: Path): Option[PluginDescription] = // XXX Return to this once we have some ARM support diff --git a/src/compiler/scala/tools/nsc/plugins/PluginDescription.scala b/src/compiler/scala/tools/nsc/plugins/PluginDescription.scala index 9ecc098687..f77123ba11 100644 --- a/src/compiler/scala/tools/nsc/plugins/PluginDescription.scala +++ b/src/compiler/scala/tools/nsc/plugins/PluginDescription.scala @@ -26,7 +26,7 @@ abstract class PluginDescription { val classname: String /** An XML representation of this description. It can be - * read back using PluginDescription.fromXML. + * read back using `PluginDescription.fromXML`. * It should be stored inside the jar archive file. */ def toXML: Node = { diff --git a/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala b/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala index 245ac6adaa..bda195f9d3 100644 --- a/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala +++ b/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala @@ -34,9 +34,6 @@ class ConsoleReporter(val settings: Settings, reader: BufferedReader, writer: Pr } /** Returns the number of errors issued totally as a string. - * - * @param severity ... - * @return ... */ private def getCountString(severity: Severity): String = StringOps.countElementsAsString((severity).count, label(severity)) @@ -52,17 +49,12 @@ class ConsoleReporter(val settings: Settings, reader: BufferedReader, writer: Pr printMessage(pos, clabel(severity) + msg) } - /** - * @param pos ... - */ def printSourceLine(pos: Position) { printMessage(pos.lineContent.stripLineEnd) printColumnMarker(pos) } /** Prints the column marker of the given position. - * - * @param pos ... */ def printColumnMarker(pos: Position) = if (pos.isDefined) { printMessage(" " * (pos.column - 1) + "^") } diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala index 941604b154..9a8db447c3 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala @@ -149,8 +149,6 @@ abstract class Pickler extends SubComponent { } /** Store symbol in index. If symbol is local, also store everything it references. - * - * @param sym ... */ def putSymbol(sym: Symbol) { if (putEntry(sym)) { diff --git a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala index 13e7e17951..01c22245cb 100644 --- a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala +++ b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala @@ -234,11 +234,6 @@ abstract class ExplicitOuter extends InfoTransform *
    `base'.$outer$$C1 ... .$outer$$Cn
    * which refers to the outer instance of class to of * value base. The result is typed but not positioned. - * - * @param base ... - * @param from ... - * @param to ... - * @return ... */ protected def outerPath(base: Tree, from: Symbol, to: Symbol): Tree = { //Console.println("outerPath from "+from+" to "+to+" at "+base+":"+base.tpe) diff --git a/src/compiler/scala/tools/nsc/transform/Mixin.scala b/src/compiler/scala/tools/nsc/transform/Mixin.scala index 8122dc38cf..4797a231f8 100644 --- a/src/compiler/scala/tools/nsc/transform/Mixin.scala +++ b/src/compiler/scala/tools/nsc/transform/Mixin.scala @@ -588,8 +588,8 @@ abstract class Mixin extends InfoTransform with ast.TreeDSL { tree } - /** Create a static reference to given symbol sym of the - * form M.sym where M is the symbol's implementation module. + /** Create a static reference to given symbol `sym` of the + * form `M.sym` where M is the symbol's implementation module. */ private def staticRef(sym: Symbol): Tree = { sym.owner.info //todo: needed? @@ -671,8 +671,8 @@ abstract class Mixin extends InfoTransform with ast.TreeDSL { def addValDef(sym: Symbol, rhs: Tree = EmptyTree) = addDef(position(sym), ValDef(sym, rhs)) /** Add `newdefs` to `stats`, removing any abstract method definitions - * in stats that are matched by some symbol defined in - * newDefs. + * in `stats` that are matched by some symbol defined in + * `newDefs`. */ def add(stats: List[Tree], newDefs: List[Tree]) = { val newSyms = newDefs map (_.symbol) @@ -1144,9 +1144,9 @@ abstract class Mixin extends InfoTransform with ast.TreeDSL { qual case Apply(Select(qual, _), args) => - /** Changes qual.m(args) where m refers to an implementation + /** Changes `qual.m(args)` where m refers to an implementation * class method to Q.m(S, args) where Q is the implementation module of - * m and S is the self parameter for the call, which + * `m` and S is the self parameter for the call, which * is determined as follows: * - if qual != super, qual itself * - if qual == super, and we are in an implementation class, diff --git a/src/compiler/scala/tools/nsc/transform/TailCalls.scala b/src/compiler/scala/tools/nsc/transform/TailCalls.scala index 2e0cc3bd98..488b8aad4e 100644 --- a/src/compiler/scala/tools/nsc/transform/TailCalls.scala +++ b/src/compiler/scala/tools/nsc/transform/TailCalls.scala @@ -82,7 +82,7 @@ abstract class TailCalls extends Transform { * that label. *

    *

    - * Assumes: Uncurry has been run already, and no multiple + * Assumes: `Uncurry` has been run already, and no multiple * parameter lists exit. *

    */ diff --git a/src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala b/src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala index a9f6e2517b..65bfd8e34e 100644 --- a/src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala +++ b/src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala @@ -27,9 +27,6 @@ abstract class ConstantFolder { /** If tree is a constant value that can be converted to type `pt`, perform * the conversion. - * - * @param tree ... - * @param pt ... */ def apply(tree: Tree, pt: Type): Tree = fold(apply(tree), tree.tpe match { case ConstantType(x) => x convertTo pt diff --git a/src/compiler/scala/tools/nsc/typechecker/EtaExpansion.scala b/src/compiler/scala/tools/nsc/typechecker/EtaExpansion.scala index 9e21a2b82d..2806d7b2d9 100644 --- a/src/compiler/scala/tools/nsc/typechecker/EtaExpansion.scala +++ b/src/compiler/scala/tools/nsc/typechecker/EtaExpansion.scala @@ -33,7 +33,7 @@ trait EtaExpansion { self: Analyzer => } /**

    - * Expand partial function applications of type type. + * Expand partial function applications of type `type`. *

        *  p.f(es_1)...(es_n)
        *     ==>  {
    @@ -56,11 +56,8 @@ trait EtaExpansion { self: Analyzer =>
         }
         val defs = new ListBuffer[Tree]
     
    -    /** Append to defs value definitions for all non-stable
    -     *  subexpressions of the function application tree.
    -     *
    -     *  @param tree ...
    -     *  @return     ...
    +    /** Append to `defs` value definitions for all non-stable
    +     *  subexpressions of the function application `tree`.
          */
         def liftoutPrefix(tree: Tree): Tree = {
           def liftout(tree: Tree, byName: Boolean): Tree =
    diff --git a/src/compiler/scala/tools/nsc/typechecker/Infer.scala b/src/compiler/scala/tools/nsc/typechecker/Infer.scala
    index 6e42481d60..e1f05e1279 100644
    --- a/src/compiler/scala/tools/nsc/typechecker/Infer.scala
    +++ b/src/compiler/scala/tools/nsc/typechecker/Infer.scala
    @@ -130,9 +130,6 @@ trait Infer extends Checkable {
       }
     
       /** A fresh type variable with given type parameter as origin.
    -   *
    -   *  @param tparam ...
    -   *  @return       ...
        */
       def freshVar(tparam: Symbol): TypeVar = TypeVar(tparam)
     
    @@ -169,9 +166,6 @@ trait Infer extends Checkable {
       }
     
       /** Is type fully defined, i.e. no embedded anytypes or wildcards in it?
    -   *
    -   *  @param tp ...
    -   *  @return   ...
        */
       private[typechecker] def isFullyDefined(tp: Type): Boolean = tp match {
         case WildcardType | BoundedWildcardType(_) | NoType =>
    @@ -457,11 +451,6 @@ trait Infer extends Checkable {
          *  its type parameters and result type and a prototype `pt`.
          *  If no minimal type variables exist that make the
          *  instantiated type a subtype of `pt`, return null.
    -     *
    -     *  @param tparams ...
    -     *  @param restpe  ...
    -     *  @param pt      ...
    -     *  @return        ...
          */
         private def exprTypeArgs(tparams: List[Symbol], restpe: Type, pt: Type, useWeaklyCompatible: Boolean = false): (List[Type], List[TypeVar]) = {
           val tvars = tparams map freshVar
    @@ -494,12 +483,6 @@ trait Infer extends Checkable {
         *  in the value parameter list.
         *  If instantiation of a type parameter fails,
         *  take WildcardType for the proto-type argument.
    -    *
    -    *  @param tparams ...
    -    *  @param formals ...
    -    *  @param restype ...
    -    *  @param pt      ...
    -    *  @return        ...
         */
         def protoTypeArgs(tparams: List[Symbol], formals: List[Type], restpe: Type,
                           pt: Type): List[Type] = {
    @@ -927,10 +910,6 @@ trait Infer extends Checkable {
         /** Is type `ftpe1` strictly more specific than type `ftpe2`
          *  when both are alternatives in an overloaded function?
          *  @see SLS (sec:overloading-resolution)
    -     *
    -     *  @param ftpe1 ...
    -     *  @param ftpe2 ...
    -     *  @return      ...
          */
         def isAsSpecific(ftpe1: Type, ftpe2: Type): Boolean = ftpe1 match {
           case OverloadedType(pre, alts) =>
    @@ -1173,11 +1152,6 @@ trait Infer extends Checkable {
     
         /** Substitute free type variables `undetparams` of polymorphic argument
          *  expression `tree` to `targs`, Error if `targs` is null.
    -     *
    -     *  @param tree ...
    -     *  @param undetparams ...
    -     *  @param targs ...
    -     *  @param pt ...
          */
         private def substExpr(tree: Tree, undetparams: List[Symbol], targs: List[Type], pt: Type) {
           if (targs eq null) {
    @@ -1640,8 +1614,6 @@ trait Infer extends Checkable {
     
         /** Try inference twice, once without views and once with views,
          *  unless views are already disabled.
    -     *
    -     *  @param infer ...
          */
         def tryTwice(infer: Boolean => Unit): Unit = {
           if (context.implicitsEnabled) {
    @@ -1679,9 +1651,6 @@ trait Infer extends Checkable {
         /** Assign `tree` the type of all polymorphic alternatives
          *  with `nparams` as the number of type parameters, if it exists.
          *  If no such polymorphic alternative exist, error.
    -     *
    -     *  @param tree ...
    -     *  @param nparams ...
          */
         def inferPolyAlternatives(tree: Tree, argtypes: List[Type]): Unit = {
           val OverloadedType(pre, alts) = tree.tpe
    diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala
    index 0a0ab53852..ee5446ee87 100644
    --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala
    +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala
    @@ -57,16 +57,6 @@ trait Typers extends Modes with Adaptations with Tags {
           super.traverse(tree)
         }
       }
    -/* needed for experimental version where early types can be type arguments
    -  class EarlyMap(clazz: Symbol) extends TypeMap {
    -    def apply(tp: Type): Type = tp match {
    -      case TypeRef(NoPrefix, sym, List()) if (sym hasFlag PRESUPER) =>
    -        TypeRef(ThisType(clazz), sym, List())
    -      case _ =>
    -        mapOver(tp)
    -    }
    -  }
    -*/
     
       sealed abstract class SilentResult[+T] {
         @inline final def map[U](f: T => U): SilentResult[U] = this match {
    @@ -240,10 +230,7 @@ trait Typers extends Modes with Adaptations with Tags {
           case _ => tp
         }
     
    -    /** Check that tree is a stable expression.
    -     *
    -     *  @param tree ...
    -     *  @return     ...
    +    /** Check that `tree` is a stable expression.
          */
         def checkStable(tree: Tree): Tree = (
           if (treeInfo.isExprSafeToInline(tree)) tree
    @@ -297,11 +284,7 @@ trait Typers extends Modes with Adaptations with Tags {
           )
         }
     
    -    /** Check that type tp is not a subtype of itself.
    -     *
    -     *  @param pos ...
    -     *  @param tp  ...
    -     *  @return    true if tp is not a subtype of itself.
    +    /** Check that type `tp` is not a subtype of itself.
          */
         def checkNonCyclic(pos: Position, tp: Type): Boolean = {
           def checkNotLocked(sym: Symbol) = {
    @@ -316,12 +299,6 @@ trait Typers extends Modes with Adaptations with Tags {
     
             case SingleType(pre, sym) =>
               checkNotLocked(sym)
    -/*
    -        case TypeBounds(lo, hi) =>
    -          var ok = true
    -          for (t <- lo) ok = ok & checkNonCyclic(pos, t)
    -          ok
    -*/
             case st: SubType =>
               checkNonCyclic(pos, st.supertype)
             case ct: CompoundType =>
    @@ -375,13 +352,9 @@ trait Typers extends Modes with Adaptations with Tags {
           private var scope: Scope = _
           private var hiddenSymbols: List[Symbol] = _
     
    -      /** Check that type tree does not refer to private
    +      /** Check that type `tree` does not refer to private
            *  components unless itself is wrapped in something private
    -       *  (owner tells where the type occurs).
    -       *
    -       *  @param owner ...
    -       *  @param tree  ...
    -       *  @return      ...
    +       *  (`owner` tells where the type occurs).
            */
           def privates[T <: Tree](owner: Symbol, tree: T): T =
             check(owner, EmptyScope, WildcardType, tree)
    @@ -472,7 +445,7 @@ trait Typers extends Modes with Adaptations with Tags {
           }
     
         /** The qualifying class
    -     *  of a this or super with prefix qual.
    +     *  of a this or super with prefix `qual`.
          *  packageOk is equal false when qualifying class symbol
          */
         def qualifyingClass(tree: Tree, qual: Name, packageOK: Boolean) =
    @@ -558,7 +531,7 @@ trait Typers extends Modes with Adaptations with Tags {
           }
         }
     
    -    /** Does the context of tree tree require a stable type?
    +    /** Does the context of tree `tree` require a stable type?
          */
         private def isStableContext(tree: Tree, mode: Int, pt: Type) =
           isNarrowable(tree.tpe) && ((mode & (EXPRmode | LHSmode)) == EXPRmode) &&
    @@ -660,12 +633,6 @@ trait Typers extends Modes with Adaptations with Tags {
           case _                                    => !phase.erasedTypes
         }
     
    -    /**
    -     *  @param tree ...
    -     *  @param mode ...
    -     *  @param pt   ...
    -     *  @return     ...
    -     */
         def stabilizeFun(tree: Tree, mode: Int, pt: Type): Tree = {
           val sym = tree.symbol
           val pre = tree match {
    @@ -874,7 +841,6 @@ trait Typers extends Modes with Adaptations with Tags {
               debuglog("eta-expanding " + tree + ":" + tree.tpe + " to " + pt)
               checkParamsConvertible(tree, tree.tpe)
               val tree0 = etaExpand(context.unit, tree, this)
    -          // println("eta "+tree+" ---> "+tree0+":"+tree0.tpe+" undet: "+context.undetparams+ " mode: "+Integer.toHexString(mode))
     
               if (context.undetparams.nonEmpty) {
                 // #2624: need to infer type arguments for eta expansion of a polymorphic method
    @@ -960,9 +926,11 @@ trait Typers extends Modes with Adaptations with Tags {
           def adaptConstrPattern(): Tree = { // (5)
             def hasUnapplyMember(tp: Type) = reallyExists(unapplyMember(tp))
             val overloadedExtractorOfObject = tree.symbol filter (sym => hasUnapplyMember(sym.tpe))
    -        // if the tree's symbol's type does not define an extractor, maybe the tree's type does
    -        // this is the case when we encounter an arbitrary tree as the target of an unapply call (rather than something that looks like a constructor call)
    -        // (for now, this only happens due to wrapClassTagUnapply, but when we support parameterized extractors, it will become more common place)
    +        // if the tree's symbol's type does not define an extractor, maybe the tree's type does.
    +        // this is the case when we encounter an arbitrary tree as the target of an unapply call
    +        // (rather than something that looks like a constructor call.) (for now, this only happens
    +        // due to wrapClassTagUnapply, but when we support parameterized extractors, it will become
    +        // more common place)
             val extractor = overloadedExtractorOfObject orElse unapplyMember(tree.tpe)
             if (extractor != NoSymbol) {
               // if we did some ad-hoc overloading resolution, update the tree's symbol
    @@ -1555,16 +1523,6 @@ trait Typers extends Modes with Adaptations with Tags {
                 if (!supertparams.isEmpty)
                   MissingTypeArgumentsParentTpeError(supertpt)
             }
    -/* experimental: early types as type arguments
    -        val hasEarlyTypes = templ.body exists (treeInfo.isEarlyTypeDef)
    -        val earlyMap = new EarlyMap(clazz)
    -        List.mapConserve(supertpt :: mixins){ tpt =>
    -          val tpt1 = checkNoEscaping.privates(clazz, tpt)
    -          if (hasEarlyTypes) tpt1 else tpt1 setType earlyMap(tpt1.tpe)
    -        }
    -*/
    -
    -        //Console.println("parents("+clazz") = "+supertpt :: mixins);//DEBUG
     
             // Certain parents are added in the parser before it is known whether
             // that class also declared them as parents.  For instance, this is an
    @@ -1652,9 +1610,6 @@ trait Typers extends Modes with Adaptations with Tags {
                   !selfType.isErroneous &&
                   !parent.tpe.isErroneous)
               {
    -            //Console.println(context.owner);//DEBUG
    -            //Console.println(context.owner.unsafeTypeParams);//DEBUG
    -            //Console.println(List.fromArray(context.owner.info.closure));//DEBUG
                 pending += ParentSelfTypeConformanceError(parent, selfType)
                 if (settings.explaintypes.value) explainTypes(selfType, parent.tpe.typeOfThis)
               }
    @@ -1670,13 +1625,6 @@ trait Typers extends Modes with Adaptations with Tags {
             for (p <- parents) validateParentClass(p, superclazz)
           }
     
    -/*
    -      if (settings.Xshowcls.value != "" &&
    -          settings.Xshowcls.value == context.owner.fullName)
    -        println("INFO "+context.owner+
    -                ", baseclasses = "+(context.owner.info.baseClasses map (_.fullName))+
    -                ", lin = "+(context.owner.info.baseClasses map (context.owner.thisType.baseType)))
    -*/
           pending.foreach(ErrorUtils.issueTypeError)
         }
     
    @@ -1700,12 +1648,7 @@ trait Typers extends Modes with Adaptations with Tags {
           }
         }
     
    -    /**
    -     *  @param cdef ...
    -     *  @return     ...
    -     */
         def typedClassDef(cdef: ClassDef): Tree = {
    -//      attributes(cdef)
           val clazz = cdef.symbol
           val typedMods = typedModifiers(cdef.mods)
           assert(clazz != NoSymbol, cdef)
    @@ -1734,10 +1677,6 @@ trait Typers extends Modes with Adaptations with Tags {
             .setType(NoType)
         }
     
    -    /**
    -     *  @param mdef ...
    -     *  @return     ...
    -     */
         def typedModuleDef(mdef: ModuleDef): Tree = {
           // initialize all constructors of the linked class: the type completer (Namer.methodSig)
           // might add default getters to this object. example: "object T; class T(x: Int = 1)"
    @@ -1795,13 +1734,7 @@ trait Typers extends Modes with Adaptations with Tags {
           if (txt eq context) namer.enterSym(tree)
           else newNamer(txt).enterSym(tree)
     
    -    /**
    -     *  @param templ    ...
    -     *  @param parents1 ...
    -     *    
  3. - * Check that inner classes do not inherit from Annotation - *
  4. - * @return ... + /** Check that inner classes do not inherit from Annotation */ def typedTemplate(templ: Template, parents1: List[Tree]): Template = { val clazz = context.owner @@ -1876,12 +1809,7 @@ trait Typers extends Modes with Adaptations with Tags { def typedModifiers(mods: Modifiers): Modifiers = mods.copy(annotations = Nil) setPositions mods.positions - /** - * @param vdef ... - * @return ... - */ def typedValDef(vdef: ValDef): ValDef = { -// attributes(vdef) val sym = vdef.symbol.initialize val typer1 = constrTyperIf(sym.isParameter && sym.owner.isConstructor) val typedMods = typedModifiers(vdef.mods) @@ -1922,10 +1850,6 @@ trait Typers extends Modes with Adaptations with Tags { } /** Enter all aliases of local parameter accessors. - * - * @param clazz ... - * @param vparamss ... - * @param rhs ... */ def computeParamAliases(clazz: Symbol, vparamss: List[List[ValDef]], rhs: Tree) { debuglog(s"computing param aliases for $clazz:${clazz.primaryConstructor.tpe}:$rhs") @@ -2020,7 +1944,7 @@ trait Typers extends Modes with Adaptations with Tags { f(subTree) } - /** Check if a structurally defined method violates implementation restrictions. + /** Check if a structurally defined method violates implementation restrictions. * A method cannot be called if it is a non-private member of a refinement type * and if its parameter's types are any of: * - the self-type of the refinement @@ -2101,10 +2025,6 @@ trait Typers extends Modes with Adaptations with Tags { useCase.defined foreach (sym => println("defined use cases: %s:%s".format(sym, sym.tpe))) } - /** - * @param ddef ... - * @return ... - */ def typedDefDef(ddef: DefDef): DefDef = { val meth = ddef.symbol.initialize @@ -2257,12 +2177,6 @@ trait Typers extends Modes with Adaptations with Tags { } } - /** - * @param block ... - * @param mode ... - * @param pt ... - * @return ... - */ def typedBlock(block: Block, mode: Int, pt: Type): Block = { val syntheticPrivates = new ListBuffer[Symbol] try { @@ -2335,12 +2249,6 @@ trait Typers extends Modes with Adaptations with Tags { } } - /** - * @param cdef ... - * @param pattpe ... - * @param pt ... - * @return ... - */ def typedCase(cdef: CaseDef, pattpe: Type, pt: Type): CaseDef = { // verify no _* except in last position for (Apply(_, xs) <- cdef.pat ; x <- xs dropRight 1 ; if treeInfo isStar x) @@ -2606,12 +2514,6 @@ trait Typers extends Modes with Adaptations with Tags { override def mkSel(params: List[Symbol]) = sel.duplicate } - /** - * @param fun ... - * @param mode ... - * @param pt ... - * @return ... - */ private def typedFunction(fun: Function, mode: Int, pt: Type): Tree = { val numVparams = fun.vparams.length if (numVparams > definitions.MaxFunctionArity) @@ -3294,10 +3196,7 @@ trait Typers extends Modes with Adaptations with Tags { if (formals == null) duplErrorTree(WrongNumberOfArgsError(tree, fun)) else { val args1 = typedArgs(args, mode, formals, formalsExpanded) - // This used to be the following (failing) assert: - // assert(isFullyDefined(pt), tree+" ==> "+UnApply(fun1, args1)+", pt = "+pt) - // I modified as follows. See SI-1048. - val pt1 = if (isFullyDefined(pt)) pt else makeFullyDefined(pt) + val pt1 = if (isFullyDefined(pt)) pt else makeFullyDefined(pt) // SI-1048 val itype = glb(List(pt1, arg.tpe)) arg.tpe = pt1 // restore type (arg is a dummy tree, just needs to pass typechecking) @@ -4300,10 +4199,6 @@ trait Typers extends Modes with Adaptations with Tags { UnderscoreEtaError(expr1) } - /** - * @param args ... - * @return ... - */ def tryTypedArgs(args: List[Tree], mode: Int): Option[List[Tree]] = { val c = context.makeSilent(false) c.retyping = true @@ -4563,12 +4458,8 @@ trait Typers extends Modes with Adaptations with Tags { if (isStableContext(tree, mode, pt)) tree setType clazz.thisType else tree } - /** Attribute a selection where tree is qual.name. - * qual is already attributed. - * - * @param qual ... - * @param name ... - * @return ... + /** Attribute a selection where `tree` is `qual.name`. + * `qual` is already attributed. */ def typedSelect(tree: Tree, qual: Tree, name: Name): Tree = { val t = typedSelectInternal(tree, qual, name) @@ -5186,12 +5077,6 @@ trait Typers extends Modes with Adaptations with Tags { } } - /** - * @param tree ... - * @param mode ... - * @param pt ... - * @return ... - */ def typed(tree: Tree, mode: Int, pt: Type): Tree = { lastTreeToTyper = tree indentTyping() @@ -5262,10 +5147,7 @@ trait Typers extends Modes with Adaptations with Tags { def atOwner(tree: Tree, owner: Symbol): Typer = newTyper(context.make(tree, owner)) - /** Types expression or definition tree. - * - * @param tree ... - * @return ... + /** Types expression or definition `tree`. */ def typed(tree: Tree): Tree = { val ret = typed(tree, EXPRmode, WildcardType) @@ -5278,23 +5160,19 @@ trait Typers extends Modes with Adaptations with Tags { // it makes for a lot less casting. // def typedPos[T <: Tree](pos: Position)(tree: T): T = typed(atPos(pos)(tree)).asInstanceOf[T] - /** Types expression tree with given prototype pt. - * - * @param tree ... - * @param pt ... - * @return ... + /** Types expression `tree` with given prototype `pt`. */ def typed(tree: Tree, pt: Type): Tree = typed(tree, EXPRmode, pt) - /** Types qualifier tree of a select node. - * E.g. is tree occurs in a context like tree.m. + /** Types qualifier `tree` of a select node. + * E.g. is tree occurs in a context like `tree.m`. */ def typedQualifier(tree: Tree, mode: Int, pt: Type): Tree = typed(tree, EXPRmode | QUALmode | POLYmode | mode & TYPEPATmode, pt) // TR: don't set BYVALmode, since qualifier might end up as by-name param to an implicit - /** Types qualifier tree of a select node. - * E.g. is tree occurs in a context like tree.m. + /** Types qualifier `tree` of a select node. + * E.g. is tree occurs in a context like `tree.m`. */ def typedQualifier(tree: Tree, mode: Int): Tree = typedQualifier(tree, mode, WildcardType) @@ -5305,7 +5183,7 @@ trait Typers extends Modes with Adaptations with Tags { def typedOperator(tree: Tree): Tree = typed(tree, EXPRmode | FUNmode | POLYmode | TAPPmode, WildcardType) - /** Types a pattern with prototype pt */ + /** Types a pattern with prototype `pt` */ def typedPattern(tree: Tree, pt: Type): Tree = { // We disable implicits because otherwise some constructs will // type check which should not. The pattern matcher does not diff --git a/src/compiler/scala/tools/nsc/typechecker/Variances.scala b/src/compiler/scala/tools/nsc/typechecker/Variances.scala index ea436a71fb..aa66a8d00a 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Variances.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Variances.scala @@ -40,7 +40,7 @@ trait Variances { (VARIANCES /: tps) ((v, tp) => v & varianceInType(tp)(tparam)) /** Compute variance of type parameter `tparam` in all type arguments - * tps which correspond to formal type parameters `tparams1`. + * `tps` which correspond to formal type parameters `tparams1`. */ def varianceInArgs(tps: List[Type], tparams1: List[Symbol])(tparam: Symbol): Int = { var v: Int = VARIANCES; @@ -63,7 +63,7 @@ trait Variances { varianceInType(annot.atp)(tparam) } - /** Compute variance of type parameter tparam in type tp. */ + /** Compute variance of type parameter `tparam` in type `tp`. */ def varianceInType(tp: Type)(tparam: Symbol): Int = tp match { case ErrorType | WildcardType | NoType | NoPrefix | ThisType(_) | ConstantType(_) => VARIANCES diff --git a/src/library/scala/collection/immutable/RedBlackTree.scala b/src/library/scala/collection/immutable/RedBlackTree.scala index 3ade581c8f..99f8d95517 100644 --- a/src/library/scala/collection/immutable/RedBlackTree.scala +++ b/src/library/scala/collection/immutable/RedBlackTree.scala @@ -18,7 +18,7 @@ import scala.annotation.meta.getter /** An object containing the RedBlack tree implementation used by for `TreeMaps` and `TreeSets`. * * Implementation note: since efficiency is important for data structures this implementation - * uses null to represent empty trees. This also means pattern matching cannot + * uses `null` to represent empty trees. This also means pattern matching cannot * easily be used. The API represented by the RedBlackTree object tries to hide these * optimizations behind a reasonably clean API. * @@ -82,7 +82,7 @@ object RedBlackTree { f((tree.key, tree.value)) if (tree.right ne null) _foreach(tree.right, f) } - + def foreachKey[A, U](tree:Tree[A,_], f: A => U):Unit = if (tree ne null) _foreachKey(tree,f) private[this] def _foreachKey[A, U](tree: Tree[A, _], f: A => U) { @@ -90,7 +90,7 @@ object RedBlackTree { f((tree.key)) if (tree.right ne null) _foreachKey(tree.right, f) } - + def iterator[A, B](tree: Tree[A, B]): Iterator[(A, B)] = new EntriesIterator(tree) def keysIterator[A, _](tree: Tree[A, _]): Iterator[A] = new KeysIterator(tree) def valuesIterator[_, B](tree: Tree[_, B]): Iterator[B] = new ValuesIterator(tree) diff --git a/src/library/scala/concurrent/FutureTaskRunner.scala b/src/library/scala/concurrent/FutureTaskRunner.scala index eeadaddb5e..cb4f8687f3 100644 --- a/src/library/scala/concurrent/FutureTaskRunner.scala +++ b/src/library/scala/concurrent/FutureTaskRunner.scala @@ -10,7 +10,7 @@ package scala.concurrent import scala.language.{implicitConversions, higherKinds} -/** The `FutureTaskRunner trait is a base trait of task runners +/** The `FutureTaskRunner` trait is a base trait of task runners * that provide some sort of future abstraction. * * @author Philipp Haller diff --git a/src/library/scala/xml/Elem.scala b/src/library/scala/xml/Elem.scala index b9e665e292..fc32e45a5e 100755 --- a/src/library/scala/xml/Elem.scala +++ b/src/library/scala/xml/Elem.scala @@ -17,7 +17,7 @@ package scala.xml * @author Burak Emir */ object Elem { - /** Build an Elem, setting its minimizeEmpty property to true if it has no children. Note that this + /** Build an Elem, setting its minimizeEmpty property to `true` if it has no children. Note that this * default may not be exactly what you want, as some XML dialects don't permit some elements to be minimized. * * @deprecated This factory method is retained for backward compatibility; please use the other one, with which you diff --git a/src/library/scala/xml/Node.scala b/src/library/scala/xml/Node.scala index 6b6c962692..dcd4c15969 100755 --- a/src/library/scala/xml/Node.scala +++ b/src/library/scala/xml/Node.scala @@ -55,7 +55,7 @@ abstract class Node extends NodeSeq { def scope: NamespaceBinding = TopScope /** - * convenience, same as getNamespace(this.prefix) + * convenience, same as `getNamespace(this.prefix)` */ def namespace = getNamespace(this.prefix) @@ -64,8 +64,8 @@ abstract class Node extends NodeSeq { * checks if scope is `'''null'''`. * * @param pre the prefix whose namespace name we would like to obtain - * @return the namespace if scope != null and prefix was - * found, else null + * @return the namespace if `scope != null` and prefix was + * found, else `null` */ def getNamespace(pre: String): String = if (scope eq null) null else scope.getURI(pre) @@ -74,8 +74,8 @@ abstract class Node extends NodeSeq { * Same as `attributes.getValue(key)` * * @param key of queried attribute. - * @return value of UnprefixedAttribute with given key - * in attributes, if it exists, otherwise null. + * @return value of `UnprefixedAttribute` with given key + * in attributes, if it exists, otherwise `null`. */ final def attribute(key: String): Option[Seq[Node]] = attributes.get(key) diff --git a/src/reflect/scala/reflect/internal/Scopes.scala b/src/reflect/scala/reflect/internal/Scopes.scala index 950e30dbc5..6d0d34cfc1 100644 --- a/src/reflect/scala/reflect/internal/Scopes.scala +++ b/src/reflect/scala/reflect/internal/Scopes.scala @@ -30,11 +30,6 @@ trait Scopes extends api.Scopes { self: SymbolTable => override def toString() = s"$sym (depth=$depth)" } - /** - * @param sym ... - * @param owner ... - * @return ... - */ private def newScopeEntry(sym: Symbol, owner: Scope): ScopeEntry = { val e = new ScopeEntry(sym, owner) e.next = owner.elems @@ -101,8 +96,6 @@ trait Scopes extends api.Scopes { self: SymbolTable => } /** enter a scope entry - * - * @param e ... */ protected def enterEntry(e: ScopeEntry) { elemsCache = null @@ -119,8 +112,6 @@ trait Scopes extends api.Scopes { self: SymbolTable => } /** enter a symbol - * - * @param sym ... */ def enter[T <: Symbol](sym: T): T = { enterEntry(newScopeEntry(sym, this)) @@ -128,8 +119,6 @@ trait Scopes extends api.Scopes { self: SymbolTable => } /** enter a symbol, asserting that no symbol with same name exists in scope - * - * @param sym ... */ def enterUnique(sym: Symbol) { assert(lookup(sym.name) == NoSymbol, (sym.fullLocationString, lookup(sym.name).fullLocationString)) @@ -184,8 +173,6 @@ trait Scopes extends api.Scopes { self: SymbolTable => } /** remove entry - * - * @param e ... */ def unlink(e: ScopeEntry) { if (elems == e) { diff --git a/src/reflect/scala/reflect/internal/Symbols.scala b/src/reflect/scala/reflect/internal/Symbols.scala index eec780470e..2e806dd6b1 100644 --- a/src/reflect/scala/reflect/internal/Symbols.scala +++ b/src/reflect/scala/reflect/internal/Symbols.scala @@ -876,9 +876,6 @@ trait Symbols extends api.Symbols { self: SymbolTable => * (1) it is declared deferred or * (2) it is abstract override and its super symbol in `base` is * nonexistent or incomplete. - * - * @param base ... - * @return ... */ final def isIncompleteIn(base: Symbol): Boolean = this.isDeferred || @@ -1774,8 +1771,8 @@ trait Symbols extends api.Symbols { self: SymbolTable => /** The type of `this` in a class, or else the type of the symbol itself. */ def typeOfThis = thisSym.tpe_* - /** If symbol is a class, the type this.type in this class, - * otherwise NoPrefix. + /** If symbol is a class, the type `this.type` in this class, + * otherwise `NoPrefix`. * We always have: thisType <:< typeOfThis */ def thisType: Type = NoPrefix diff --git a/src/reflect/scala/reflect/internal/Types.scala b/src/reflect/scala/reflect/internal/Types.scala index 42a9d9e456..2f97b01ffa 100644 --- a/src/reflect/scala/reflect/internal/Types.scala +++ b/src/reflect/scala/reflect/internal/Types.scala @@ -2060,8 +2060,6 @@ trait Types extends api.Types { self: SymbolTable => extends ClassInfoType(List(), decls, clazz) /** A class representing a constant type. - * - * @param value ... */ abstract case class ConstantType(value: Constant) extends SingletonType with ConstantTypeApi { override def underlying: Type = value.tpe @@ -3567,10 +3565,6 @@ trait Types extends api.Types { self: SymbolTable => } /** The canonical creator for a refined type with an initially empty scope. - * - * @param parents ... - * @param owner ... - * @return ... */ def refinedType(parents: List[Type], owner: Symbol): Type = refinedType(parents, owner, newScope, owner.pos) diff --git a/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala b/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala index 6170fcbb90..e8ee202978 100644 --- a/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala +++ b/src/reflect/scala/reflect/internal/pickling/PickleBuffer.scala @@ -62,11 +62,8 @@ class PickleBuffer(data: Array[Byte], from: Int, to: Int) { writeByte((x & 0x7f).toInt) } - /** Write a natural number x at position pos. + /** Write a natural number `x` at position `pos`. * If number is more than one byte, shift rest of array to make space. - * - * @param pos ... - * @param x ... */ def patchNat(pos: Int, x: Int) { def patchNatPrefix(x: Int) { @@ -81,7 +78,7 @@ class PickleBuffer(data: Array[Byte], from: Int, to: Int) { if (y != 0) patchNatPrefix(y) } - /** Write a long number x in signed big endian format, base 256. + /** Write a long number `x` in signed big endian format, base 256. * * @param x The long number to be written. */ @@ -151,18 +148,14 @@ class PickleBuffer(data: Array[Byte], from: Int, to: Int) { result.toIndexedSeq } - /** Perform operation op until the condition - * readIndex == end is satisfied. + /** Perform operation `op` until the condition + * `readIndex == end` is satisfied. * Concatenate results into a list. - * - * @param end ... - * @param op ... - * @return ... */ def until[T](end: Int, op: () => T): List[T] = if (readIndex == end) List() else op() :: until(end, op); - /** Perform operation op the number of + /** Perform operation `op` the number of * times specified. Concatenate the results into a list. */ def times[T](n: Int, op: ()=>T): List[T] = diff --git a/src/reflect/scala/reflect/internal/pickling/UnPickler.scala b/src/reflect/scala/reflect/internal/pickling/UnPickler.scala index c82546b552..551ba4ee5c 100644 --- a/src/reflect/scala/reflect/internal/pickling/UnPickler.scala +++ b/src/reflect/scala/reflect/internal/pickling/UnPickler.scala @@ -159,9 +159,9 @@ abstract class UnPickler /*extends scala.reflect.generic.UnPickler*/ { result } - /** If entry at i is undefined, define it by performing - * operation op with readIndex at start of i'th - * entry. Restore readIndex afterwards. + /** If entry at `i` is undefined, define it by performing + * operation `op` with `readIndex at start of i'th + * entry. Restore `readIndex` afterwards. */ protected def at[T <: AnyRef](i: Int, op: () => T): T = { var r = entries(i) diff --git a/src/reflect/scala/reflect/internal/util/StringOps.scala b/src/reflect/scala/reflect/internal/util/StringOps.scala index bc02ad1058..5645eb4889 100644 --- a/src/reflect/scala/reflect/internal/util/StringOps.scala +++ b/src/reflect/scala/reflect/internal/util/StringOps.scala @@ -73,10 +73,6 @@ trait StringOps { else Some((str take idx, str drop (if (doDropIndex) idx + 1 else idx))) /** Returns a string meaning "n elements". - * - * @param n ... - * @param elements ... - * @return ... */ def countElementsAsString(n: Int, elements: String): String = n match { @@ -89,9 +85,6 @@ trait StringOps { } /** Turns a count into a friendly English description if n<=4. - * - * @param n ... - * @return ... */ def countAsString(n: Int): String = n match { diff --git a/src/reflect/scala/reflect/io/AbstractFile.scala b/src/reflect/scala/reflect/io/AbstractFile.scala index 15befb67f1..fa7298c726 100644 --- a/src/reflect/scala/reflect/io/AbstractFile.scala +++ b/src/reflect/scala/reflect/io/AbstractFile.scala @@ -27,7 +27,7 @@ object AbstractFile { /** * If the specified File exists and is a regular file, returns an - * abstract regular file backed by it. Otherwise, returns null. + * abstract regular file backed by it. Otherwise, returns `null`. */ def getFile(file: File): AbstractFile = if (file.isFile) new PlainFile(file) else null @@ -38,10 +38,7 @@ object AbstractFile { /** * If the specified File exists and is either a directory or a * readable zip or jar archive, returns an abstract directory - * backed by it. Otherwise, returns null. - * - * @param file ... - * @return ... + * backed by it. Otherwise, returns `null`. */ def getDirectory(file: File): AbstractFile = if (file.isDirectory) new PlainFile(file) @@ -51,10 +48,7 @@ object AbstractFile { /** * If the specified URL exists and is a readable zip or jar archive, * returns an abstract directory backed by it. Otherwise, returns - * null. - * - * @param file ... - * @return ... + * `null`. */ def getURL(url: URL): AbstractFile = { if (url == null || !Path.isExtensionJarOrZip(url.getPath)) null @@ -80,10 +74,10 @@ object AbstractFile { *

    *

    * The interface does not allow to access the content. - * The class symtab.classfile.AbstractFileReader accesses + * The class `symtab.classfile.AbstractFileReader` accesses * bytes, knowing that the character set of classfiles is UTF-8. For - * all other cases, the class SourceFile is used, which honors - * global.settings.encoding.value. + * all other cases, the class `SourceFile` is used, which honors + * `global.settings.encoding.value`. *

    * * ''Note: This library is considered experimental and should not be used unless you know what you are doing.'' @@ -148,7 +142,7 @@ abstract class AbstractFile extends Iterable[AbstractFile] { def toURL: URL = if (file == null) null else file.toURI.toURL /** Returns contents of file (if applicable) in a Char array. - * warning: use Global.getSourceFile() to use the proper + * warning: use `Global.getSourceFile()` to use the proper * encoding when converting to the char array. */ @throws(classOf[IOException]) @@ -175,8 +169,8 @@ abstract class AbstractFile extends Iterable[AbstractFile] { def iterator: Iterator[AbstractFile] /** Returns the abstract file in this abstract directory with the specified - * name. If there is no such file, returns null. The argument - * directory tells whether to look for a directory or + * name. If there is no such file, returns `null`. The argument + * `directory` tells whether to look for a directory or * a regular file. */ def lookupName(name: String, directory: Boolean): AbstractFile diff --git a/src/reflect/scala/reflect/io/VirtualFile.scala b/src/reflect/scala/reflect/io/VirtualFile.scala index 95f4429fad..eea81da290 100644 --- a/src/reflect/scala/reflect/io/VirtualFile.scala +++ b/src/reflect/scala/reflect/io/VirtualFile.scala @@ -3,7 +3,6 @@ * @author Martin Odersky */ - package scala.reflect package io @@ -33,12 +32,8 @@ class VirtualFile(val name: String, override val path: String) extends AbstractF case _ => false } - //######################################################################## - // Private data private var content = Array.emptyByteArray - //######################################################################## - // Public Methods def absolute = this /** Returns null. */ @@ -84,10 +79,6 @@ class VirtualFile(val name: String, override val path: String) extends AbstractF * specified name. If there is no such file, returns null. The * argument "directory" tells whether to look for a directory or * or a regular file. - * - * @param name ... - * @param directory ... - * @return ... */ def lookupName(name: String, directory: Boolean): AbstractFile = { assert(isDirectory, "not a directory '" + this + "'") @@ -98,6 +89,4 @@ class VirtualFile(val name: String, override val path: String) extends AbstractF * check that it exists. */ def lookupNameUnchecked(name: String, directory: Boolean) = unsupported - - //######################################################################## } -- cgit v1.2.3 From d09bb9c6377de4664da9a0a7067f94644ba841d5 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Tue, 13 Nov 2012 08:22:25 -0800 Subject: Some files removed in their entirety. And small associated changes. --- src/compiler/scala/tools/nsc/CompilerRun.scala | 21 ------ .../scala/tools/nsc/interpreter/CodeHandlers.scala | 50 -------------- .../scala/tools/nsc/interpreter/ExprTyper.scala | 7 +- src/compiler/scala/tools/nsc/io/Fileish.scala | 33 ---------- src/compiler/scala/tools/nsc/io/Jar.scala | 6 -- .../tools/nsc/settings/AdvancedScalaSettings.scala | 77 ---------------------- .../tools/partest/nest/ReflectiveRunner.scala | 7 +- .../scala/tools/partest/nest/RunnerUtils.scala | 29 -------- .../scala/tools/partest/utils/PrintMgr.scala | 52 --------------- 9 files changed, 8 insertions(+), 274 deletions(-) delete mode 100644 src/compiler/scala/tools/nsc/CompilerRun.scala delete mode 100644 src/compiler/scala/tools/nsc/interpreter/CodeHandlers.scala delete mode 100644 src/compiler/scala/tools/nsc/io/Fileish.scala delete mode 100644 src/compiler/scala/tools/nsc/settings/AdvancedScalaSettings.scala delete mode 100644 src/partest/scala/tools/partest/nest/RunnerUtils.scala delete mode 100644 src/partest/scala/tools/partest/utils/PrintMgr.scala (limited to 'src/compiler/scala/tools') diff --git a/src/compiler/scala/tools/nsc/CompilerRun.scala b/src/compiler/scala/tools/nsc/CompilerRun.scala deleted file mode 100644 index 6746b08155..0000000000 --- a/src/compiler/scala/tools/nsc/CompilerRun.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2013 LAMP/EPFL - * @author Martin Odersky - */ - -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 -} - diff --git a/src/compiler/scala/tools/nsc/interpreter/CodeHandlers.scala b/src/compiler/scala/tools/nsc/interpreter/CodeHandlers.scala deleted file mode 100644 index 1741a82775..0000000000 --- a/src/compiler/scala/tools/nsc/interpreter/CodeHandlers.scala +++ /dev/null @@ -1,50 +0,0 @@ -/* 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/ExprTyper.scala b/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala index ebd0030802..5ebaf6e031 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala @@ -17,7 +17,8 @@ trait ExprTyper { import syntaxAnalyzer.UnitParser import naming.freshInternalVarName - object codeParser extends { val global: repl.global.type = repl.global } with CodeHandlers[Tree] { + object codeParser { + val global: repl.global.type = repl.global def applyRule[T](code: String, rule: UnitParser => T): T = { reporter.reset() val scanner = newUnitParser(code) @@ -28,11 +29,7 @@ trait ExprTyper { result } - - 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 } /** Parse a line into a sequence of trees. Returns None if the input is incomplete. */ diff --git a/src/compiler/scala/tools/nsc/io/Fileish.scala b/src/compiler/scala/tools/nsc/io/Fileish.scala deleted file mode 100644 index 7b4e385dd8..0000000000 --- a/src/compiler/scala/tools/nsc/io/Fileish.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2013 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package io - -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() - - 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 "." - - 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) -} diff --git a/src/compiler/scala/tools/nsc/io/Jar.scala b/src/compiler/scala/tools/nsc/io/Jar.scala index ef2c9b13c0..3a9a878bc2 100644 --- a/src/compiler/scala/tools/nsc/io/Jar.scala +++ b/src/compiler/scala/tools/nsc/io/Jar.scala @@ -63,12 +63,6 @@ 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))) - - private def getEntryStream(entry: JarEntry) = jarFile getInputStream entry match { - case null => errorFn("No such entry: " + entry) ; null - case x => x - } override def toString = "" + file } diff --git a/src/compiler/scala/tools/nsc/settings/AdvancedScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/AdvancedScalaSettings.scala deleted file mode 100644 index 0bec113743..0000000000 --- a/src/compiler/scala/tools/nsc/settings/AdvancedScalaSettings.scala +++ /dev/null @@ -1,77 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2013 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package settings - -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 -} \ No newline at end of file diff --git a/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala b/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala index 5cb8589d66..22010d4b16 100644 --- a/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala +++ b/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala @@ -12,7 +12,6 @@ import scala.tools.nsc.Properties.{ setProp, propOrEmpty } import scala.tools.nsc.util.ClassPath import scala.tools.nsc.io import io.Path -import RunnerUtils._ import java.net.URLClassLoader /* This class is used to load an instance of DirectRunner using @@ -28,6 +27,12 @@ class ReflectiveRunner { // was used to start the runner. val sepRunnerClassName = "scala.tools.partest.nest.ConsoleRunner" + private def searchPath(option: String, as: List[String]): Option[String] = as match { + case `option` :: r :: _ => Some(r) + case _ :: rest => searchPath(option, rest) + case Nil => None + } + def main(args: String) { val argList = (args.split("\\s")).toList diff --git a/src/partest/scala/tools/partest/nest/RunnerUtils.scala b/src/partest/scala/tools/partest/nest/RunnerUtils.scala deleted file mode 100644 index 6707a9338a..0000000000 --- a/src/partest/scala/tools/partest/nest/RunnerUtils.scala +++ /dev/null @@ -1,29 +0,0 @@ -/* NEST (New Scala Test) - * Copyright 2007-2013 LAMP/EPFL - * @author Philipp Haller - */ - -// $Id$ - -package scala.tools.partest -package nest - -object RunnerUtils { - def splitArgs(str: String) = str split "\\s" filterNot (_ == "") toList - - def searchPath(option: String, as: List[String]): Option[String] = as match { - case `option` :: r :: _ => Some(r) - case _ :: rest => searchPath(option, rest) - case Nil => None - } - - def searchAndRemovePath(option: String, as: List[String]) = (as indexOf option) match { - case -1 => (None, as) - case idx => (Some(as(idx + 1)), (as take idx) ::: (as drop (idx + 2))) - } - - def searchAndRemoveOption(option: String, as: List[String]) = (as indexOf option) match { - case -1 => (false, as) - case idx => (true, (as take idx) ::: (as drop (idx + 1))) - } -} diff --git a/src/partest/scala/tools/partest/utils/PrintMgr.scala b/src/partest/scala/tools/partest/utils/PrintMgr.scala deleted file mode 100644 index d25be87c1e..0000000000 --- a/src/partest/scala/tools/partest/utils/PrintMgr.scala +++ /dev/null @@ -1,52 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala Parallel Testing ** -** / __/ __// _ | / / / _ | (c) 2007-2013, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.tools.partest -package utils - -/** - * @author Thomas Hofer - */ -object PrintMgr { - - val NONE = 0 - val SOME = 1 - val MANY = 2 - - var outline = "" - var success = "" - var failure = "" - var warning = "" - var default = "" - - def initialization(number: Int) = number match { - case MANY => - outline = Console.BOLD + Console.BLACK - success = Console.BOLD + Console.GREEN - failure = Console.BOLD + Console.RED - warning = Console.BOLD + Console.YELLOW - default = Console.RESET - case SOME => - outline = Console.BOLD + Console.BLACK - success = Console.RESET - failure = Console.BOLD + Console.BLACK - warning = Console.BOLD + Console.BLACK - default = Console.RESET - case _ => - } - - def printOutline(msg: String) = print(outline + msg + default) - - def printSuccess(msg: String) = print(success + msg + default) - - def printFailure(msg: String) = print(failure + msg + default) - - def printWarning(msg: String) = print(warning + msg + default) -} -- cgit v1.2.3 From 59c0c5dfce92e0ef70708b95b2712556cdab3623 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Tue, 13 Nov 2012 08:25:33 -0800 Subject: Members removed from the repl. There were a whole lot of these. --- .../scala/tools/nsc/interpreter/ByteCode.scala | 20 ---- .../scala/tools/nsc/interpreter/CommandLine.scala | 1 - .../scala/tools/nsc/interpreter/Completion.scala | 2 - .../tools/nsc/interpreter/CompletionAware.scala | 28 ----- .../tools/nsc/interpreter/CompletionOutput.scala | 1 - .../nsc/interpreter/ConsoleReaderHelper.scala | 5 - .../scala/tools/nsc/interpreter/Delimited.scala | 3 - .../scala/tools/nsc/interpreter/ExprTyper.scala | 4 - .../scala/tools/nsc/interpreter/ILoop.scala | 38 +------ .../scala/tools/nsc/interpreter/IMain.scala | 126 +-------------------- .../scala/tools/nsc/interpreter/ISettings.scala | 7 -- .../scala/tools/nsc/interpreter/Imports.scala | 16 +-- .../tools/nsc/interpreter/InteractiveReader.scala | 8 +- .../tools/nsc/interpreter/JLineCompletion.scala | 8 -- .../scala/tools/nsc/interpreter/JLineReader.scala | 8 -- .../scala/tools/nsc/interpreter/Logger.scala | 4 - .../scala/tools/nsc/interpreter/LoopCommands.scala | 21 ---- .../tools/nsc/interpreter/MemberHandlers.scala | 17 --- .../scala/tools/nsc/interpreter/NamedParam.scala | 4 - .../scala/tools/nsc/interpreter/Naming.scala | 1 - .../scala/tools/nsc/interpreter/Parsed.scala | 8 -- .../scala/tools/nsc/interpreter/Phased.scala | 19 ---- .../scala/tools/nsc/interpreter/Power.scala | 110 ++---------------- .../scala/tools/nsc/interpreter/ReplConfig.scala | 12 -- .../scala/tools/nsc/interpreter/ReplProps.scala | 4 - .../scala/tools/nsc/interpreter/ReplStrings.scala | 1 - .../scala/tools/nsc/interpreter/RichClass.scala | 5 +- .../scala/tools/nsc/interpreter/SimpleReader.scala | 5 +- .../scala/tools/nsc/interpreter/TypeStrings.scala | 10 -- .../scala/tools/nsc/interpreter/package.scala | 29 ----- .../tools/nsc/interpreter/session/History.scala | 6 - .../nsc/interpreter/session/SimpleHistory.scala | 6 +- 32 files changed, 25 insertions(+), 512 deletions(-) (limited to 'src/compiler/scala/tools') diff --git a/src/compiler/scala/tools/nsc/interpreter/ByteCode.scala b/src/compiler/scala/tools/nsc/interpreter/ByteCode.scala index 014661e525..48890a21c6 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ByteCode.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ByteCode.scala @@ -38,25 +38,5 @@ object ByteCode { } yield names - /** 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 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) - } } diff --git a/src/compiler/scala/tools/nsc/interpreter/CommandLine.scala b/src/compiler/scala/tools/nsc/interpreter/CommandLine.scala index 8042f0aee2..0ab92ab769 100644 --- a/src/compiler/scala/tools/nsc/interpreter/CommandLine.scala +++ b/src/compiler/scala/tools/nsc/interpreter/CommandLine.scala @@ -10,5 +10,4 @@ package interpreter */ class CommandLine(arguments: List[String], error: String => Unit) extends CompilerCommand(arguments, error) { override def cmdName = "scala" - 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 1dfccbfbf7..84a5cb49ae 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Completion.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Completion.scala @@ -23,8 +23,6 @@ object NoCompletion extends Completion { } object Completion { - 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 3a0b48ef57..3dd5d93390 100644 --- a/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala +++ b/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala @@ -51,31 +51,3 @@ trait CompletionAware { results.sorted } } - -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 - } - - /** 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 _) -} - diff --git a/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala b/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala index 13880bb8af..c647ef6f51 100644 --- a/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala +++ b/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala @@ -38,7 +38,6 @@ 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 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 b5850d901c..48af261937 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala @@ -9,15 +9,10 @@ package interpreter import scala.tools.jline.console.{ ConsoleReader, CursorBuffer } trait ConsoleReaderHelper extends ConsoleReader { - 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 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 80debfacb9..e88a044931 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Delimited.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Delimited.scala @@ -26,7 +26,6 @@ trait Delimited { def delimited: Char => Boolean def escapeChars: List[Char] = List('\\') - def quoteChars: List[(Char, Char)] = List(('\'', '\''), ('"', '"')) /** Break String into args based on delimiting function. */ @@ -39,6 +38,4 @@ 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 } diff --git a/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala b/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala index 5ebaf6e031..b087547cf8 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala @@ -42,10 +42,6 @@ trait ExprTyper { else Some(trees) } } - // def parsesAsExpr(line: String) = { - // import codeParser._ - // (opt expr line).isDefined - // } def symbolOfLine(code: String): Symbol = { def asExpr(): Symbol = { diff --git a/src/compiler/scala/tools/nsc/interpreter/ILoop.scala b/src/compiler/scala/tools/nsc/interpreter/ILoop.scala index 74549ef558..612a90f3ea 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ILoop.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ILoop.scala @@ -14,7 +14,6 @@ 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 util.ScalaClassLoader import ScalaClassLoader._ import scala.tools.util._ @@ -71,13 +70,9 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) intp.reporter printUntruncatedMessage msg } - 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 - // classpath entries added via :cp var addedClasspath: String = "" @@ -131,20 +126,18 @@ 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.longHelp) + case Some(lc) => echo("\n" + lc.help) case _ => ambiguousError(line) } } private def helpSummary() = { val usageWidth = commands map (_.usageMsg.length) max - val formatStr = "%-" + usageWidth + "s %s %s" + val formatStr = "%-" + usageWidth + "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") commands foreach { cmd => - val star = if (cmd.hasLongHelp) "*" else " " - echo(formatStr.format(cmd.usageMsg, star, cmd.help)) + echo(formatStr.format(cmd.usageMsg, cmd.help)) } } private def ambiguousError(cmd: String): Result = { @@ -194,10 +187,6 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) out println msg out.flush() } - protected def echoNoNL(msg: String) = { - out print msg - out.flush() - } /** Search the history */ def searchHistory(_cmdline: String) { @@ -208,8 +197,8 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) echo("%d %s".format(index + offset, line)) } - private var currentPrompt = Properties.shellPromptString - def setPrompt(prompt: String) = currentPrompt = prompt + private val currentPrompt = Properties.shellPromptString + /** Prompt to print when awaiting input */ def prompt = currentPrompt @@ -684,7 +673,6 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) def process(settings: Settings): Boolean = savingContextLoader { this.settings = settings createInterpreter() - 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,22 +691,8 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) true } - /** 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 - } - } - @deprecated("Use `process` instead", "2.9.0") - def main(settings: Settings): Unit = process(settings) + def main(settings: Settings): Unit = process(settings) //used by sbt } object ILoop { diff --git a/src/compiler/scala/tools/nsc/interpreter/IMain.scala b/src/compiler/scala/tools/nsc/interpreter/IMain.scala index 0ef27ac96a..3f49e782b0 100644 --- a/src/compiler/scala/tools/nsc/interpreter/IMain.scala +++ b/src/compiler/scala/tools/nsc/interpreter/IMain.scala @@ -63,6 +63,7 @@ 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 @@ -82,20 +83,11 @@ 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 } - } - 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 - } // Run the code body with the given boolean settings flipped to true. def withoutWarnings[T](body: => T): T = beQuietDuring { val saved = settings.nowarn.value @@ -110,12 +102,6 @@ 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 formatting: Formatting = new Formatting { val prompt = Properties.shellPromptString } @@ -175,7 +161,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends } import global._ - import definitions.{ ObjectClass, termMember, typeMember, dropNullaryMethod} + import definitions.{ ObjectClass, termMember, dropNullaryMethod} lazy val runtimeMirror = ru.runtimeMirror(classLoader) @@ -189,13 +175,8 @@ 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) - ) implicit class ReplTypeOps(tp: Type) { - 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) } @@ -211,7 +192,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends if (replScope containsName name) freshUserTermName() else name } - def isUserTermName(name: Name) = isUserVarName("" + name) def isInternalTermName(name: Name) = isInternalVarName("" + name) } import naming._ @@ -310,11 +290,8 @@ 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 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 sig(sym: Symbol): String = shift(sym.defString) } object typerOp extends PhaseDependentOps { @@ -328,7 +305,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends def originalPath(name: Name): String = typerOp path name def originalPath(sym: Symbol): String = typerOp path sym def flatPath(sym: Symbol): String = flatOp shift sym.javaClassName - // def translatePath(path: String) = symbolOfPath(path).fold(Option.empty[String])(flatPath) def translatePath(path: String) = { val sym = if (path endsWith "$") symbolOfTerm(path.init) else symbolOfIdent(path) sym match { @@ -354,8 +330,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends case p => new URLClassLoader(compilerClasspath, p) }) - def getInterpreterClassLoader() = classLoader - // Set the current Java "context" class loader to this interpreter's class loader def setContextClassLoader() = classLoader.setAsContext() @@ -405,7 +379,6 @@ 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 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.") @@ -423,19 +396,6 @@ 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 compileSourcesKeepingRun(sources: SourceFile*) = { val run = new Run() reporter.reset() @@ -653,17 +613,9 @@ 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 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) /** Reset this interpreter, forgetting all user-specified requests. */ def reset() { @@ -719,7 +671,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends def readPath = pathTo(readName) def evalPath = pathTo(evalName) - def printPath = pathTo(printName) def call(name: String, args: Any*): AnyRef = { val m = evalMethod(name) @@ -734,10 +685,6 @@ 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 } - class EvalException(msg: String, cause: Throwable) extends RuntimeException(msg, cause) { } private def evalError(path: String, ex: Throwable) = @@ -749,7 +696,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends } lazy val evalClass = load(evalPath) - lazy val evalValue = callOpt(resultName) def compile(source: String): Boolean = compileAndSaveRun("", source) @@ -798,14 +744,11 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends } /** One line of code submitted by the user for interpretation */ - // private class Request(val line: String, val trees: List[Tree]) { def defines = defHandlers flatMap (_.definedSymbols) def imports = importedSymbols - 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 lineRep = new ReadEvalPrint() private var _originalLine: String = null @@ -816,9 +759,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends val handlers: List[MemberHandler] = trees map (memberHandlers chooseHandler _) def defHandlers = handlers collect { case x: MemberDefHandler => x } - /** all (public) names defined by these statements */ - val definedNames = handlers flatMap (_.definedNames) - /** list of names used by this expression */ val referencedNames: List[Name] = handlers flatMap (_.referencedNames) @@ -836,9 +776,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends val ComputedImports(importsPreamble, importsTrailer, accessPath) = exitingTyper(importsCode(referencedNames.toSet)) - /** The unmangled symbol name, but supplemented with line info. */ - def disambiguated(name: Name): String = name + " (in " + lineRep + ")" - /** the line of code to compute */ def toCompute = line @@ -852,13 +789,11 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends // $intp is not bound; punt, but include the line. else if (path == "$intp") List( "def $line = " + tquoted(originalLine), - // "def $req = %s.requestForReqId(%s).orNull".format(path, reqId), "def $trees = Nil" ) else List( "def $line = " + tquoted(originalLine), "def $trees = Nil" - // "def $trees = if ($req eq null) Nil else $req.trees".format(lineRep.readName, path, reqId) ) } @@ -931,7 +866,6 @@ 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) private def typeMap[T](f: Type => T) = mapFrom[Name, Name, T](termNames ++ typeNames)(x => f(cleanMemberDecl(resultSymbol, x))) @@ -1011,8 +945,6 @@ 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 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)) @@ -1067,76 +999,30 @@ 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 definedSymbolList = prevRequestList flatMap (_.defines) filterNot (s => isInternalTermName(s.name)) // Terms with user-given names (i.e. not res0 and not synthetic) def namedDefinedTerms = definedTerms filterNot (x => isUserVarName("" + x) || directlyBoundNames(x)) - /** 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) - } - private var _replScope: Scope = _ private def resetReplScope() { _replScope = newScope } - 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 - } - } 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 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 importHandlers = allHandlers collect { case x: ImportHandler => x } + def allHandlers = prevRequestList flatMap (_.handlers) + def lastRequest = if (prevRequests.isEmpty) null else prevRequests.last + def prevRequestList = prevRequests.toList + def importHandlers = allHandlers collect { case x: ImportHandler => x } def withoutUnwrapping(op: => Unit): Unit = { val saved = isettings.unwrapStrings diff --git a/src/compiler/scala/tools/nsc/interpreter/ISettings.scala b/src/compiler/scala/tools/nsc/interpreter/ISettings.scala index 302ba7a8ac..d114ca2359 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ISettings.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ISettings.scala @@ -12,13 +12,6 @@ package interpreter * @author Lex Spoon, 2007/3/24 **/ class ISettings(intp: IMain) { - /** 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 - /** The maximum length of toString to use when printing the result * of an evaluation. 0 means no maximum. If a printout requires * more than this number of characters, then the printout is diff --git a/src/compiler/scala/tools/nsc/interpreter/Imports.scala b/src/compiler/scala/tools/nsc/interpreter/Imports.scala index c5048ebfd8..ff7bfd432c 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Imports.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Imports.scala @@ -15,9 +15,6 @@ trait Imports { import definitions.{ ObjectClass, ScalaPackage, JavaLangPackage, PredefModule } import memberHandlers._ - def isNoImports = settings.noimports.value - def isNoPredef = settings.nopredef.value - /** Synthetic import handlers for the language defined imports. */ private def makeWildcardImportHandler(sym: Symbol): ImportHandler = { val hd :: tl = sym.fullName.split('.').toList map newTermName @@ -31,12 +28,9 @@ 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 languageWildcardHandlers = languageWildcardSyms map makeWildcardImportHandler def allImportedNames = importHandlers flatMap (_.importedNames) - 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 +46,11 @@ trait Imports { def sessionWildcards: List[Type] = { importHandlers filter (_.importsWildcard) map (_.targetType) distinct } - 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 importedTermNamed(name: String): Symbol = - importedTermSymbols find (_.name.toString == name) getOrElse NoSymbol /** Tuples of (source, imported symbols) in the order they were imported. */ @@ -104,9 +92,7 @@ trait Imports { * last one imported is actually usable. */ case class ComputedImports(prepend: String, append: String, access: String) - protected def importsCode(wanted0: Set[Name]): ComputedImports = { - val wanted = wanted0 filterNot isUnlinked - + protected def importsCode(wanted: Set[Name]): ComputedImports = { /** Narrow down the list of requests from which imports * should be taken. Removes requests which cannot contribute * useful imports for the specified set of wanted names. diff --git a/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala b/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala index 6513381d77..28ddf2939c 100644 --- a/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala +++ b/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala @@ -15,22 +15,16 @@ import Properties.isMac trait InteractiveReader { val interactive: Boolean - def init(): Unit def reset(): Unit - def history: History def completion: Completion - def eraseLine(): Unit def redrawLine(): Unit - 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) protected def readOneLine(prompt: String): String protected def readOneKey(prompt: String): Int @@ -50,6 +44,6 @@ object InteractiveReader { def apply(): InteractiveReader = SimpleReader() @deprecated("Use `apply` instead.", "2.9.0") - def createDefault(): InteractiveReader = apply() + def createDefault(): InteractiveReader = apply() // used by sbt } diff --git a/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala index 5ee5e5526d..19fa562234 100644 --- a/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala +++ b/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala @@ -28,9 +28,6 @@ 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) trait CompilerCompletion { def tp: Type @@ -47,7 +44,6 @@ 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 // XXX we'd like to say "filterNot (_.isDeprecated)" but this causes the // compiler to crash for reasons not yet known. @@ -279,10 +275,6 @@ class JLineCompletion(val intp: IMain) extends Completion with CompletionOutput if (parsed.isEmpty) xs map ("." + _) else xs } - // generic interface for querying (e.g. interpreter loop, testing) - def completions(buf: String): List[String] = - topLevelFor(Parsed.dotted(buf + ".", buf.length + 1)) - def completer(): ScalaCompleter = new JLineTabCompletion /** This gets a little bit hairy. It's no small feat delegating everything diff --git a/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala b/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala index e033bab03b..a620c7c75a 100644 --- a/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala +++ b/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala @@ -23,7 +23,6 @@ class JLineReader(_completion: => Completion) extends InteractiveReader { private def term = consoleReader.getTerminal() def reset() = term.reset() - def init() = term.init() def scalaToJline(tc: ScalaCompleter): Completer = new Completer { def complete(_buf: String, cursor: Int, candidates: JList[CharSequence]): Int = { @@ -35,8 +34,6 @@ 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 readOneKey(prompt: String) = { this.print(prompt) this.flush() @@ -44,7 +41,6 @@ class JLineReader(_completion: => Completion) extends InteractiveReader { } def eraseLine() = consoleReader.resetPromptLine("", "", 0) def redrawLineAndFlush(): Unit = { flush() ; drawLine() ; flush() } - // override def readLine(prompt: String): String // A hook for running code after the repl is done initializing. lazy val postInit: Unit = { @@ -63,11 +59,7 @@ class JLineReader(_completion: => Completion) extends InteractiveReader { } } - def currentLine = consoleReader.getCursorBuffer.buffer.toString def redrawLine() = consoleReader.redrawLineAndFlush() - 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 def readOneKey(prompt: String) = consoleReader readOneKey prompt } diff --git a/src/compiler/scala/tools/nsc/interpreter/Logger.scala b/src/compiler/scala/tools/nsc/interpreter/Logger.scala index aeb25fc688..7407daf8d0 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Logger.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Logger.scala @@ -11,8 +11,4 @@ trait Logger { def isDebug: Boolean 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 } diff --git a/src/compiler/scala/tools/nsc/interpreter/LoopCommands.scala b/src/compiler/scala/tools/nsc/interpreter/LoopCommands.scala index 60325ece30..39979c8fbe 100644 --- a/src/compiler/scala/tools/nsc/interpreter/LoopCommands.scala +++ b/src/compiler/scala/tools/nsc/interpreter/LoopCommands.scala @@ -19,13 +19,8 @@ class ProcessResult(val line: String) { val exitCode = builder ! logger def lines = buffer.toList - 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) -} trait LoopCommands { protected def out: JPrintWriter @@ -35,14 +30,6 @@ 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 - } def usage: String = "" def usageMsg: String = ":" + name + ( if (usage == "") "" else " " + usage @@ -54,11 +41,6 @@ trait LoopCommands { "usage is " + usageMsg Result(true, None) } - - def onError(msg: String) = { - out.println("error: " + msg) - showUsage() - } } object LoopCommand { def nullary(name: String, help: String, f: () => Result): LoopCommand = @@ -67,9 +49,6 @@ trait LoopCommands { def cmd(name: String, usage: String, help: String, f: String => Result): LoopCommand = 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) } 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 95482f1e46..381dfeb261 100644 --- a/src/compiler/scala/tools/nsc/interpreter/MemberHandlers.scala +++ b/src/compiler/scala/tools/nsc/interpreter/MemberHandlers.scala @@ -81,7 +81,6 @@ trait MemberHandlers { def symbol = if (member.symbol eq null) NoSymbol else member.symbol def definesImplicit = false def definesValue = false - def isLegalTopLevel = false def definesTerm = Option.empty[TermName] def definesType = Option.empty[TypeName] @@ -152,7 +151,6 @@ trait MemberHandlers { class ModuleHandler(module: ModuleDef) extends MemberDefHandler(module) { override def definesTerm = Some(name) override def definesValue = true - override def isLegalTopLevel = true override def resultExtractionCode(req: Request) = codegenln("defined module ", name) } @@ -161,7 +159,6 @@ 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 resultExtractionCode(req: Request) = codegenln("defined %s %s".format(keyword, name)) @@ -182,20 +179,6 @@ 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) - } - // 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) - // wildcard imports, e.g. import foo._ private def selectorWild = selectors filter (_.name == nme.USCOREkw) // renamed imports, e.g. import foo.{ bar => baz } diff --git a/src/compiler/scala/tools/nsc/interpreter/NamedParam.scala b/src/compiler/scala/tools/nsc/interpreter/NamedParam.scala index eff0ef59c5..627a881cae 100644 --- a/src/compiler/scala/tools/nsc/interpreter/NamedParam.scala +++ b/src/compiler/scala/tools/nsc/interpreter/NamedParam.scala @@ -14,14 +14,10 @@ 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[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) - 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 0d03a8669a..41ddf23de4 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Naming.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Naming.scala @@ -78,7 +78,6 @@ 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 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 24c01e9ae6..672a6fd28f 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Parsed.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Parsed.scala @@ -17,7 +17,6 @@ class Parsed private ( ) extends Delimited { def isEmpty = args.isEmpty def isUnqualified = args.size == 1 - def isQualified = args.size > 1 def isAtStart = cursor <= 0 private var _verbosity = 0 @@ -31,7 +30,6 @@ 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 currentChar = buffer(cursor) def currentArg = args.last def position = @@ -41,8 +39,6 @@ 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 isQuoted = false // TODO def isEscaped = !isAtStart && isEscapeChar(currentChar) && !isEscapeChar(prev.currentChar) @@ -56,13 +52,9 @@ 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, 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, cursor: Int): Parsed = new Parsed(onull(s), cursor, _ == '.') - - 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 e6b780f177..f625124e70 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Phased.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Phased.scala @@ -24,7 +24,6 @@ trait Phased { case NoPhaseName => false case name => active = name ; true } - def getMulti = multi def setMulti(phases: Seq[PhaseName]): Boolean = { if (phases contains NoPhaseName) false else { @@ -66,16 +65,8 @@ trait Phased { try parseInternal(str) catch { case _: Exception => NoPhaseName } - 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 at[T](ph: PhaseName)(body: => T): T = { val saved = get @@ -90,11 +81,6 @@ 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 atMap[T](phs: Seq[PhaseName])(body: => T): Seq[(PhaseName, T)] = phs zip atMulti(phs)(body) @@ -112,16 +98,12 @@ 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 } sealed abstract class PhaseName { lazy val id = phase.id lazy val name = toString.toLowerCase def phase = currentRun.phaseNamed(name) def isEmpty = this eq NoPhaseName - - // Execute some code during this phase. - def apply[T](body: => T): T = enteringPhase(phase)(body) } case object Parser extends PhaseName @@ -158,5 +140,4 @@ trait Phased { } implicit def phaseEnumToPhase(name: PhaseName): Phase = name.phase - 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 ab0f1c0033..e517a16b32 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Power.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Power.scala @@ -149,17 +149,6 @@ 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", "") - ) - } trait LowPriorityInternalInfo { implicit def apply[T: ru.TypeTag : ClassTag] : InternalInfo[T] = new InternalInfo[T](None) @@ -172,12 +161,7 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re * symbol, by only implicitly installing one method, "?", and the rest * of the conveniences exist on that wrapper. */ - trait LowPriorityInternalInfoWrapper { - implicit def apply[T: ru.TypeTag : ClassTag] : InternalInfoWrapper[T] = new InternalInfoWrapper[T](None) - } - object InternalInfoWrapper extends LowPriorityInternalInfoWrapper { - - } + trait LowPriorityInternalInfoWrapper { } class InternalInfoWrapper[T: ru.TypeTag : ClassTag](value: Option[T] = None) { def ? : InternalInfo[T] = new InternalInfo[T](value) } @@ -187,7 +171,6 @@ 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 isSpecialized(s: Symbol) = s.name.toString contains "$mc" private def isImplClass(s: Symbol) = s.name.toString endsWith "$class" @@ -198,47 +181,15 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re || s.isAnonOrRefinementClass || s.isAnonymousFunction ) - 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 symbol = compilerSymbolFromTag(tag) + def tpe = compilerTypeFromTag(tag) 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 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 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 <:<[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 pkg = symbol.enclosingPackage + def tag = typeEvidence + def runtimeClass = runtimeClassEvidence.runtimeClass + def shortClass = runtimeClass.getName split "[$.]" last + def baseClasses = tpe.baseClasses override def toString = value match { case Some(x) => "%s (%s)".format(x, shortClass) @@ -264,7 +215,6 @@ 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 default[T] = new Prettifier[T] { def prettify(x: T): TraversableOnce[String] = AnyPrettifier prettify x def show(x: T): Unit = AnyPrettifier show x @@ -274,7 +224,6 @@ 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 prettify(xs: TraversableOnce[T]): TraversableOnce[String] = xs flatMap (x => prettify(x)) } @@ -286,31 +235,10 @@ 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 |[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) def >!(): Unit = pp(_.distinct) def >(): Unit = pp(identity) - - 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))) - - 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 - } } class MultiPrettifierClass[T: Prettifier](val value: Seq[T]) extends PrettifierClass[T]() { } @@ -334,17 +262,11 @@ class Power[ReplValsImpl <: ReplVals : ru.TypeTag: ClassTag](val intp: IMain, re class RichReplURL(url: URL)(implicit codec: Codec) { def slurp(): String = io.Streamable.slurp(url) } - class RichSymbolList(syms: List[Symbol]) { - def sigs = syms map (_.defString) - def infos = syms map (_.info) - } trait Implicits1 { // fallback 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) } trait Implicits2 extends Implicits1 { class RichSymbol(sym: Symbol) { @@ -369,26 +291,13 @@ 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) } trait ReplUtilities { - // [Eugene to Paul] needs review! - // def module[T: Manifest] = getModuleIfDefined(manifest[T].erasure.getName stripSuffix nme.MODULE_SUFFIX_STRING) - // def clazz[T: Manifest] = getClassIfDefined(manifest[T].erasure.getName) def module[T: ru.TypeTag] = ru.typeOf[T].typeSymbol.suchThat(_.isPackage) 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 sanitize(s: String): String = sanitize(s.getBytes()) def sanitize(s: Array[Byte]): String = (s map { case x if x.toChar.isControl => '?' @@ -406,11 +315,8 @@ 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 unit(code: String) = newCompilationUnit(code) def trees(code: String) = parse(code) getOrElse Nil - 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 7cd0f436c4..3392ea0b5e 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ReplConfig.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ReplConfig.scala @@ -14,9 +14,7 @@ trait ReplConfig { lazy val replProps = new ReplProps class TapMaker[T](x: T) { - 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 tap[U](f: T => U): T = { f(x) x @@ -28,12 +26,6 @@ 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 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 +37,10 @@ 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](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) 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 bc3e7a10d7..2364918494 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ReplProps.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ReplProps.scala @@ -13,15 +13,11 @@ 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 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 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 670bbf9bae..08472bbc64 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ReplStrings.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ReplStrings.scala @@ -29,5 +29,4 @@ 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) } diff --git a/src/compiler/scala/tools/nsc/interpreter/RichClass.scala b/src/compiler/scala/tools/nsc/interpreter/RichClass.scala index 4371f7fe05..36cdf65510 100644 --- a/src/compiler/scala/tools/nsc/interpreter/RichClass.scala +++ b/src/compiler/scala/tools/nsc/interpreter/RichClass.scala @@ -10,7 +10,6 @@ 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) // Sadly isAnonymousClass does not return true for scala anonymous // classes because our naming scheme is not doing well against the @@ -20,14 +19,12 @@ class RichClass[T](val clazz: Class[T]) { catch { case _: java.lang.InternalError => false } // good ol' "Malformed class name" ) - /** It's not easy... to be... me... */ - def supermans: List[ClassTag[_]] = supers map (_.toTag) + def supertags: 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 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 bccd8158ec..2d0917d91f 100644 --- a/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala +++ b/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala @@ -19,11 +19,8 @@ extends InteractiveReader val history = NoHistory val completion = NoCompletion - def init() = () def reset() = () - def eraseLine() = () def redrawLine() = () - def currentLine = "" def readOneLine(prompt: String): String = { if (interactive) { out.print(prompt) @@ -40,4 +37,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 9fb79a9d6f..239dbb8149 100644 --- a/src/compiler/scala/tools/nsc/interpreter/TypeStrings.scala +++ b/src/compiler/scala/tools/nsc/interpreter/TypeStrings.scala @@ -33,7 +33,6 @@ trait StructuredTypeStrings extends DestructureTypes { val NoGrouping = Grouping("", "", "", false) val ListGrouping = Grouping("(", ", ", ")", false) val ProductGrouping = Grouping("(", ", ", ")", true) - val ParamGrouping = Grouping("(", ", ", ")", true) val BlockGrouping = Grouping(" { ", "; ", "}", false) private def str(level: Int)(body: => String): String = " " * level + body @@ -189,7 +188,6 @@ trait TypeStrings { else enclClass.getName + "." + (name stripPrefix enclPre) ) } - 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 +218,6 @@ 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 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] @@ -240,13 +237,6 @@ trait TypeStrings { case (res, (k, v)) => res.replaceAll(k, v) } } - - 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 6a2d69db2c..52a085080b 100644 --- a/src/compiler/scala/tools/nsc/interpreter/package.scala +++ b/src/compiler/scala/tools/nsc/interpreter/package.scala @@ -48,7 +48,6 @@ 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 debugging[T](msg: String)(x: T) = x.tapDebug(msg) private val ourClassloader = getClass.getClassLoader @@ -68,39 +67,11 @@ package object interpreter extends ReplConfig with ReplStrings { import global.{ reporter => _, _ } import definitions._ - 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 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 daa05b86db..794d41adc7 100644 --- a/src/compiler/scala/tools/nsc/interpreter/session/History.scala +++ b/src/compiler/scala/tools/nsc/interpreter/session/History.scala @@ -14,15 +14,9 @@ trait History { def asStrings: List[String] def index: Int def size: Int - def grep(s: String): List[String] } object NoHistory extends History { def asStrings = Nil - def grep(s: String) = Nil def index = 0 def size = 0 } - -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 9f4e2b9df3..89998e438a 100644 --- a/src/compiler/scala/tools/nsc/interpreter/session/SimpleHistory.scala +++ b/src/compiler/scala/tools/nsc/interpreter/session/SimpleHistory.scala @@ -54,9 +54,5 @@ class SimpleHistory extends JLineHistory { def moveTo(idx: Int) = (idx > 0) && (idx <= lastIndex) && setTo(idx) def moveToEnd(): Unit = setTo(size) - // scala legacy interface - def asList: List[JEntry] = toEntries().toList - def asJavaList = entries() - def asStrings = buf.toList - def grep(s: String) = buf.toList filter (_ contains s) + def asStrings = buf.toList } -- cgit v1.2.3 From 50712cf5639bd42f420c540f526393a110f3349c Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Tue, 13 Nov 2012 08:29:07 -0800 Subject: Members removed in the backend. --- .../tools/nsc/backend/icode/BasicBlocks.scala | 28 ------------------ .../nsc/backend/icode/ExceptionHandlers.scala | 6 ---- .../scala/tools/nsc/backend/icode/GenICode.scala | 18 ------------ .../scala/tools/nsc/backend/icode/Members.scala | 28 ------------------ .../scala/tools/nsc/backend/icode/Opcodes.scala | 20 +------------ .../scala/tools/nsc/backend/icode/Primitives.scala | 13 --------- .../scala/tools/nsc/backend/icode/Repository.scala | 11 ------- .../scala/tools/nsc/backend/icode/TypeKinds.scala | 3 -- .../scala/tools/nsc/backend/icode/TypeStacks.scala | 10 ------- .../backend/icode/analysis/CopyPropagation.scala | 18 ++---------- .../backend/icode/analysis/DataFlowAnalysis.scala | 13 --------- .../backend/icode/analysis/TypeFlowAnalysis.scala | 34 ---------------------- .../scala/tools/nsc/backend/jvm/GenASM.scala | 14 --------- .../scala/tools/nsc/backend/jvm/GenJVM.scala | 17 ----------- .../scala/tools/nsc/backend/msil/GenMSIL.scala | 10 +------ .../tools/nsc/backend/opt/ClosureElimination.scala | 4 --- .../scala/tools/nsc/backend/opt/Inliners.scala | 4 --- 17 files changed, 4 insertions(+), 247 deletions(-) (limited to 'src/compiler/scala/tools') diff --git a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala index 7c7777f761..34bdc1ede4 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala @@ -280,14 +280,6 @@ 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") - - instrs = instrs.patch(idx + 1, is, 0) - code.touched = true - } - /** Removes instructions found at the given positions. */ def removeInstructionsAt(positions: Int*) { @@ -335,10 +327,6 @@ trait BasicBlocks { * is closed, which sets the DIRTYSUCCS flag. */ def emit(instr: Instruction, pos: Position) { -/* if (closed) { - print() - Console.println("trying to emit: " + instr) - } */ assert(!closed || ignore, this) if (ignore) { @@ -432,11 +420,6 @@ trait BasicBlocks { ignore = true } - 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 = if (closed) instrs(instrs.length - 1) @@ -493,17 +476,6 @@ 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() - } - 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 f35996eeb9..7c2961778f 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala @@ -71,10 +71,4 @@ trait ExceptionHandlers { override def toString() = "finalizer_" + label 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 - } } diff --git a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala index e2436d0e90..61d0292707 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala @@ -1946,13 +1946,6 @@ 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 - } - /** Prepare a new context upon entry into a method. */ def enterMethod(m: IMethod, d: DefDef): Context = { @@ -2025,16 +2018,6 @@ abstract class GenICode extends SubComponent { currentExceptionHandlers = currentExceptionHandlers.tail } - /** 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); - - } - /** Clone the current context */ def dup: Context = new Context(this) @@ -2321,7 +2304,6 @@ abstract class GenICode extends SubComponent { val locals: ListBuffer[Local] = new ListBuffer def add(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 07abe9d74f..12daa32186 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Members.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Members.scala @@ -126,9 +126,7 @@ trait Members { override def toString() = symbol.fullName - 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) /* returns this methods static ctor if it has one. */ def lookupStaticCtor: Option[IMethod] = methods find (_.symbol.isStaticConstructor) @@ -159,7 +157,6 @@ 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) var native = false @@ -192,7 +189,6 @@ trait Members { } def addLocals(ls: List[Local]) = ls foreach addLocal - 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 +203,7 @@ 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) - } - 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) - } - } - } /** Merge together blocks that have a single successor which has a * single predecessor. Exception handlers are taken into account (they @@ -294,9 +269,6 @@ trait Members { /** Starting PC for this local's visibility range. */ var start: Int = _ - /** Ending PC for this local's visibility range. */ - 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 0e7c75de50..eaa742a1da 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala @@ -3,8 +3,6 @@ * @author Martin Odersky */ - - package scala.tools.nsc package backend package icode @@ -110,17 +108,11 @@ trait Opcodes { self: ICodes => // Vlad: I wonder why we keep producedTypes around -- it looks like an useless thing to have def producedTypes: List[TypeKind] = Nil - /** This method returns the difference of size of the stack when the instruction is used */ - def difference = produced-consumed - /** The corresponding position in the source file */ private var _pos: Position = NoPosition def pos: Position = _pos - /** Used by dead code elimination. */ - var useful: Boolean = false - def setPos(p: Position): this.type = { _pos = p this @@ -132,13 +124,6 @@ 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 - } - /** Loads "this" on top of the stack. * Stack: ... * ->: ...:ref @@ -714,8 +699,6 @@ trait Opcodes { self: ICodes => /** Is this a static method call? */ def isStatic: Boolean = false - def isSuper: Boolean = false - /** Is this an instance method call? */ def hasInstance: Boolean = true @@ -749,7 +732,6 @@ trait Opcodes { self: ICodes => * On JVM, translated to `invokespecial`. */ case class SuperCall(mix: Name) extends InvokeStyle { - override def isSuper = true override def toString(): String = { "super(" + mix + ")" } } @@ -814,7 +796,7 @@ trait Opcodes { self: ICodes => case class CIL_NEWOBJ(method: Symbol) extends Instruction { override def toString(): String = "CIL_NEWOBJ " + hostClass.fullName + method.fullName - var hostClass: Symbol = method.owner; + val 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 c8579041ba..351d99f51a 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Primitives.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Primitives.scala @@ -76,25 +76,12 @@ trait Primitives { self: ICodes => /** Pretty printer for primitives */ class PrimitivePrinter(out: PrintWriter) { - def print(s: String): PrimitivePrinter = { out.print(s) this } def print(o: AnyRef): PrimitivePrinter = print(o.toString()) - - def printPrimitive(prim: Primitive) = prim match { - case Negation(kind) => - print("!") - - case Test(op, kind, zero) => - print(op).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 e73015c4da..e92e61c957 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Repository.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Repository.scala @@ -26,17 +26,6 @@ trait Repository { /** The icode of the given class, if available */ def icode(sym: Symbol): Option[IClass] = (classes get sym) orElse (loaded get sym) - /** 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) - } - /** Load bytecode for given symbol. */ def load(sym: Symbol): Boolean = { try { diff --git a/src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala b/src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala index f96dce9f1c..0990cfba6f 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala @@ -66,7 +66,6 @@ trait TypeKinds { self: ICodes => def isValueType = false def isBoxedType = false final def isRefOrArrayType = isReferenceType || isArrayType - final def isRefArrayOrBoxType = isRefOrArrayType || isBoxedType final def isNothingType = this == NothingReference final def isNullType = this == NullReference final def isInterfaceType = this match { @@ -114,8 +113,6 @@ trait TypeKinds { self: ICodes => } } - var lubs0 = 0 - /** * The least upper bound of two typekinds. They have to be either * REFERENCE or ARRAY kinds. diff --git a/src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala b/src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala index c1bf4304ea..57d51dad49 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala @@ -20,8 +20,6 @@ trait TypeStacks { */ type Rep = List[TypeKind] - object NoTypeStack extends TypeStack(Nil) { } - class TypeStack(var types: Rep) { if (types.nonEmpty) checkerDebug("Created " + this) @@ -69,14 +67,6 @@ trait TypeStacks { def apply(n: Int): TypeKind = types(n) - /** - * A TypeStack agrees with another one if they have the same - * 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) - /* This method returns a String representation of the stack */ override def toString() = if (types.isEmpty) "[]" 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 4a5844531a..7f32b2b764 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala @@ -26,12 +26,8 @@ abstract class CopyPropagation { case object This extends Location /** Values that can be on the stack. */ - abstract class Value { - def isRecord = false - } - case class Record(cls: Symbol, bindings: mutable.Map[Symbol, Value]) extends Value { - override def isRecord = true - } + abstract class Value { } + case class Record(cls: Symbol, bindings: mutable.Map[Symbol, Value]) extends Value { } /** The value of some location in memory. */ case class Deref(l: Location) extends Value @@ -91,16 +87,6 @@ abstract class CopyPropagation { loop(l) getOrElse Deref(LocalVar(l)) } - /* 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 - } - } - /** 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 * binding of that local. 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 04c3eedbad..cc3a7eb876 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala @@ -34,15 +34,6 @@ trait DataFlowAnalysis[L <: SemiLattice] { f } - /** 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 run(): Unit /** Implements forward dataflow analysis: the transfer function is @@ -82,10 +73,6 @@ trait DataFlowAnalysis[L <: SemiLattice] { sys.error("Could not find element " + e.getMessage) } - /** ... - * - * @param f ... - */ def backwardAnalysis(f: (P, lattice.Elem) => lattice.Elem): Unit = while (worklist.nonEmpty) { if (stat) iterations += 1 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 15755f31ad..c9d295a350 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala @@ -268,36 +268,6 @@ abstract class TypeFlowAnalysis { out } // 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)) } - } - abstract class InferredType { /** Return the type kind pointed by this inferred type. */ def getKind(in: lattice.Elem): icodes.TypeKind = this match { @@ -737,10 +707,6 @@ abstract class TypeFlowAnalysis { private var lastStart = 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 8bae80c760..1aa80d5c5b 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala @@ -455,7 +455,6 @@ 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_STRING_ARRAY = Array.empty[String] val mdesc_arglessvoid = "()V" @@ -523,7 +522,6 @@ 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[String]): Array[String] = { val a = new Array[String](xs.size); xs.copyToArray(a); a } // ----------------------------------------------------------------------------------------- @@ -1757,11 +1755,6 @@ 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) } - } - final def boolconst(b: Boolean) { iconst(if(b) 1 else 0) } def iconst(cst: Int) { @@ -2924,15 +2917,8 @@ abstract class GenASM extends SubComponent with BytecodeWriters { ////////////////////// local vars /////////////////////// - // 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) - // } - final def indexOf(local: Local): Int = { assert(local.index >= 0, "Invalid index for: " + local + "{" + local.## + "}: ") local.index diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala index 31a4554d97..e1484d1f97 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala @@ -182,15 +182,9 @@ 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") // 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") final val ExcludedForwarderFlags = { import Flags._ @@ -254,7 +248,6 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with var method: IMethod = _ var jclass: JClass = _ var jmethod: JMethod = _ - // var jcode: JExtendedCode = _ def isParcelableClass = isAndroidParcelableClass(clasz.symbol) def isRemoteClass = clasz.symbol hasAnnotation RemoteAttr @@ -263,9 +256,6 @@ 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 emitVars = debugLevel >= 3 // bug had phase with wrong name; leaving enabled for brief pseudo deprecation @@ -1835,15 +1825,8 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with ////////////////////// local vars /////////////////////// - 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(local: Local): Int = { assert(local.index >= 0, "Invalid index for: " + local + "{" + local.## + "}: ") local.index diff --git a/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala b/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala index 2253ae6e15..2fb6550239 100644 --- a/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala +++ b/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala @@ -23,8 +23,6 @@ abstract class GenMSIL extends SubComponent { import icodes._ import icodes.opcodes._ - val x = loaders - /** Create a new phase */ override def newPhase(p: Phase) = new MsilPhase(p) @@ -83,9 +81,6 @@ 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 ICLONEABLE = clrTypes.getType("System.ICloneable") val MEMBERWISE_CLONE = MOBJECT.GetMethod("MemberwiseClone", MsilType.EmptyTypes) val MMONITOR = clrTypes.getType("System.Threading.Monitor") @@ -102,9 +97,6 @@ abstract class GenMSIL extends SubComponent { val INT_PTR = clrTypes.getType("System.IntPtr") - val JOBJECT = definitions.ObjectClass - val JSTRING = definitions.StringClass - val SystemConvert = clrTypes.getType("System.Convert") val objParam = Array(MOBJECT) @@ -622,7 +614,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 */ - var currentHandlers = new mutable.Stack[ExceptionHandler] + val 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 8d6de821bb..650775b259 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala @@ -187,10 +187,6 @@ abstract class ClosureElimination extends SubComponent { case Boxed(LocalVar(v)) => LOAD_LOCAL(v) } - - /** is field 'f' accessible from method 'm'? */ - 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 7d741aab60..ca1cfc8929 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala @@ -602,7 +602,6 @@ abstract class Inliners extends SubComponent { override def toString = m.toString val sym = m.symbol - val name = sym.name def owner = sym.owner def paramTypes = sym.info.paramTypes def minimumStack = paramTypes.length + 1 @@ -618,13 +617,11 @@ abstract class Inliners extends SubComponent { def length = blocks.length def openBlocks = blocks filterNot (_.closed) def instructions = m.code.instructions - // def linearized = linearizer linearize m def isSmall = (length <= SMALL_METHOD_SIZE) && blocks(0).length < 10 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 isSynchronized = sym.hasFlag(Flags.SYNCHRONIZED) def hasNonFinalizerHandler = handlers exists { @@ -732,7 +729,6 @@ abstract class Inliners extends SubComponent { */ sealed abstract class InlineSafetyInfo { def isSafe = false - def isUnsafe = !isSafe } case object NeverSafeToInline extends InlineSafetyInfo case object InlineableAtThisCaller extends InlineSafetyInfo { override def isSafe = true } -- cgit v1.2.3 From 009c57d4622fe69394fe031ad7577a4fdee0b1d9 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Tue, 13 Nov 2012 08:30:55 -0800 Subject: Removed code from the typechecker. Removing code from this neighborhood is more difficult than elsewhere, making it all the more important that it be done. --- .../scala/tools/nsc/typechecker/Contexts.scala | 22 ----- .../tools/nsc/typechecker/DestructureTypes.scala | 10 -- .../scala/tools/nsc/typechecker/Duplicators.scala | 22 ----- .../scala/tools/nsc/typechecker/Implicits.scala | 6 -- .../tools/nsc/typechecker/MethodSynthesis.scala | 82 +++------------- .../scala/tools/nsc/typechecker/Namers.scala | 6 -- .../tools/nsc/typechecker/NamesDefaults.scala | 2 - .../tools/nsc/typechecker/PatternMatching.scala | 105 +++++++++------------ .../scala/tools/nsc/typechecker/TreeCheckers.scala | 7 -- .../tools/nsc/typechecker/TypeDiagnostics.scala | 13 --- .../scala/tools/nsc/typechecker/Typers.scala | 24 ----- .../scala/tools/nsc/typechecker/Unapplies.scala | 12 --- 12 files changed, 60 insertions(+), 251 deletions(-) (limited to 'src/compiler/scala/tools') diff --git a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala index a8d7de6362..16e5e7d4a2 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala @@ -219,8 +219,6 @@ trait Contexts { self: Analyzer => current } - def logError(err: AbsTypeError) = buffer += err - def withImplicitsEnabled[T](op: => T): T = { val saved = implicitsEnabled implicitsEnabled = true @@ -312,15 +310,6 @@ trait Contexts { self: Analyzer => c } - // 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 makeNewImport(sym: Symbol): Context = makeNewImport(gen.mkWildcardImport(sym)) @@ -489,17 +478,6 @@ trait Contexts { self: Analyzer => sub.isNonBottomSubClass(base) || sub.isModuleClass && sub.linkedClassOfClass.isNonBottomSubClass(base) - /** 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 - } - /** 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 79cd46e018..73572bcae9 100644 --- a/src/compiler/scala/tools/nsc/typechecker/DestructureTypes.scala +++ b/src/compiler/scala/tools/nsc/typechecker/DestructureTypes.scala @@ -64,15 +64,6 @@ 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 wrapSymbolInfo(sym: Symbol): Node = { if ((sym eq NoSymbol) || openSymbols(sym)) wrapEmpty else { @@ -95,7 +86,6 @@ 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 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 7d58155eb2..9c23b8663c 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala @@ -19,11 +19,6 @@ abstract class Duplicators extends Analyzer { import global._ import definitions.{ AnyRefClass, AnyValClass } - 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 * the old class with the new class, and map symbols through the given 'env'. The @@ -42,9 +37,6 @@ 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) - /** Return the special typer for duplicate method bodies. */ override def newTyper(context: Context): Typer = newBodyDuplicator(context) @@ -186,20 +178,6 @@ 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) - } - /** 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 576a21fe31..c92f65afdd 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala @@ -233,10 +233,6 @@ 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 - } } /** An extractor for types of the form ? { name: (? >: argtpe <: Any*)restp } @@ -1493,9 +1489,7 @@ 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 implicitSearchCount = Statistics.newCounter ("#implicit searches", "typer") - 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 6aafd32237..e67d6814f1 100644 --- a/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala +++ b/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala @@ -29,61 +29,23 @@ 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 - - // 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): _*) - } - - 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[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, 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) - } - - /** The annotations amongst those found on the original symbol which - * should be propagated to this kind of accessor. - */ - def deriveAnnotations(initial: List[AnnotationInfo], category: Symbol, keepClean: Boolean): List[AnnotationInfo] = { - initial filter { ann => - // There are no meta-annotation arguments attached to `ann` - if (ann.metaAnnotations.isEmpty) { - // A meta-annotation matching `annotKind` exists on `ann`'s definition. - (ann.defaultTargets contains category) || - // `ann`'s definition has no meta-annotations, and `keepClean` is true. - (ann.defaultTargets.isEmpty && keepClean) - } - // There are meta-annotation arguments, and one of them matches `annotKind` - else ann.metaAnnotations exists (_ matches category) + /** The annotations amongst those found on the original symbol which + * should be propagated to this kind of accessor. + */ + def deriveAnnotations(initial: List[AnnotationInfo], category: Symbol, keepClean: Boolean): List[AnnotationInfo] = { + initial filter { ann => + // There are no meta-annotation arguments attached to `ann` + if (ann.metaAnnotations.isEmpty) { + // A meta-annotation matching `annotKind` exists on `ann`'s definition. + (ann.defaultTargets contains category) || + // `ann`'s definition has no meta-annotations, and `keepClean` is true. + (ann.defaultTargets.isEmpty && keepClean) } + // There are meta-annotation arguments, and one of them matches `annotKind` + else ann.metaAnnotations exists (_ matches category) } - } + } + } import synthesisUtil._ class ClassMethodSynthesis(val clazz: Symbol, localTyper: Typer) { @@ -118,22 +80,9 @@ trait MethodSynthesis { finishMethod(clazz.info.decls enter m, f) } - 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 - /** Function argument takes the newly created method symbol of - * 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(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 +260,6 @@ 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 } 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 28bed0f1bf..817b4b7542 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Namers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Namers.scala @@ -1388,12 +1388,6 @@ 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 - } - class LogTransitions[S](onEnter: S => String, onExit: S => String) { val enabled = settings.debug.value @inline final def apply[T](entity: S)(body: => T): T = { diff --git a/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala b/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala index 252a738755..14c8d85836 100644 --- a/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala +++ b/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala @@ -41,8 +41,6 @@ trait NamesDefaults { self: Analyzer => blockTyper: Typer ) { } - val noApplyInfo = NamedApplyInfo(None, Nil, Nil, null) - def nameOf(arg: Tree) = arg match { case AssignOrNamedArg(Ident(name), rhs) => Some(name) case _ => None diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala index 7cb420d2dc..07c12f1034 100644 --- a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala +++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala @@ -291,8 +291,6 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL // pt is the skolemized version val pt = repeatedToSeq(ptUnCPS) - // val packedPt = repeatedToSeq(typer.packedType(match_, context.owner)) - // the alternative to attaching the default case override would be to simply // append the default to the list of cases and suppress the unreachable case error that may arise (once we detect that...) val matchFailGenOverride = match_.attachments.get[DefaultOverrideMatchAttachment].map{case DefaultOverrideMatchAttachment(default) => ((scrut: Tree) => default)} @@ -547,54 +545,55 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL def fromCaseClass(fun: Tree, args: List[Tree]): Option[ExtractorCall] = Some(new ExtractorCallProd(fun, args)) // THE PRINCIPLED SLOW PATH -- NOT USED + // !!! Use it, test it, or delete it, else it is unlikely to be an asset. // generate a call to the (synthetically generated) extractor of a case class // 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 +1412,8 @@ 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 _equals(checker: Tree, binder: Symbol): Tree def _isInstanceOf(b: Symbol, tp: Type): 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 +1455,10 @@ 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 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 // 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,10 +1466,8 @@ 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(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 } // duplicated out of frustration with cast generation def mkZero(tp: Type): Tree = { @@ -2879,8 +2872,6 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL v +"(="+ v.path +": "+ v.staticTpCheckable +") "+ assignment }.mkString("\n") - 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, // so, naively, you might try to construct a counter example like _ :: Nil(_ :: _, _ :: _), @@ -3538,7 +3529,6 @@ 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 val alternativesSupported = false // TODO: needs either back-end support of flattening of alternatives during typers val canJump = false @@ -3584,11 +3574,6 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL trait OptimizedCodegen extends CodegenCore with TypedSubstitution with OptimizedMatchMonadInterface { override def codegen: AbsCodegen = optimizedCodegen - // trait AbsOptimizedCodegen extends AbsCodegen { - // def flatMapCondStored(cond: Tree, condSym: Symbol, res: Tree, nextBinder: Symbol, next: Tree): Tree - // } - // def optimizedCodegen: AbsOptimizedCodegen - // when we know we're targetting Option, do some inlining the optimizer won't do // for example, `o.flatMap(f)` becomes `if(o == None) None else f(o.get)`, similarly for orElse and guard // this is a special instance of the advanced inlining optimization that takes a method call on diff --git a/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala b/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala index 710adf5a9c..be7554abe2 100644 --- a/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala @@ -142,13 +142,6 @@ 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 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 4f5291507e..19f0b56e94 100644 --- a/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala +++ b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala @@ -37,14 +37,6 @@ trait TypeDiagnostics { import global._ import definitions._ - /** The common situation of making sure nothing is erroneous could be - * 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) - /** For errors which are artifacts of the implementation: such messages * indicate that the restriction may be lifted in the future. */ @@ -294,7 +286,6 @@ 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 modifyName(f: String => String) = sym setName newTypeName(f(sym.name.toString)) /** Prepend java.lang, scala., or Predef. if this type originated @@ -478,10 +469,6 @@ trait TypeDiagnostics { } super.traverse(t) } - 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 ee5446ee87..670e3902dd 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -359,17 +359,6 @@ trait Typers extends Modes with Adaptations with Tags { def privates[T <: Tree](owner: Symbol, tree: T): T = check(owner, EmptyScope, WildcardType, tree) - /** Check that type tree does not refer to entities - * defined in scope scope. - * - * @param scope ... - * @param pt ... - * @param tree ... - * @return ... - */ - 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 this.scope = scope @@ -5221,8 +5210,6 @@ 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) - /** Types a type constructor tree used in a new or supertype */ def typedTypeConstructor(tree: Tree, mode: Int): Tree = { val result = typed(tree, forTypeMode(mode) | FUNmode, WildcardType) @@ -5297,28 +5284,17 @@ trait Typers extends Modes with Adaptations with Tags { case Some(tree1) => transformed -= tree; tree1 case None => typed(tree, mode, pt) } - -/* - def convertToTypeTree(tree: Tree): Tree = tree match { - case TypeTree() => tree - case _ => TypeTree(tree.tpe) - } -*/ } } object TypersStats { import scala.reflect.internal.TypesStats._ - 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 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 bf44b65406..061c6679da 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala @@ -23,7 +23,6 @@ trait Unapplies extends ast.TreeDSL private val unapplyParamName = nme.x_0 - // In the typeCompleter (templateSig) of a case class (resp it's module), // synthetic `copy` (reps `apply`, `unapply`) methods are added. To compute // their signatures, the corresponding ClassDef is needed. During naming (in @@ -46,17 +45,6 @@ trait Unapplies extends ast.TreeDSL } } - /** returns type of the unapply method returning T_0...T_n - * for n == 0, boolean - * 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))) - } - /** returns unapply or unapplySeq if available */ def unapplyMember(tp: Type): Symbol = (tp member nme.unapply) match { case NoSymbol => tp member nme.unapplySeq -- cgit v1.2.3 From c54432c3e209f1ffbe3a05d0d7ee0532d20e4dd0 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Tue, 13 Nov 2012 08:32:27 -0800 Subject: Removed code from scaladoc. Nobody is immune! --- src/compiler/scala/tools/nsc/ast/DocComments.scala | 7 ---- src/compiler/scala/tools/nsc/doc/html/Page.scala | 6 --- .../scala/tools/nsc/doc/model/Entity.scala | 27 -------------- .../tools/nsc/doc/model/IndexModelFactory.scala | 2 - .../scala/tools/nsc/doc/model/ModelFactory.scala | 43 ++-------------------- .../doc/model/ModelFactoryImplicitSupport.scala | 25 ++++--------- .../tools/nsc/doc/model/comment/Comment.scala | 3 -- .../nsc/doc/model/comment/CommentFactory.scala | 20 ---------- .../tools/nsc/doc/model/diagram/Diagram.scala | 11 +----- 9 files changed, 13 insertions(+), 131 deletions(-) (limited to 'src/compiler/scala/tools') diff --git a/src/compiler/scala/tools/nsc/ast/DocComments.scala b/src/compiler/scala/tools/nsc/ast/DocComments.scala index 21407289db..023f3c229c 100755 --- a/src/compiler/scala/tools/nsc/ast/DocComments.scala +++ b/src/compiler/scala/tools/nsc/ast/DocComments.scala @@ -21,11 +21,6 @@ trait DocComments { self: Global => /** The raw doc comment map */ 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)) - /** The raw doc comment of symbol `sym`, as it appears in the source text, "" if missing. */ def rawDocComment(sym: Symbol): String = @@ -120,8 +115,6 @@ trait DocComments { self: Global => getDocComment(sym) map getUseCases getOrElse List() } - def useCases(sym: Symbol): List[(Symbol, String, Position)] = useCases(sym, sym.enclClass) - /** Returns the javadoc format of doc comment string `s`, including wiki expansion */ def toJavaDoc(s: String): String = expandWiki(s) diff --git a/src/compiler/scala/tools/nsc/doc/html/Page.scala b/src/compiler/scala/tools/nsc/doc/html/Page.scala index 62166f7def..ef9beb1dce 100644 --- a/src/compiler/scala/tools/nsc/doc/html/Page.scala +++ b/src/compiler/scala/tools/nsc/doc/html/Page.scala @@ -88,12 +88,6 @@ abstract class Page { def relativeLinkTo(destClass: TemplateEntity): String = relativeLinkTo(templateToPath(destClass)) - /** 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) - } - /** A relative link from this page to some destination path. * @param destPath The path that the link will point to. */ def relativeLinkTo(destPath: List[String]): String = { diff --git a/src/compiler/scala/tools/nsc/doc/model/Entity.scala b/src/compiler/scala/tools/nsc/doc/model/Entity.scala index 6b24073339..04046accc4 100644 --- a/src/compiler/scala/tools/nsc/doc/model/Entity.scala +++ b/src/compiler/scala/tools/nsc/doc/model/Entity.scala @@ -23,10 +23,6 @@ import diagram._ * - type and value parameters; * - annotations. */ trait Entity { - - /** Similar to symbols, so we can track entities */ - def id: Int - /** The name of the entity. Note that the name does not qualify this entity uniquely; use its `qualifiedName` * instead. */ def name : String @@ -59,9 +55,6 @@ trait Entity { /** Indicates whether this entity lives in the types namespace (classes, traits, abstract/alias types) */ def isType: Boolean - - /** Indicates whether this entity lives in the terms namespace (objects, packages, methods, values) */ - def isTerm: Boolean } object Entity { @@ -97,9 +90,6 @@ trait TemplateEntity extends Entity { /** Whether documentation is available for this template. */ def isDocTemplate: Boolean - /** Whether documentation is available for this template. */ - def isNoDocMemberTemplate: Boolean - /** Whether this template is a case class. */ def isCaseClass: Boolean @@ -174,12 +164,6 @@ trait MemberEntity extends Entity { /** Whether this member is an abstract type. */ def isAbstractType: Boolean - /** Whether this member is a template. */ - def isTemplate: Boolean - - /** Whether this member is implicit. */ - def isImplicit: Boolean - /** Whether this member is abstract. */ def isAbstract: Boolean @@ -381,14 +365,9 @@ trait RootPackage extends Package /** A non-template member (method, value, lazy value, variable, constructor, alias type, and abstract type). */ trait NonTemplateMemberEntity extends MemberEntity { - /** Whether this member is a use case. A use case is a member which does not exist in the documented code. * It corresponds to a real member, and provides a simplified, yet compatible signature for that member. */ def isUseCase: Boolean - - /** 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 } @@ -503,12 +482,6 @@ trait ImplicitConversion { /** The result type after the conversion */ def targetType: TypeEntity - /** The result type after the conversion - * 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] - /** 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 10e2f23142..1d6063255d 100755 --- a/src/compiler/scala/tools/nsc/doc/model/IndexModelFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/model/IndexModelFactory.scala @@ -17,8 +17,6 @@ object IndexModelFactory { object result extends mutable.HashMap[Char,SymbolMap] { - /* Owner template ordering */ - 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 f11f090b4b..96ecf51e44 100644 --- a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala @@ -43,11 +43,6 @@ 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 - } - def makeModel: Option[Universe] = { val universe = new Universe { thisUniverse => thisFactory.universe = thisUniverse @@ -77,7 +72,6 @@ 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 name = optimize(sym.nameString) val universe = thisFactory.universe @@ -91,7 +85,6 @@ 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 } trait TemplateImpl extends EntityImpl with TemplateEntity { @@ -103,7 +96,6 @@ 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 selfType = if (sym.thisSym eq sym) None else Some(makeType(sym.thisSym.typeOfThis, this)) } @@ -178,9 +170,7 @@ 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 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 +185,6 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { def isVal = false def isLazyVal = false def isVar = false - def isImplicit = sym.isImplicit def isConstructor = false def isAliasType = false def isAbstractType = false @@ -203,7 +192,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 signature = externalSignature(sym) lazy val signatureCompat = { @@ -257,25 +246,10 @@ 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 def isDocTemplate = false - 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 */ - // Seems unused - // def parentTemplates = - // if (sym.isPackage || sym == AnyClass) - // List() - // else - // sym.tpe.parents.flatMap { tpe: Type => - // val tSym = tpe.typeSymbol - // if (tSym != NoSymbol) - // List(makeTemplate(tSym)) - // else - // List() - // } filter (_.isInstanceOf[DocTemplateEntity]) - def parentTypes = if (sym.isPackage || sym == AnyClass) List() else { val tps = (this match { @@ -380,9 +354,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) - var memberSymsLazy = memberSyms.filter(t => templateShouldDocument(t, this) && !inOriginalOwner(t, this)) + val memberSymsLazy = memberSyms.filter(t => templateShouldDocument(t, this) && !inOriginalOwner(t, this)) // the direct members (methods, values, vars, types and directly contained templates) - var memberSymsEager = memberSyms.filter(!memberSymsLazy.contains(_)) + val memberSymsEager = memberSyms.filter(!memberSymsLazy.contains(_)) // the members generated by the symbols in memberSymsEager val ownMembers = (memberSymsEager.flatMap(makeMember(_, None, this))) @@ -438,7 +412,6 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { else List() ) - override def isTemplate = true override def isDocTemplate = true private[this] lazy val companionSymbol = if (sym.isAliasType || sym.isAbstractType) { @@ -545,7 +518,6 @@ 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 isUseCase = useCaseOf.isDefined override def byConversion: Option[ImplicitConversionImpl] = conversion override def isImplicitlyInherited = { assert(modelFinished); conversion.isDefined } @@ -707,7 +679,6 @@ 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 isRootPackage = true override lazy val memberSyms = (bSym.info.members ++ EmptyPackage.info.members).toList filter { s => @@ -857,12 +828,6 @@ 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 } - } - def findTemplateMaybe(aSym: Symbol): Option[DocTemplateImpl] = { assert(modelFinished) docTemplatesCache.get(normalizeTemplate(aSym)).filterNot(packageDropped(_)) diff --git a/src/compiler/scala/tools/nsc/doc/model/ModelFactoryImplicitSupport.scala b/src/compiler/scala/tools/nsc/doc/model/ModelFactoryImplicitSupport.scala index c1ca8c1448..015fce294e 100644 --- a/src/compiler/scala/tools/nsc/doc/model/ModelFactoryImplicitSupport.scala +++ b/src/compiler/scala/tools/nsc/doc/model/ModelFactoryImplicitSupport.scala @@ -345,15 +345,6 @@ 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 targetTypeComponents: List[(TemplateEntity, TypeEntity)] = makeParentTypes(toType, None, inTpl) def convertorMethod: Either[MemberEntity, String] = { @@ -492,14 +483,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 3e172544dd..736727fc1a 100644 --- a/src/compiler/scala/tools/nsc/doc/model/comment/Comment.scala +++ b/src/compiler/scala/tools/nsc/doc/model/comment/Comment.scala @@ -102,9 +102,6 @@ abstract class Comment { /** A usage example related to the entity. */ def example: List[Body] - /** The comment as it appears in the source text. */ - 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 9617b15068..c798def4cb 100644 --- a/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala @@ -28,11 +28,6 @@ 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 comment(sym: global.Symbol, currentTpl: Option[DocTemplateImpl], inTpl: DocTemplateImpl): Option[Comment] = { val key = (sym, inTpl) if (commentCache isDefinedAt key) @@ -132,7 +127,6 @@ trait CommentFactory { thisFactory: ModelFactory with CommentFactory with Member val note = note0 val example = example0 val constructor = constructor0 - val source = source0 val inheritDiagram = inheritDiagram0 val contentDiagram = contentDiagram0 val groupDesc = groupDesc0 @@ -957,20 +951,6 @@ 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(pred: => Boolean): Int = { var count = 0 while (!pred && char != endOfText) { 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 c2aa1f17f3..150b293b81 100644 --- a/src/compiler/scala/tools/nsc/doc/model/diagram/Diagram.scala +++ b/src/compiler/scala/tools/nsc/doc/model/diagram/Diagram.scala @@ -36,20 +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 } } 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 } abstract class Node { @@ -142,5 +134,4 @@ class ContentDiagramDepth(pack: ContentDiagram) extends DepthInfo { } val maxDepth = _maxDepth - def nodeDepth(node: Node) = _nodeDepth.getOrElse(node, -1) -} \ No newline at end of file +} -- cgit v1.2.3 From 69d850c8993765e4b3008f8bcc99b90937df9ffb Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Tue, 13 Nov 2012 08:34:06 -0800 Subject: Remove code from misc bits of the compiler. They are everywhere. They defy categorization. They are... M I S C --- src/compiler/scala/tools/ant/sabbus/Settings.scala | 2 +- src/compiler/scala/tools/cmd/FromString.scala | 9 +-------- src/compiler/scala/tools/cmd/Reference.scala | 1 - .../scala/tools/reflect/ToolBoxFactory.scala | 3 --- src/compiler/scala/tools/util/Javap.scala | 8 -------- src/compiler/scala/tools/util/PathResolver.scala | 23 +++------------------- .../scala/util/continuations/ControlContext.scala | 4 ++-- .../library/scala/util/continuations/package.scala | 6 +++--- src/detach/plugin/scala/tools/detach/Detach.scala | 2 +- 9 files changed, 11 insertions(+), 47 deletions(-) (limited to 'src/compiler/scala/tools') diff --git a/src/compiler/scala/tools/ant/sabbus/Settings.scala b/src/compiler/scala/tools/ant/sabbus/Settings.scala index fde61e9564..d0fefdaa03 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, Reference} +import org.apache.tools.ant.types.Path class Settings { diff --git a/src/compiler/scala/tools/cmd/FromString.scala b/src/compiler/scala/tools/cmd/FromString.scala index 2a624875ee..433bbb167e 100644 --- a/src/compiler/scala/tools/cmd/FromString.scala +++ b/src/compiler/scala/tools/cmd/FromString.scala @@ -24,18 +24,11 @@ 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)) + // We need this because we clash with the String => Path implicits. 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 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 d4f2060f81..ec2a414065 100644 --- a/src/compiler/scala/tools/cmd/Reference.scala +++ b/src/compiler/scala/tools/cmd/Reference.scala @@ -26,7 +26,6 @@ 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 expandArg(arg: String) = expansionMap.getOrElse(fromOpt(arg), List(arg)) diff --git a/src/compiler/scala/tools/reflect/ToolBoxFactory.scala b/src/compiler/scala/tools/reflect/ToolBoxFactory.scala index f0c88eadea..b1d343cee9 100644 --- a/src/compiler/scala/tools/reflect/ToolBoxFactory.scala +++ b/src/compiler/scala/tools/reflect/ToolBoxFactory.scala @@ -392,9 +392,6 @@ 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 parse(code: String): u.Tree = { if (compiler.settings.verbose.value) println("parsing "+code) val ctree: compiler.Tree = compiler.parse(code) diff --git a/src/compiler/scala/tools/util/Javap.scala b/src/compiler/scala/tools/util/Javap.scala index 4d94581cc1..381dbd1d87 100644 --- a/src/compiler/scala/tools/util/Javap.scala +++ b/src/compiler/scala/tools/util/Javap.scala @@ -107,19 +107,11 @@ 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()) - sealed trait JpResult { type ResultType def isError: Boolean def value: ResultType def show(): Unit - // todo - // def header(): String - // def fields(): List[String] - // def methods(): List[String] - // def signatures(): List[String] } class JpError(msg: String) extends JpResult { type ResultType = String diff --git a/src/compiler/scala/tools/util/PathResolver.scala b/src/compiler/scala/tools/util/PathResolver.scala index 6b0821edf3..5d79a7d6cd 100644 --- a/src/compiler/scala/tools/util/PathResolver.scala +++ b/src/compiler/scala/tools/util/PathResolver.scala @@ -18,16 +18,9 @@ import scala.language.postfixOps // https://wiki.scala-lang.org/display/SW/Classpath object PathResolver { - // Imports property/environment functions which suppress - // security exceptions. + // Imports property/environment functions which suppress security exceptions. import AccessControl._ - 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) - /** pretty print class path */ def ppcp(s: String) = split(s) match { case Nil => "" @@ -45,7 +38,6 @@ object PathResolver { /** Environment variables which java pays attention to so it * seems we do as well. */ - def classPathEnv = envOrElse("CLASSPATH", "") def sourcePathEnv = envOrElse("SOURCEPATH", "") def javaBootClassPath = propOrElse("sun.boot.class.path", searchForBootClasspath) @@ -85,7 +77,6 @@ object PathResolver { def scalaHome = Environment.scalaHome def scalaHomeDir = Directory(scalaHome) - def scalaHomeExists = scalaHomeDir.isDirectory def scalaLibDir = Directory(scalaHomeDir / "lib") def scalaClassesDir = Directory(scalaHomeDir / "classes") @@ -108,15 +99,7 @@ object PathResolver { // classpath as set up by the runner (or regular classpath under -nobootcp) // and then again here. def scalaBootClassPath = "" - // scalaLibDirFound match { - // case Some(dir) if scalaHomeExists => - // val paths = ClassPath expandDir dir.path - // join(paths: _*) - // case _ => "" - // } - def scalaExtDirs = Environment.scalaExtDirs - def scalaPluginPath = (scalaHomeDir / "misc" / "scala-devel" / "plugins").path override def toString = """ @@ -135,7 +118,7 @@ object PathResolver { ) } - def fromPathString(path: String, context: JavaContext = DefaultJavaContext): JavaClassPath = { + def fromPathString(path: String, context: JavaContext = DefaultJavaContext): JavaClassPath = { // called from scalap val s = new Settings() s.classpath.value = path new PathResolver(s, context) result @@ -160,7 +143,7 @@ object PathResolver { } } } -import PathResolver.{ Defaults, Environment, firstNonEmpty, ppcp } +import PathResolver.{ Defaults, Environment, ppcp } class PathResolver(settings: Settings, context: JavaContext) { def this(settings: Settings) = this(settings, if (settings.inline.value) new JavaContext else DefaultJavaContext) diff --git a/src/continuations/library/scala/util/continuations/ControlContext.scala b/src/continuations/library/scala/util/continuations/ControlContext.scala index 44a5b537b6..c196809da9 100644 --- a/src/continuations/library/scala/util/continuations/ControlContext.scala +++ b/src/continuations/library/scala/util/continuations/ControlContext.scala @@ -183,7 +183,7 @@ final class ControlContext[+A,-B,+C](val fun: (A => B, Exception => B) => C, val // need filter or other functions? - final def flatMapCatch[A1>:A,B1<:B,C1>:C<:B1](pf: PartialFunction[Exception, ControlContext[A1,B1,C1]]): ControlContext[A1,B1,C1] = { + final def flatMapCatch[A1>:A,B1<:B,C1>:C<:B1](pf: PartialFunction[Exception, ControlContext[A1,B1,C1]]): ControlContext[A1,B1,C1] = { // called by codegen from SelectiveCPSTransform if (fun eq null) this else { @@ -209,7 +209,7 @@ final class ControlContext[+A,-B,+C](val fun: (A => B, Exception => B) => C, val } } - final def mapFinally(f: () => Unit): ControlContext[A,B,C] = { + final def mapFinally(f: () => Unit): ControlContext[A,B,C] = { // called in code generated by SelectiveCPSTransform if (fun eq null) { try { f() diff --git a/src/continuations/library/scala/util/continuations/package.scala b/src/continuations/library/scala/util/continuations/package.scala index 1b50956c93..573fae85e7 100644 --- a/src/continuations/library/scala/util/continuations/package.scala +++ b/src/continuations/library/scala/util/continuations/package.scala @@ -166,7 +166,7 @@ package object continuations { throw new NoSuchMethodException("this code has to be compiled with the Scala continuations plugin enabled") } - def shiftUnitR[A,B](x: A): ControlContext[A,B,B] = { + def shiftUnitR[A,B](x: A): ControlContext[A,B,B] = { // called in code generated by SelectiveCPSTransform new ControlContext[A, B, B](null, x) } @@ -176,11 +176,11 @@ package object continuations { * a final result. * @see shift */ - def shiftR[A,B,C](fun: (A => B) => C): ControlContext[A,B,C] = { + def shiftR[A,B,C](fun: (A => B) => C): ControlContext[A,B,C] = { // called in code generated by SelectiveCPSTransform new ControlContext((f:A=>B,g:Exception=>B) => fun(f), null.asInstanceOf[A]) } - def reifyR[A,B,C](ctx: => ControlContext[A,B,C]): ControlContext[A,B,C] = { + def reifyR[A,B,C](ctx: => ControlContext[A,B,C]): ControlContext[A,B,C] = { // called in code generated by SelectiveCPSTransform ctx } diff --git a/src/detach/plugin/scala/tools/detach/Detach.scala b/src/detach/plugin/scala/tools/detach/Detach.scala index 73f6cde58c..499a97b761 100644 --- a/src/detach/plugin/scala/tools/detach/Detach.scala +++ b/src/detach/plugin/scala/tools/detach/Detach.scala @@ -73,7 +73,7 @@ abstract class Detach extends PluginComponent } private val serializableAnnotationInfo = - AnnotationInfo(SerializableAttr.tpe, List(), List()) + AnnotationInfo(requiredClass[scala.annotation.serializable].tpe, List(), List()) /* private val throwsAnnotationInfo = { val RemoteExceptionClass = definitions.getClass("java.rmi.RemoteException") -- cgit v1.2.3 From 373ded2ad31e6c9d85a6e3ca40774913ba2ab4f9 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Tue, 13 Nov 2012 08:35:21 -0800 Subject: Remove code from compiler central. All those old-timey methods whose melodies have become unfashionable. --- .../scala/tools/nsc/CompilationUnits.scala | 25 +---- src/compiler/scala/tools/nsc/CompileServer.scala | 2 - src/compiler/scala/tools/nsc/CompilerCommand.scala | 5 - src/compiler/scala/tools/nsc/Global.scala | 84 ++-------------- src/compiler/scala/tools/nsc/ObjectRunner.scala | 5 - src/compiler/scala/tools/nsc/Phases.scala | 2 - src/compiler/scala/tools/nsc/Properties.scala | 1 - src/compiler/scala/tools/nsc/ScriptRunner.scala | 2 - src/compiler/scala/tools/nsc/ast/Printers.scala | 79 --------------- src/compiler/scala/tools/nsc/ast/TreeDSL.scala | 57 +---------- src/compiler/scala/tools/nsc/ast/TreeGen.scala | 94 ------------------ src/compiler/scala/tools/nsc/ast/TreeInfo.scala | 5 - .../scala/tools/nsc/ast/parser/Parsers.scala | 22 +---- .../scala/tools/nsc/ast/parser/Scanners.scala | 42 +------- .../scala/tools/nsc/ast/parser/Tokens.scala | 38 +------- .../scala/tools/nsc/ast/parser/TreeBuilder.scala | 16 ---- .../scala/tools/nsc/interactive/BuildManager.scala | 5 - .../scala/tools/nsc/interactive/Global.scala | 35 ------- src/compiler/scala/tools/nsc/io/Jar.scala | 9 -- src/compiler/scala/tools/nsc/io/MsilFile.scala | 5 +- src/compiler/scala/tools/nsc/io/Pickler.scala | 82 ---------------- src/compiler/scala/tools/nsc/io/Socket.scala | 5 +- src/compiler/scala/tools/nsc/io/SourceReader.scala | 3 - src/compiler/scala/tools/nsc/io/package.scala | 16 ---- .../scala/tools/nsc/javac/JavaParsers.scala | 46 +-------- .../scala/tools/nsc/javac/JavaScanners.scala | 37 ------- .../scala/tools/nsc/javac/JavaTokens.scala | 6 -- .../scala/tools/nsc/matching/MatchSupport.scala | 20 ---- src/compiler/scala/tools/nsc/matching/Matrix.scala | 27 ------ .../tools/nsc/matching/ParallelMatching.scala | 6 +- .../scala/tools/nsc/matching/PatternBindings.scala | 7 -- .../scala/tools/nsc/matching/Patterns.scala | 36 +------ .../scala/tools/nsc/settings/AbsSettings.scala | 11 +-- .../scala/tools/nsc/settings/MutableSettings.scala | 10 +- .../scala/tools/nsc/settings/ScalaSettings.scala | 8 +- .../tools/nsc/settings/StandardScalaSettings.scala | 5 - .../scala/tools/nsc/settings/Warnings.scala | 15 +-- .../nsc/symtab/classfile/AbstractFileReader.scala | 7 +- .../nsc/symtab/classfile/ClassfileParser.scala | 14 --- .../tools/nsc/symtab/classfile/ICodeReader.scala | 6 +- .../scala/tools/nsc/symtab/classfile/Pickler.scala | 106 --------------------- .../tools/nsc/transform/SpecializeTypes.scala | 27 +----- .../scala/tools/nsc/transform/TailCalls.scala | 1 - .../tools/nsc/transform/TypingTransformers.scala | 2 - src/compiler/scala/tools/nsc/util/ClassPath.scala | 35 ------- .../scala/tools/nsc/util/CommandLineParser.scala | 4 - .../scala/tools/nsc/util/JavaCharArrayReader.scala | 57 +---------- .../scala/tools/nsc/util/ScalaClassLoader.scala | 43 --------- .../scala/tools/nsc/util/SimpleTracer.scala | 1 - src/compiler/scala/tools/nsc/util/package.scala | 20 ---- src/reflect/scala/reflect/internal/Names.scala | 4 +- src/reflect/scala/reflect/internal/TreeGen.scala | 2 +- 52 files changed, 56 insertions(+), 1146 deletions(-) (limited to 'src/compiler/scala/tools') diff --git a/src/compiler/scala/tools/nsc/CompilationUnits.scala b/src/compiler/scala/tools/nsc/CompilationUnits.scala index 5be819c134..663fbeceb0 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 */ - var fresh: FreshNameCreator = new FreshNameCreator.Default + val fresh: FreshNameCreator = new FreshNameCreator.Default def freshTermName(prefix: String): TermName = newTermName(fresh.newName(prefix)) def freshTypeName(prefix: String): TypeName = newTypeName(fresh.newName(prefix)) @@ -36,16 +36,6 @@ trait CompilationUnits { self: Global => def exists = source != NoSourceFile && source != null -// def parseSettings() = { -// val argsmarker = "SCALAC_ARGS" -// if(comments nonEmpty) { -// val pragmas = comments find (_.text.startsWith("//#")) // only parse first one -// pragmas foreach { p => -// val i = p.text.indexOf(argsmarker) -// if(i > 0) -// } -// } -// } /** Note: depends now contains toplevel classes. * To get their sourcefiles, you need to dereference with .sourcefile */ @@ -107,18 +97,5 @@ trait CompilationUnits { self: Global => lazy val isJava = source.file.name.endsWith(".java") 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() - } } } - - diff --git a/src/compiler/scala/tools/nsc/CompileServer.scala b/src/compiler/scala/tools/nsc/CompileServer.scala index 521f788fa1..f79990d526 100644 --- a/src/compiler/scala/tools/nsc/CompileServer.scala +++ b/src/compiler/scala/tools/nsc/CompileServer.scala @@ -29,8 +29,6 @@ class StandardCompileServer extends SocketServer { var shutdown = false var verbose = false - val versionMsg = "Fast " + Properties.versionMsg - val MaxCharge = 0.8 private val runtime = Runtime.getRuntime() diff --git a/src/compiler/scala/tools/nsc/CompilerCommand.scala b/src/compiler/scala/tools/nsc/CompilerCommand.scala index 829e097714..0462e69f74 100644 --- a/src/compiler/scala/tools/nsc/CompilerCommand.scala +++ b/src/compiler/scala/tools/nsc/CompilerCommand.scala @@ -14,9 +14,6 @@ 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 - private val processArgumentsResult = if (shouldProcessArguments) processArguments else (true, Nil) @@ -40,8 +37,6 @@ 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 "" /** 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/Global.scala b/src/compiler/scala/tools/nsc/Global.scala index 13bec828ca..1574be8d86 100644 --- a/src/compiler/scala/tools/nsc/Global.scala +++ b/src/compiler/scala/tools/nsc/Global.scala @@ -70,8 +70,6 @@ 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 picklerPhase: Phase = if (currentRun.isDefined) currentRun.picklerPhase else NoPhase // platform specific elements @@ -265,15 +263,10 @@ 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 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)) - } - override def shouldLogAtThisPhase = settings.log.isSetByUser && ( (settings.log containsPhase globalPhase) || (settings.log containsPhase phase) ) @@ -419,8 +412,8 @@ class Global(var currentSettings: Settings, var reporter: Reporter) } /** Switch to turn on detailed type logs */ - var printTypings = settings.Ytyperdebug.value - var printInfers = settings.Yinferdebug.value + val printTypings = settings.Ytyperdebug.value + val printInfers = settings.Yinferdebug.value // phaseName = "parser" object syntaxAnalyzer extends { @@ -638,13 +631,6 @@ 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 - /** The checkers are for validating the compiler data structures * at phase boundaries. */ @@ -778,7 +764,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)] = { + def afterEachPhase[T](op: => T): List[(Phase, T)] = { // used in tests 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 @@ -786,40 +772,8 @@ class Global(var currentSettings: Settings, var reporter: Reporter) } reverse } - /** Returns List of ChangeAfterPhase objects, encapsulating those - * 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 - } private def numberedPhase(ph: Phase) = "%2d/%s".format(ph.id, ph.name) - case class ChangeAfterPhase[+T](ph: Phase, lost: List[T], gained: List[T]) { - private def mkStr(what: String, xs: List[_]) = ( - if (xs.isEmpty) "" - else xs.mkString(what + " after " + numberedPhase(ph) + " {\n ", "\n ", "\n}\n") - ) - 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 describeAfterEveryPhase[T](op: => T): String = - describeAfterEachPhase(op) map (" " + _ + "\n") mkString - - def printAfterEachPhase[T](op: => T): Unit = - describeAfterEachPhase(op) foreach (m => println(" " + m)) - // ------------ Invalidations --------------------------------- /** Is given package class a system package class that cannot be invalidated? @@ -1057,7 +1011,6 @@ 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 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 +1024,9 @@ 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 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) - ) - ) - ) // Owners up to and including the first package class. private def ownerChainString(sym: Symbol): String = ( if (sym == null) "" @@ -1098,9 +1039,6 @@ 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( - ) - /** Don't want to introduce new errors trying to report errors, * so swallow exceptions. */ @@ -1158,7 +1096,6 @@ 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 newCompilationUnit(code: String) = new CompilationUnit(newSourceFile(code)) def newSourceFile(code: String) = new BatchSourceFile("", code) @@ -1181,9 +1118,8 @@ class Global(var currentSettings: Settings, var reporter: Reporter) val inlinerWarnings = new ConditionalWarning("inliner", settings.YinlinerWarnings) val allConditionalWarnings = List(deprecationWarnings0, uncheckedWarnings0, featureWarnings, inlinerWarnings) - // for sbt's benefit - def uncheckedWarnings: List[(Position, String)] = uncheckedWarnings0.warnings.toList - def deprecationWarnings: List[(Position, String)] = deprecationWarnings0.warnings.toList + def uncheckedWarnings: List[(Position, String)] = uncheckedWarnings0.warnings.toList // used in sbt + def deprecationWarnings: List[(Position, String)] = deprecationWarnings0.warnings.toList // used in sbt var reportedFeature = Set[Symbol]() @@ -1350,7 +1286,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") @@ -1363,7 +1299,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") @@ -1373,12 +1309,10 @@ 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 runIsAtBytecodeGen = (runIsAt(jvmPhase) || runIsAt(msilPhase)) def runIsAtOptimiz = { runIsAt(inlinerPhase) || // listing phases in full for robustness when -Ystop-after has been given. runIsAt(inlineExceptionHandlersPhase) || @@ -1743,7 +1677,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 3c75429311..95264aeda6 100644 --- a/src/compiler/scala/tools/nsc/ObjectRunner.scala +++ b/src/compiler/scala/tools/nsc/ObjectRunner.scala @@ -11,11 +11,6 @@ import util.ScalaClassLoader 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) - /** 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 aad70a9c5e..1266622b6d 100644 --- a/src/compiler/scala/tools/nsc/Phases.scala +++ b/src/compiler/scala/tools/nsc/Phases.scala @@ -20,7 +20,6 @@ object Phases { } val values = new Array[Cell](MaxPhases + 1) def results = values filterNot (_ == null) - 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 +37,6 @@ object Phases { >> ("ms" -> (_.value)) >+ " " << ("share" -> (_.value.toDouble * 100 / total formatted "%.2f")) } - def formatted = "" + table() } } diff --git a/src/compiler/scala/tools/nsc/Properties.scala b/src/compiler/scala/tools/nsc/Properties.scala index 55fd196716..570d5572d6 100644 --- a/src/compiler/scala/tools/nsc/Properties.scala +++ b/src/compiler/scala/tools/nsc/Properties.scala @@ -21,5 +21,4 @@ object Properties extends scala.util.PropertiesTrait { // derived values def isEmacsShell = propOrEmpty("env.emacs") != "" - def fileEndings = fileEndingString.split("""\|""").toList } diff --git a/src/compiler/scala/tools/nsc/ScriptRunner.scala b/src/compiler/scala/tools/nsc/ScriptRunner.scala index 0b307a861e..92b2dc79ed 100644 --- a/src/compiler/scala/tools/nsc/ScriptRunner.scala +++ b/src/compiler/scala/tools/nsc/ScriptRunner.scala @@ -48,8 +48,6 @@ class ScriptRunner extends HasCompileSocket { case x => x } - 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( if (scriptFile endsWith ".jar") scriptFile diff --git a/src/compiler/scala/tools/nsc/ast/Printers.scala b/src/compiler/scala/tools/nsc/ast/Printers.scala index 0414e0f123..b9f348632a 100644 --- a/src/compiler/scala/tools/nsc/ast/Printers.scala +++ b/src/compiler/scala/tools/nsc/ast/Printers.scala @@ -200,91 +200,12 @@ 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 newCompactTreePrinter(writer: PrintWriter): CompactTreePrinter = new CompactTreePrinter(writer) - 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 3acefe9441..e8bc932bf5 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeDSL.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeDSL.scala @@ -84,16 +84,12 @@ 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_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.GE), other) def INT_== (other: Tree) = fn(target, getMember(IntClass, nme.EQ), 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,9 +97,6 @@ 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) - /** Apply, Select, Match **/ def APPLY(params: Tree*) = Apply(target, params.toList) def APPLY(params: List[Tree]) = Apply(target, params) @@ -129,8 +122,6 @@ trait TreeDSL { def IS(tpe: Type) = gen.mkIsInstanceOf(target, tpe, true) def IS_OBJ(tpe: Type) = gen.mkIsInstanceOf(target, tpe, false) - // XXX having some difficulty expressing nullSafe in a way that doesn't freak out value types - // def TOSTRING() = nullSafe(fn(_: Tree, nme.toString_), LIT("null"))(target) def TOSTRING() = fn(target, nme.toString_) def GETCLASS() = fn(target, Object_getClass) } @@ -158,7 +149,6 @@ trait TreeDSL { def mkTree(rhs: Tree): ResultTreeType def ===(rhs: Tree): ResultTreeType - private var _mods: Modifiers = null private var _tpt: Tree = null private var _pos: Position = null @@ -166,19 +156,12 @@ trait TreeDSL { _tpt = TypeTree(tp) this } - def withFlags(flags: Long*): this.type = { - if (_mods == null) - _mods = defaultMods - - _mods = flags.foldLeft(_mods)(_ | _) - this - } def withPos(pos: Position): this.type = { _pos = pos this } - final def mods = if (_mods == null) defaultMods else _mods + final def mods = defaultMods final def tpt = if (_tpt == null) defaultTpt else _tpt final def pos = if (_pos == null) defaultPos else _pos } @@ -243,7 +226,6 @@ 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 ENDTRY = Try(body, catches, fin) } @@ -251,16 +233,9 @@ trait TreeDSL { def DEFAULT: CaseStart = new CaseStart(WILD.empty, EmptyTree) class SymbolMethods(target: Symbol) { - def BIND(body: Tree) = Bind(target, body) - def IS_NULL() = REF(target) OBJ_EQ 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 ARGS = target.paramss.head - def ARGNAMES = ARGS map Ident + def IS_NULL() = REF(target) OBJ_EQ NULL + def GET() = fn(REF(target), nme.get) + def ARGS = target.paramss.head } /** Top level accessible. */ @@ -268,32 +243,13 @@ 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 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(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 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 IF(tree: Tree) = new IfStart(tree, EmptyTree) def TRY(tree: Tree) = new TryStart(tree, Nil, EmptyTree) def BLOCK(xs: Tree*) = Block(xs.init.toList, xs.last) @@ -311,11 +267,6 @@ 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) - } /** 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 983f355c58..1adcf46958 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeGen.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeGen.scala @@ -62,72 +62,6 @@ abstract class TreeGen extends scala.reflect.internal.TreeGen with TreeDSL { // are very picky about things and it crashes the compiler with "unexpected new". 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 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 - ) - } // Builds a tree of the form "{ lhs = rhs ; lhs }" def mkAssignAndReturn(lhs: Symbol, rhs: Tree): Tree = { @@ -150,11 +84,6 @@ abstract class TreeGen extends scala.reflect.internal.TreeGen with TreeDSL { ValDef(mval) } - // 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 mkModuleAccessDef(accessor: Symbol, msym: Symbol) = DefDef(accessor, Select(This(msym.owner), msym)) @@ -164,10 +93,6 @@ abstract class TreeGen extends scala.reflect.internal.TreeGen with TreeDSL { else New(tpe, This(accessor.owner.enclClass)) } - // def m: T; - def mkModuleAccessDcl(accessor: Symbol) = - DefDef(accessor setFlag lateDEFERRED, EmptyTree) - def mkRuntimeCall(meth: Name, args: List[Tree]): Tree = mkRuntimeCall(meth, Nil, args) @@ -264,25 +189,6 @@ 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 - } - /** Translate names in Select/Ident nodes to type names. */ def convertToTypeName(tree: Tree): Option[RefTree] = tree match { diff --git a/src/compiler/scala/tools/nsc/ast/TreeInfo.scala b/src/compiler/scala/tools/nsc/ast/TreeInfo.scala index 97227a5b6e..f53f99a279 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeInfo.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeInfo.scala @@ -6,8 +6,6 @@ package scala.tools.nsc package ast -import scala.reflect.internal.HasFlags - /** This class ... * * @author Martin Odersky @@ -38,7 +36,4 @@ abstract class TreeInfo extends scala.reflect.internal.TreeInfo { case ClassDef(_, `name`, _, _) :: Nil => true case _ => super.firstDefinesClassOrObject(trees, name) } - - 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 c934f34398..f430f1fc34 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala @@ -9,7 +9,8 @@ package scala.tools.nsc package ast.parser -import scala.collection.mutable.{ListBuffer, StringBuilder} +import scala.collection.{ mutable, immutable } +import mutable.{ ListBuffer, StringBuilder } import scala.reflect.internal.{ ModifierFlags => Flags } import scala.reflect.internal.Chars.{ isScalaLetter } import scala.reflect.internal.util.{ SourceFile, OffsetPosition } @@ -167,7 +168,6 @@ 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 xmlLiteral : Tree = xmlp.xLiteral @@ -463,7 +463,7 @@ self => /* ------------- ERROR HANDLING ------------------------------------------- */ - var assumedClosingParens = scala.collection.mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0) + val assumedClosingParens = mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0) private var inFunReturnType = false @inline private def fromWithinReturnType[T](body: => T): T = { @@ -640,8 +640,6 @@ self => case _ => false } - def isTypeIntro: Boolean = isTypeIntroToken(in.token) - def isStatSeqEnd = in.token == RBRACE || in.token == EOF def isStatSep(token: Int): Boolean = @@ -765,10 +763,6 @@ self => } } - 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) syntaxError( @@ -1214,15 +1208,6 @@ self => /* ----------- EXPRESSIONS ------------------------------------------------ */ - /** {{{ - * EqualsExpr ::= `=' Expr - * }}} - */ - def equalsExpr(): Tree = { - accept(EQUALS) - expr() - } - def condExpr(): Tree = { if (in.token == LPAREN) { in.nextToken() @@ -1964,7 +1949,6 @@ self => /** Default entry points into some pattern contexts. */ def pattern(): Tree = noSeq.pattern() - 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 1be5fb1782..af7f48988f 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala @@ -10,7 +10,8 @@ import scala.reflect.internal.util._ import scala.reflect.internal.Chars._ import Tokens._ import scala.annotation.switch -import scala.collection.mutable.{ ListBuffer, ArrayBuffer } +import scala.collection.{ mutable, immutable } +import mutable.{ ListBuffer, ArrayBuffer } import scala.xml.Utility.{ isNameStart } /** See Parsers.scala / ParsersCommon for some explanation of ScannersCommon. @@ -26,7 +27,6 @@ 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 error (off: Int, msg: String): Unit def incompleteInputError(off: Int, msg: String): Unit def deprecationWarning(off: Int, msg: String): Unit @@ -50,9 +50,6 @@ trait Scanners extends ScannersCommon { /** Offset into source character array */ type Offset = Int - /** An undefined offset */ - val NoOffset: Offset = -1 - trait TokenData extends CommonTokenData { /** the next token */ @@ -88,8 +85,6 @@ trait Scanners extends ScannersCommon { def isAtEnd = charOffset >= buf.length - def flush = { charOffset = offset; nextChar(); this } - def resume(lastCode: Int) = { token = lastCode if (next.token != EMPTY && !reporter.hasErrors) @@ -98,10 +93,6 @@ trait Scanners extends ScannersCommon { nextToken() } - /** the last error offset - */ - var errOffset: Offset = NoOffset - /** A character buffer for literals */ val cbuf = new StringBuilder @@ -1063,7 +1054,6 @@ trait Scanners extends ScannersCommon { def syntaxError(off: Offset, msg: String) { error(off, msg) token = ERROR - errOffset = off } /** generate an error at the current token offset @@ -1076,7 +1066,6 @@ trait Scanners extends ScannersCommon { def incompleteInputError(msg: String) { incompleteInputError(offset, msg) token = EOF - errOffset = offset } override def toString() = token match { @@ -1241,7 +1230,6 @@ 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 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) @@ -1252,7 +1240,6 @@ 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 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) @@ -1311,7 +1298,7 @@ trait Scanners extends ScannersCommon { } class ParensAnalyzer(unit: CompilationUnit, patches: List[BracePatch]) extends UnitScanner(unit, patches) { - var balance = scala.collection.mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0) + val balance = mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0) init() @@ -1433,18 +1420,6 @@ trait Scanners extends ScannersCommon { else bp :: insertPatch(bps, patch) } - 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 insertRBrace(): List[BracePatch] = { def insert(bps: List[BracePair]): List[BracePatch] = bps match { case List() => patches @@ -1486,17 +1461,6 @@ 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 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 c3fd414426..5a7dc4950d 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala @@ -6,15 +6,11 @@ package scala.tools.nsc package ast.parser -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._ - /** special tokens */ final val EMPTY = -3 final val UNDEF = -2 @@ -34,14 +30,6 @@ abstract class Tokens { 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) } object Tokens extends Tokens { @@ -52,20 +40,10 @@ object Tokens extends Tokens { def isLiteral(code: Int) = code >= CHARLIT && code <= INTERPOLATIONID - /** identifiers */ final val IDENTIFIER = 10 final val BACKQUOTED_IDENT = 11 - 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) - } + def isIdentifier(code: Int) = code >= IDENTIFIER && code <= BACKQUOTED_IDENT // used by ide /** keywords */ final val IF = 20 @@ -113,17 +91,6 @@ 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 - - @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 final val SEMI = 71 @@ -141,9 +108,6 @@ object Tokens extends Tokens { final val AT = 83 final val VIEWBOUND = 84 - def isSymbol(code: Int) = - code >= COMMA && code <= VIEWBOUND - /** parenthesis */ final val LPAREN = 90 final val RPAREN = 91 diff --git a/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala b/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala index 49b772ed2c..d6c499d838 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala @@ -26,15 +26,11 @@ 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 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 scalaUnitConstr = scalaDot(tpnme.Unit) def productConstr = scalaDot(tpnme.Product) - def productConstrN(n: Int) = scalaDot(newTypeName("Product" + n)) def serializableConstr = scalaDot(tpnme.Serializable) def convertToTypeName(t: Tree) = gen.convertToTypeName(t) @@ -444,18 +440,6 @@ abstract class TreeBuilder { def makeForYield(enums: List[Enumerator], body: Tree): Tree = makeFor(nme.map, nme.flatMap, enums, body) - /** 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) - } - /** Create tree for a pattern alternative */ def makeAlternative(ts: List[Tree]): Tree = { def alternatives(t: Tree): List[Tree] = t match { diff --git a/src/compiler/scala/tools/nsc/interactive/BuildManager.scala b/src/compiler/scala/tools/nsc/interactive/BuildManager.scala index a3f76994bc..6b72eb12f8 100644 --- a/src/compiler/scala/tools/nsc/interactive/BuildManager.scala +++ b/src/compiler/scala/tools/nsc/interactive/BuildManager.scala @@ -15,9 +15,6 @@ trait BuildManager { /** Add the given source files to the managed build process. */ def addSourceFiles(files: Set[AbstractFile]) - /** Remove the given files from the managed build process. */ - def removeFiles(files: Set[AbstractFile]) - /** The given files have been modified by the user. Recompile * them and their dependent files. */ @@ -71,8 +68,6 @@ object BuildManagerTest extends EvalLoop { val settings = new Settings(buildError) settings.Ybuildmanagerdebug.value = true val command = new CompilerCommand(args.toList, settings) -// settings.make.value = "off" -// val buildManager: BuildManager = new SimpleBuildManager(settings) val buildManager: BuildManager = new RefinedBuildManager(settings) buildManager.addSourceFiles(command.files) diff --git a/src/compiler/scala/tools/nsc/interactive/Global.scala b/src/compiler/scala/tools/nsc/interactive/Global.scala index 4dedbcfd3d..e4bff1e192 100644 --- a/src/compiler/scala/tools/nsc/interactive/Global.scala +++ b/src/compiler/scala/tools/nsc/interactive/Global.scala @@ -395,41 +395,6 @@ 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 - } - // ----------------- The Background Runner Thread ----------------------- private var threadId = 0 diff --git a/src/compiler/scala/tools/nsc/io/Jar.scala b/src/compiler/scala/tools/nsc/io/Jar.scala index 3a9a878bc2..49a1ff114f 100644 --- a/src/compiler/scala/tools/nsc/io/Jar.scala +++ b/src/compiler/scala/tools/nsc/io/Jar.scala @@ -36,9 +36,6 @@ 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 - - lazy val jarFile = new JarFile(file.jfile) lazy val manifest = withJarInput(s => Option(s.getManifest)) def mainClass = manifest map (f => f(Name.MAIN_CLASS)) @@ -124,7 +121,6 @@ object Jar { m } def apply(manifest: JManifest): WManifest = new WManifest(manifest) - implicit def unenrichManifest(x: WManifest): JManifest = x.underlying } class WManifest(manifest: JManifest) { for ((k, v) <- initialMainAttrs) @@ -141,12 +137,7 @@ object Jar { } def apply(name: Attributes.Name): String = attrs(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 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 1a3a4f5c81..bda13a5ed0 100644 --- a/src/compiler/scala/tools/nsc/io/MsilFile.scala +++ b/src/compiler/scala/tools/nsc/io/MsilFile.scala @@ -12,7 +12,4 @@ import ch.epfl.lamp.compiler.msil.{ Type => MsilType } * ClassPath can treat all of JVM/MSIL/bin/src files * uniformly, as AbstractFiles. */ -class MsilFile(val msilType: MsilType) extends VirtualFile(msilType.FullName, msilType.Namespace) { -} - -object NoMsilFile extends MsilFile(null) { } +class MsilFile(val msilType: MsilType) extends VirtualFile(msilType.FullName, msilType.Namespace) { } diff --git a/src/compiler/scala/tools/nsc/io/Pickler.scala b/src/compiler/scala/tools/nsc/io/Pickler.scala index 56ff4a57ee..5d32c10143 100644 --- a/src/compiler/scala/tools/nsc/io/Pickler.scala +++ b/src/compiler/scala/tools/nsc/io/Pickler.scala @@ -70,14 +70,6 @@ abstract class Pickler[T] { */ def wrapped [U] (in: T => U)(out: U => T): Pickler[U] = wrappedPickler(this)(in)(out) - /** A pickler obtained from the current pickler by also admitting `null` as - * a handled value, represented as the token `null`. - * - * @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) - /** A conditional pickler obtained from the current pickler. * @param cond the condition to test to find out whether pickler can handle * some Scala value. @@ -92,9 +84,6 @@ abstract class Pickler[T] { } object Pickler { - - var picklerDebugMode = false - /** A base class representing unpickler result. It has two subclasses: * `UnpickleSucess` for successful unpicklings and `UnpickleFailure` for failures, * where a value of the given type `T` could not be unpickled from input. @@ -174,17 +163,6 @@ object Pickler { def ~ [T](y: T): S ~ T = new ~ (x, y) } - /** 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) } - - /** 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 } } - /** Same as `p.labelled(label)`. */ def labelledPickler[T](label: String, p: Pickler[T]): Pickler[T] = new Pickler[T] { @@ -248,16 +226,6 @@ object Pickler { def unpickle(rd: Lexer) = p.unpickle(rd) orElse qq.unpickle(rd) } - /** 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) - } - /** A conditional pickler for singleton objects. It represents these * with the object's underlying class as a label. * Example: Object scala.None would be represented as `scala.None$()`. @@ -329,22 +297,9 @@ object Pickler { implicit val longPickler: Pickler[Long] = 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 } - - /** A pickler for values of type `Byte`, represented as integer literals */ - 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 } - /** 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 } - /** A conditional pickler for the boolean value `true` */ private val truePickler = tokenPickler("boolean literal") { case TrueLit => true } cond { _ == true } @@ -372,52 +327,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 } - - /** 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") - /** 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)] = (p1 ~ p2 ~ p3) .wrapped { case x1 ~ x2 ~ x3 => (x1, x2, x3) } { case (x1, x2, x3) => x1 ~ x2 ~ x3 } .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") - - /** A conditional pickler for the `scala.None` object */ - 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]]) - - /** A pickler for optional values */ - 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") - - /** A pickler for array values */ - 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 e766c1b2fd..4925c50d85 100644 --- a/src/compiler/scala/tools/nsc/io/Socket.scala +++ b/src/compiler/scala/tools/nsc/io/Socket.scala @@ -28,13 +28,10 @@ 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 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 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 +59,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 af745eb3e8..ece78db2cf 100644 --- a/src/compiler/scala/tools/nsc/io/SourceReader.scala +++ b/src/compiler/scala/tools/nsc/io/SourceReader.scala @@ -33,9 +33,6 @@ class SourceReader(decoder: CharsetDecoder, reporter: Reporter) { "Please try specifying another one using the -encoding option") } - /** Reads the file with the specified name. */ - def read(filename: String): Array[Char]= read(new JFile(filename)) - /** Reads the specified file. */ def read(file: JFile): Array[Char] = { val c = new FileInputStream(file).getChannel diff --git a/src/compiler/scala/tools/nsc/io/package.scala b/src/compiler/scala/tools/nsc/io/package.scala index c29a7c96df..0b2db115fb 100644 --- a/src/compiler/scala/tools/nsc/io/package.scala +++ b/src/compiler/scala/tools/nsc/io/package.scala @@ -20,15 +20,11 @@ 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 Streamable = scala.reflect.io.Streamable type VirtualDirectory = scala.reflect.io.VirtualDirectory type VirtualFile = scala.reflect.io.VirtualFile - 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 - type JManifest = java.util.jar.Manifest type JFile = java.io.File @@ -38,23 +34,11 @@ 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 - // Create, start, and return a daemon thread - 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) thread.start thread } - - // 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 } - - 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 2f6c13dd67..73cbeaa6c4 100644 --- a/src/compiler/scala/tools/nsc/javac/JavaParsers.scala +++ b/src/compiler/scala/tools/nsc/javac/JavaParsers.scala @@ -35,7 +35,6 @@ trait JavaParsers extends ast.parser.ParsersCommon with JavaScanners { abstract class JavaParser extends ParserCommon { val in: JavaScanner - 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 +93,7 @@ trait JavaParsers extends ast.parser.ParsersCommon with JavaScanners { if (skipIt) skip() } - 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 // --------- tree building ----------------------------- @@ -178,11 +173,7 @@ trait JavaParsers extends ast.parser.ParsersCommon with JavaScanners { def accept(token: Int): Int = { val pos = in.currentPos if (in.token != token) { - val posToReport = - //if (in.currentPos.line(unit.source).get(0) > in.lastPos.line(unit.source).get(0)) - // in.lastPos - //else - in.currentPos + val posToReport = in.currentPos val msg = JavaScannerConfiguration.token2string(token) + " expected but " + JavaScannerConfiguration.token2string(in.token) + " found." @@ -352,41 +343,6 @@ trait JavaParsers extends ast.parser.ParsersCommon with JavaScanners { if (in.token == LPAREN) { skipAhead(); accept(RPAREN) } else if (in.token == LBRACE) { skipAhead(); accept(RBRACE) } } -/* - def annotationArg() = { - val pos = in.token - if (in.token == IDENTIFIER && in.lookaheadToken == ASSIGN) { - val name = ident() - accept(ASSIGN) - atPos(pos) { - ValDef(Modifiers(Flags.JAVA), name, TypeTree(), elementValue()) - } - } else { - elementValue() - } - } - - def elementValue(): Tree = - if (in.token == AT) annotation() - else if (in.token == LBRACE) elementValueArrayInitializer() - else expression1() - - def elementValueArrayInitializer() = { - accept(LBRACE) - val buf = new ListBuffer[Tree] - def loop() = - if (in.token != RBRACE) { - buf += elementValue() - if (in.token == COMMA) { - in.nextToken - loop() - } - } - loop() - accept(RBRACE) - buf.toList - } - */ def modifiers(inInterface: Boolean): Modifiers = { var flags: Long = Flags.JAVA diff --git a/src/compiler/scala/tools/nsc/javac/JavaScanners.scala b/src/compiler/scala/tools/nsc/javac/JavaScanners.scala index e230585a8b..84eee36f18 100644 --- a/src/compiler/scala/tools/nsc/javac/JavaScanners.scala +++ b/src/compiler/scala/tools/nsc/javac/JavaScanners.scala @@ -57,23 +57,14 @@ trait JavaScanners extends ast.parser.ScannersCommon { /** ... */ abstract class AbstractJavaScanner extends AbstractJavaTokenData { - 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 def nextToken(): Unit def next: AbstractJavaTokenData def intVal(negated: Boolean): Long def floatVal(negated: Boolean): Double def intVal: Long = intVal(false) def floatVal: Double = floatVal(false) - //def token2string(token : Int) : String = configuration.token2string(token) - /** return recent scala doc, if any */ - def flushDoc: DocComment def currentPos: Position } @@ -227,17 +218,9 @@ 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 def currentPos: Position = g2p(pos - 1) - var in: JavaCharArrayReader = _ - def dup: JavaScanner = { - val dup = clone().asInstanceOf[JavaScanner] - dup.in = in.dup - dup - } - /** character buffer for literals */ val cbuf = new StringBuilder() @@ -256,12 +239,6 @@ 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 - } - /** add the given character to the documentation buffer */ protected def putDocChar(c: Char) { @@ -277,13 +254,6 @@ trait JavaScanners extends ast.parser.ScannersCommon { // Get next token ------------------------------------------------------------ - /** read next token and return last position - */ - def skipToken: Int = { - val p = pos; nextToken - p - 1 - } - def nextToken() { if (next.token == EMPTY) { fetchToken() @@ -308,7 +278,6 @@ trait JavaScanners extends ast.parser.ScannersCommon { private def fetchToken() { if (token == EOF) return lastPos = in.cpos - 1 - //var index = bp while (true) { in.ch match { case ' ' | '\t' | CR | LF | FF => @@ -868,7 +837,6 @@ trait JavaScanners extends ast.parser.ScannersCommon { def syntaxError(pos: Int, msg: String) { error(pos, msg) token = ERROR - errpos = pos } /** generate an error at the current token position @@ -879,7 +847,6 @@ trait JavaScanners extends ast.parser.ScannersCommon { def incompleteInputError(msg: String) { incompleteInputError(pos, msg) token = EOF - errpos = pos } override def toString() = token match { @@ -913,16 +880,12 @@ 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 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 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 a562de291d..953a3c6d82 100644 --- a/src/compiler/scala/tools/nsc/javac/JavaTokens.scala +++ b/src/compiler/scala/tools/nsc/javac/JavaTokens.scala @@ -68,9 +68,6 @@ object JavaTokens extends ast.parser.Tokens { final val VOLATILE = 68 final val WHILE = 69 - def isKeyword(code : Int) = - code >= ABSTRACT && code <= WHILE - /** special symbols */ final val COMMA = 70 final val SEMI = 71 @@ -115,9 +112,6 @@ object JavaTokens extends ast.parser.Tokens { final val GTGTEQ = 113 final val GTGTGTEQ = 114 - def isSymbol(code : Int) = - code >= COMMA && code <= GTGTGTEQ - /** parenthesis */ final val LPAREN = 115 final val RPAREN = 116 diff --git a/src/compiler/scala/tools/nsc/matching/MatchSupport.scala b/src/compiler/scala/tools/nsc/matching/MatchSupport.scala index 5ce1aabcd8..3c26997cfe 100644 --- a/src/compiler/scala/tools/nsc/matching/MatchSupport.scala +++ b/src/compiler/scala/tools/nsc/matching/MatchSupport.scala @@ -22,9 +22,6 @@ 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)) - object Types { import definitions._ @@ -36,24 +33,12 @@ 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 isInt = is(IntClass) - def isChar = is(CharClass) - def isBoolean = is(BooleanClass) def isNothing = is(NothingClass) - 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 treeToString(t: Tree): String = treeInfo.unbind(t) match { case EmptyTree => "?" case WILD() => "_" @@ -66,10 +51,6 @@ 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 - }) // pretty print for debugging def pp(x: Any): String = pp(x, false) @@ -117,7 +98,6 @@ trait MatchSupport extends ast.TreeDSL { self: ParallelMatching => else x } - 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 d2f5a98411..ba966acf34 100644 --- a/src/compiler/scala/tools/nsc/matching/Matrix.scala +++ b/src/compiler/scala/tools/nsc/matching/Matrix.scala @@ -140,7 +140,6 @@ trait Matrix extends MatrixAdditions { cases: List[CaseDef], default: Tree ) { - def tvars = roots map (_.lhs) def valDefs = roots map (_.valDef) override def toString() = "MatrixInit(roots = %s, %d cases)".format(pp(roots), cases.size) } @@ -151,27 +150,12 @@ trait Matrix extends MatrixAdditions { object PatternVarGroup { def apply(xs: PatternVar*) = new PatternVarGroup(xs.toList) 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) - } } 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 extractIndex(index: Int): (PatternVar, PatternVarGroup) = { val (t, ts) = self.extractIndex(pvs, index) @@ -180,16 +164,11 @@ trait Matrix extends MatrixAdditions { def isEmpty = pvs.isEmpty def size = pvs.size - 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 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) override def toString() = pp(pvs) } @@ -237,12 +216,6 @@ 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) - - 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 ea4d9cd3f4..b5e25f3809 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 3ff5ce83bb..c6fa6f6ba0 100644 --- a/src/compiler/scala/tools/nsc/matching/PatternBindings.scala +++ b/src/compiler/scala/tools/nsc/matching/PatternBindings.scala @@ -59,10 +59,6 @@ trait PatternBindings extends ast.TreeDSL trait PatternBindingLogic { self: Pattern => - // 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 - // The outermost Bind(x1, Bind(x2, ...)) surrounding the tree. private var _boundTree: Tree = tree def boundTree = _boundTree @@ -113,9 +109,6 @@ trait PatternBindings extends ast.TreeDSL } class Bindings(private val vlist: List[Binding]) { - // if (!vlist.isEmpty) - // traceCategory("Bindings", this.toString) - def get() = vlist def toMap = vlist map (x => (x.pvar, x.tvar)) toMap diff --git a/src/compiler/scala/tools/nsc/matching/Patterns.scala b/src/compiler/scala/tools/nsc/matching/Patterns.scala index e92c43f1fd..df536da108 100644 --- a/src/compiler/scala/tools/nsc/matching/Patterns.scala +++ b/src/compiler/scala/tools/nsc/matching/Patterns.scala @@ -32,9 +32,6 @@ trait Patterns extends ast.TreeDSL { // An empty pattern def NoPattern = WildcardPattern() - // The constant null pattern - def NullPattern = LiteralPattern(NULL) - // The Nil pattern def NilPattern = Pattern(gen.mkNil) @@ -60,7 +57,6 @@ 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 simplify(pv: PatternVar) = Pattern(expr) match { case ExtractorPattern(ua) if pv.sym.tpe <:< tpt.tpe => this rebindTo expr case _ => this @@ -140,10 +136,6 @@ 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 private def isColonColon = cleanName == "::" @@ -222,15 +214,13 @@ trait Patterns extends ast.TreeDSL { // 8.1.8 (b) (literal ArrayValues) case class SequencePattern(tree: ArrayValue) extends Pattern with SequenceLikePattern { - lazy val ArrayValue(elemtpt, elems) = tree + lazy val ArrayValue(_, elems) = tree - 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(elem) = tree override def description = "_*" } // XXX temporary? @@ -384,15 +374,7 @@ trait Patterns extends ast.TreeDSL { // Covers if the symbol matches the unapply method's argument type, // and the return type of the unapply is Some. override def covers(sym: Symbol) = newMatchesPattern(sym, arg.tpe) - - // TODO: for alwaysCovers: - // 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) - } def resTypes = analyzer.unapplyTypeList(unfn.symbol, unfn.tpe, args.length) def resTypesString = resTypes match { @@ -403,13 +385,7 @@ 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 dummies = - if (!this.isCaseClass) Nil - else emptyPatterns(sufficientType.typeSymbol.caseFieldAccessors.size) - def isConstructorPattern = fn.isType override def covers(sym: Symbol) = newMatchesPattern(sym, fn.tpe) } @@ -419,9 +395,6 @@ trait Patterns extends ast.TreeDSL { // returns either a simplification of this pattern or identity. def simplify(pv: PatternVar): Pattern = this - // the right number of dummies for this pattern - def dummies: List[Pattern] = Nil - // Is this a default pattern (untyped "_" or an EmptyTree inserted by the matcher) def isDefault = false @@ -451,14 +424,8 @@ trait Patterns extends ast.TreeDSL { def isModule = sym.isModule || tpe.termSymbol.isModule def isCaseClass = tpe.typeSymbol.isCase def isObject = (sym != null) && (sym != NoSymbol) && tpe.prefix.isStable // XXX not entire logic - def hasStar = false - def setType(tpe: Type): this.type = { - tree setType tpe - this - } - def equalsCheck = tracing("equalsCheck")( if (sym.isValue) singleType(NoPrefix, sym) @@ -475,7 +442,6 @@ trait Patterns extends ast.TreeDSL { final override def toString = description - 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 e965370713..4727e6d867 100644 --- a/src/compiler/scala/tools/nsc/settings/AbsSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/AbsSettings.scala @@ -47,8 +47,6 @@ trait AbsSettings extends scala.reflect.internal.settings.AbsSettings { } }) - implicit lazy val SettingOrdering: Ordering[Setting] = Ordering.ordered - trait AbsSetting extends Ordered[Setting] with AbsSettingValue { def name: String def helpDescription: String @@ -83,14 +81,6 @@ trait AbsSettings extends scala.reflect.internal.settings.AbsSettings { this } - /** If the appearance of the setting should halt argument processing. */ - 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 } @@ -110,6 +100,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. + * !!! Needs test. */ def tryToSetFromPropertyValue(s: String): Unit = tryToSet(s :: Nil) diff --git a/src/compiler/scala/tools/nsc/settings/MutableSettings.scala b/src/compiler/scala/tools/nsc/settings/MutableSettings.scala index 4f4f0544da..748c6069f0 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 = + def embeddedDefaults[T: ClassTag]: Unit = // called from sbt and repl 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 = + def add(srcDir: String, outDir: String): Unit = // used in ide? 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) { + override def tryToSetFromPropertyValue(s : String) { // used from ide 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) + override def tryToSetFromPropertyValue(s: String) = tryToSet(s.trim.split(',').toList) // used from ide 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) + override def tryToSetFromPropertyValue(s: String) = tryToSetColon(s::Nil) // used from ide withHelpSyntax(name + ":<" + helpArg + ">") } diff --git a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala index 8dce48ee9a..c54745f6c6 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,6 @@ trait ScalaSettings extends AbsScalaSettings /** Compatibility stubs for options whose value name did * not previously match the option name. */ - def XO = optimise def debuginfo = g def dependenciesFile = dependencyfile def nowarnings = nowarn @@ -180,12 +179,9 @@ trait ScalaSettings extends AbsScalaSettings val exposeEmptyPackage = BooleanSetting("-Yexpose-empty-package", "Internal only: expose the empty package.").internalOnly() - 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 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 e866ad6ae0..98ef74aee3 100644 --- a/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala @@ -48,9 +48,4 @@ trait StandardScalaSettings { val usejavacp = BooleanSetting ("-usejavacp", "Utilize the java.class.path in classpath resolution.") val verbose = BooleanSetting ("-verbose", "Output messages about what the compiler is doing.") val version = BooleanSetting ("-version", "Print product version and exit.") - - /** 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 } diff --git a/src/compiler/scala/tools/nsc/settings/Warnings.scala b/src/compiler/scala/tools/nsc/settings/Warnings.scala index d6d77278ab..2649a150ad 100644 --- a/src/compiler/scala/tools/nsc/settings/Warnings.scala +++ b/src/compiler/scala/tools/nsc/settings/Warnings.scala @@ -26,7 +26,6 @@ trait Warnings { // These warnings should be pretty quiet unless you're doing // something inadvisable. protected def lintWarnings = List( - // warnDeadCode, warnInaccessible, warnNullaryOverride, warnNullaryUnit, @@ -39,9 +38,13 @@ 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 (_ => lintWarnings foreach (_.value = true)) + withPostSetHook { _ => + lint.value = true + allWarnings foreach (_.value = true) + } ) // Individual warnings. @@ -57,7 +60,7 @@ trait Warnings { val warnInferAny = BooleanSetting ("-Ywarn-infer-any", "Warn when a type argument is inferred to be `Any`.") // Backward compatibility. - def Xwarnfatal = fatalWarnings - def Xchecknull = warnSelectNullable - def Ywarndeadcode = warnDeadCode + @deprecated("Use fatalWarnings", "2.11.0") def Xwarnfatal = fatalWarnings // used by sbt + @deprecated("Use warnSelectNullable", "2.11.0") def Xchecknull = warnSelectNullable // used by ide + @deprecated("Use warnDeadCode", "2.11.0") def Ywarndeadcode = warnDeadCode // used by ide } diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/AbstractFileReader.scala b/src/compiler/scala/tools/nsc/symtab/classfile/AbstractFileReader.scala index 427b5bf887..17e3b08ec2 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/AbstractFileReader.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/AbstractFileReader.scala @@ -29,11 +29,6 @@ class AbstractFileReader(val file: AbstractFile) { */ var bp: Int = 0 - /** return byte at offset 'pos' - */ - @throws(classOf[IndexOutOfBoundsException]) - def byteAt(pos: Int): Byte = buf(pos) - /** read a byte */ @throws(classOf[IndexOutOfBoundsException]) @@ -45,7 +40,7 @@ class AbstractFileReader(val file: AbstractFile) { /** read some bytes */ - def nextBytes(len: Int): Array[Byte] = { + def nextBytes(len: Int): Array[Byte] = { // used in ide bp += len buf.slice(bp - len, bp) } diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala index 67f6c3ec5d..6d213af2b6 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala @@ -1169,20 +1169,6 @@ abstract class ClassfileParser { } object innerClasses extends mutable.HashMap[Name, InnerClassEntry] { - /** 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) - } - /** 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 b7511377cc..b5459ec773 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 { - 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() + 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 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 9a8db447c3..42ea7e61f0 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala @@ -999,112 +999,6 @@ abstract class Pickler extends SubComponent { patchNat(startpos + 1, writeIndex - (startpos + 2)) } - /** 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() - } - /** Write byte array */ def writeArray() { assert(writeIndex == 0) diff --git a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala index 78fb725041..7eb0b4e12c 100644 --- a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala +++ b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala @@ -184,13 +184,6 @@ 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 - case class Overload(sym: Symbol, env: TypeEnv) { override def toString = "specialized overload " + sym + " in " + env def matchesSym(sym1: Symbol) = sym.info =:= sym1.info @@ -222,8 +215,6 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { * type bounds of other @specialized type parameters (and not in its result type). */ def degenerate = false - - def isAccessor = false } /** Symbol is a special overloaded method of 'original', in the environment env. */ @@ -247,9 +238,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 - } + case class SpecializedAccessor(target: Symbol) extends SpecializedInfo { } /** Symbol is a specialized method whose body should be the target's method body. */ case class Implementation(target: Symbol) extends SpecializedInfo @@ -288,9 +277,6 @@ 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) - /** 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 * specialized type. @@ -1062,7 +1048,7 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { if (isPrimitiveValueClass(tp2.typeSymbol) || isSpecializedAnyRefSubtype(tp2, sym1)) env + ((sym1, tp2)) else if (isSpecializedAnyRefSubtype(tp2, sym1)) - env + ((sym1, tp2)) // env + ((sym1, AnyRefClass.tpe)) + env + ((sym1, tp2)) else if (strict) unifyError(tp1, tp2) else @@ -1185,7 +1171,6 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { * * A conflicting type environment could still be satisfiable. */ - 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)) } @@ -1668,7 +1653,6 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { val symbol = tree.symbol debuglog("specializing body of" + symbol.defString) val DefDef(_, _, tparams, vparams :: Nil, tpt, _) = tree -// val (_, origtparams) = splitParams(source.typeParams) val env = typeEnv(symbol) val boundTvars = env.keySet val origtparams = source.typeParams.filter(tparam => !boundTvars(tparam) || !isPrimitiveValueType(env(tparam))) @@ -1865,11 +1849,4 @@ abstract class SpecializeTypes extends InfoTransform with TypingTransformers { resultTree } } - - 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 488b8aad4e..6ab99eaec6 100644 --- a/src/compiler/scala/tools/nsc/transform/TailCalls.scala +++ b/src/compiler/scala/tools/nsc/transform/TailCalls.scala @@ -147,7 +147,6 @@ abstract class TailCalls extends Transform { } def enclosingType = method.enclClass.typeOfThis - 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 b7da0e0087..73f39225bd 100644 --- a/src/compiler/scala/tools/nsc/transform/TypingTransformers.scala +++ b/src/compiler/scala/tools/nsc/transform/TypingTransformers.scala @@ -21,13 +21,11 @@ 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) } override final def atOwner[A](owner: Symbol)(trans: => A): A = atOwner(curTree, owner)(trans) def atOwner[A](tree: Tree, owner: Symbol)(trans: => A): A = { val savedLocalTyper = localTyper -// println("transformer atOwner: " + owner + " isPackage? " + owner.isPackage) localTyper = localTyper.atOwner(tree, if (owner.isModule) owner.moduleClass else owner) val result = super.atOwner(owner)(trans) localTyper = savedLocalTyper diff --git a/src/compiler/scala/tools/nsc/util/ClassPath.scala b/src/compiler/scala/tools/nsc/util/ClassPath.scala index 0c49b9b8e7..ee66801c45 100644 --- a/src/compiler/scala/tools/nsc/util/ClassPath.scala +++ b/src/compiler/scala/tools/nsc/util/ClassPath.scala @@ -49,22 +49,6 @@ object ClassPath { /** Split the classpath, apply a transformation function, and reassemble it. */ 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: _*) - - /** Split the classpath and map them into Paths */ - 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): _*) - - /** 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)) : _*) - - /** Split the classpath and map them into URLs */ - 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] = if (expandStar) split(path) flatMap expandS @@ -124,13 +108,6 @@ 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 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 @@ -399,15 +376,3 @@ class JavaClassPath( containers: IndexedSeq[ClassPath[AbstractFile]], 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) -} diff --git a/src/compiler/scala/tools/nsc/util/CommandLineParser.scala b/src/compiler/scala/tools/nsc/util/CommandLineParser.scala index 81c1b1d37a..e8f962a9e2 100644 --- a/src/compiler/scala/tools/nsc/util/CommandLineParser.scala +++ b/src/compiler/scala/tools/nsc/util/CommandLineParser.scala @@ -21,7 +21,6 @@ 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 } } } @@ -37,7 +36,6 @@ case class CommandLine( def withUnaryArgs(xs: List[String]) = copy(unaryArguments = xs) def withBinaryArgs(xs: List[String]) = copy(binaryArguments = xs) - def originalArgs = args def assumeBinary = true def enforceArity = true def onlyKnownOptions = false @@ -105,7 +103,6 @@ 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 apply(arg: String) = argMap(arg) override def toString() = "CommandLine(\n%s)\n" format (args map (" " + _ + "\n") mkString) @@ -115,7 +112,6 @@ 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 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 b7ed7903bc..fc3dd2bac2 100644 --- a/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala +++ b/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala @@ -14,74 +14,32 @@ class JavaCharArrayReader(buf: IndexedSeq[Char], start: Int, /* startline: int, def this(buf: IndexedSeq[Char], decodeUni: Boolean, error: String => Unit) = this(buf, 0, /* 1, 1, */ decodeUni, error) - /** 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] - - /** layout constant - */ - val tabinc = 8 - /** the line and column position of the current character */ var ch: Char = _ var bp = start - 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 - - 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 - //nextline += 1 - //nextcol = 1 - } - - def hasNext: Boolean = if (bp < buf.length) true - else { - false - } - def last: Char = if (bp > start + 2) buf(bp - 2) else ' ' // XML literals + def hasNext = bp < buf.length def next(): Char = { - //cline = nextline - //ccol = nextcol val buf = this.buf.asInstanceOf[collection.mutable.WrappedArray[Char]].array if(!hasNext) { ch = SU return SU // there is an endless stream of SU's at the end } - oldBp = bp - oldCh = ch ch = buf(bp) isUnicode = false bp = bp + 1 ch match { case '\t' => - // nextcol = ((nextcol - 1) / tabinc * tabinc) + tabinc + 1; case CR => if (bp < buf.size && buf(bp) == LF) { ch = LF bp += 1 } - markNewLine() case LF | FF => - markNewLine() case '\\' => def evenSlashPrefix: Boolean = { var p = bp - 2 @@ -90,11 +48,10 @@ class JavaCharArrayReader(buf: IndexedSeq[Char], start: Int, /* startline: int, } def udigit: Int = { val d = digit2int(buf(bp), 16) - if (d >= 0) { bp += 1; /* nextcol = nextcol + 1 */ } + if (d >= 0) bp += 1 else error("error in unicode escape"); d } - // nextcol += 1 if (buf(bp) == 'u' && decodeUni && evenSlashPrefix) { do { bp += 1 //; nextcol += 1 @@ -104,20 +61,10 @@ class JavaCharArrayReader(buf: IndexedSeq[Char], start: Int, /* startline: int, isUnicode = true } case _ => - if (ch > ' ') onlyBlankChars = false - // nextcol += 1 } ch } - 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 a2994966fd..1d2cc73c6b 100644 --- a/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala +++ b/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala @@ -46,9 +46,6 @@ 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]]) - /** 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 { case null => Array() @@ -71,14 +68,6 @@ trait ScalaClassLoader extends JClassLoader { try asContext(method.invoke(null, Array(arguments.toArray: AnyRef): _*)) // !!! : AnyRef shouldn't be necessary catch unwrapHandler({ case ex => throw ex }) } - - /** 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 - }) } /** Methods for obtaining various classloaders. @@ -99,35 +88,6 @@ 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 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 setContext(cl: JClassLoader) = Thread.currentThread.setContextClassLoader(cl) def savingContextLoader[T](body: => T): T = { @@ -143,14 +103,12 @@ object ScalaClassLoader { private var classloaderURLs: Seq[URL] = urls def classPathURLs: Seq[URL] = classloaderURLs - 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 fromURLs(urls: Seq[URL], parent: ClassLoader = null): URLClassLoader = @@ -161,7 +119,6 @@ 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 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 b103ae9cb0..a33af1754d 100644 --- a/src/compiler/scala/tools/nsc/util/SimpleTracer.scala +++ b/src/compiler/scala/tools/nsc/util/SimpleTracer.scala @@ -14,6 +14,5 @@ class SimpleTracer(out: PrintStream, enabled: Boolean = true) { if (enabled) out.println(msg+value) value } - 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 e9dcaa8e16..792a659ad6 100644 --- a/src/compiler/scala/tools/nsc/util/package.scala +++ b/src/compiler/scala/tools/nsc/util/package.scala @@ -18,16 +18,9 @@ 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 - /** 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 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. */ @@ -54,18 +47,6 @@ package object util { (result, ts2 filterNot (ts1 contains _)) } - /** 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 - - f(end - start) - result - } - /** Generate a string using a routine that wants to write on a stream. */ def stringFromWriter(writer: PrintWriter => Unit): String = { val stringWriter = new StringWriter() @@ -96,7 +77,6 @@ package object util { } lazy val trace = new SimpleTracer(System.out) - 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/reflect/scala/reflect/internal/Names.scala b/src/reflect/scala/reflect/internal/Names.scala index 35ff9284e0..333651162e 100644 --- a/src/reflect/scala/reflect/internal/Names.scala +++ b/src/reflect/scala/reflect/internal/Names.scala @@ -183,7 +183,7 @@ trait Names extends api.Names with LowPriorityNames { scala.compat.Platform.arraycopy(chrs, index, cs, offset, len) /** @return the ascii representation of this name */ - final def toChars: Array[Char] = { + final def toChars: Array[Char] = { // used by ide val cs = new Array[Char](len) copyChars(cs, 0) cs @@ -394,7 +394,7 @@ trait Names extends api.Names with LowPriorityNames { def prepend(prefix: String) = newName("" + prefix + this) def decodedName: ThisNameType = newName(decode) - def isOperatorName: Boolean = decode != toString + def isOperatorName: Boolean = decode != toString // used by ide def longString: String = nameKind + " " + decode def debugString = { val s = decode ; if (isTypeName) s + "!" else s } } diff --git a/src/reflect/scala/reflect/internal/TreeGen.scala b/src/reflect/scala/reflect/internal/TreeGen.scala index f30807a26c..072e94e069 100644 --- a/src/reflect/scala/reflect/internal/TreeGen.scala +++ b/src/reflect/scala/reflect/internal/TreeGen.scala @@ -11,7 +11,7 @@ abstract class TreeGen extends macros.TreeBuilder { def rootScalaDot(name: Name) = Select(rootId(nme.scala_) setSymbol ScalaPackage, name) def scalaDot(name: Name) = Select(Ident(nme.scala_) setSymbol ScalaPackage, name) def scalaAnnotationDot(name: Name) = Select(scalaDot(nme.annotation), name) - def scalaAnyRefConstr = scalaDot(tpnme.AnyRef) setSymbol AnyRefClass + def scalaAnyRefConstr = scalaDot(tpnme.AnyRef) setSymbol AnyRefClass // used in ide def scalaFunctionConstr(argtpes: List[Tree], restpe: Tree, abstractFun: Boolean = false): Tree = { val cls = if (abstractFun) -- cgit v1.2.3