summaryrefslogtreecommitdiff
path: root/src/repl/scala/tools/nsc/interpreter
diff options
context:
space:
mode:
Diffstat (limited to 'src/repl/scala/tools/nsc/interpreter')
-rw-r--r--src/repl/scala/tools/nsc/interpreter/Delimited.scala41
-rw-r--r--src/repl/scala/tools/nsc/interpreter/Formatting.scala27
-rw-r--r--src/repl/scala/tools/nsc/interpreter/ILoop.scala171
-rw-r--r--src/repl/scala/tools/nsc/interpreter/IMain.scala67
-rw-r--r--src/repl/scala/tools/nsc/interpreter/Imports.scala24
-rw-r--r--src/repl/scala/tools/nsc/interpreter/InteractiveReader.scala2
-rw-r--r--src/repl/scala/tools/nsc/interpreter/JLineCompletion.scala1
-rw-r--r--src/repl/scala/tools/nsc/interpreter/JLineReader.scala75
-rw-r--r--src/repl/scala/tools/nsc/interpreter/Parsed.scala19
-rw-r--r--src/repl/scala/tools/nsc/interpreter/Pasted.scala22
-rw-r--r--src/repl/scala/tools/nsc/interpreter/ReplProps.scala11
-rw-r--r--src/repl/scala/tools/nsc/interpreter/Tabulators.scala (renamed from src/repl/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala)59
-rw-r--r--src/repl/scala/tools/nsc/interpreter/session/FileBackedHistory.scala84
-rw-r--r--src/repl/scala/tools/nsc/interpreter/session/History.scala3
-rw-r--r--src/repl/scala/tools/nsc/interpreter/session/JLineHistory.scala49
-rw-r--r--src/repl/scala/tools/nsc/interpreter/session/SimpleHistory.scala12
-rw-r--r--src/repl/scala/tools/nsc/interpreter/session/package.scala5
17 files changed, 220 insertions, 452 deletions
diff --git a/src/repl/scala/tools/nsc/interpreter/Delimited.scala b/src/repl/scala/tools/nsc/interpreter/Delimited.scala
deleted file mode 100644
index b7f06f1d0a..0000000000
--- a/src/repl/scala/tools/nsc/interpreter/Delimited.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2013 LAMP/EPFL
- * @author Paul Phillips
- */
-
-package scala.tools.nsc
-package interpreter
-
-import jline.console.completer.ArgumentCompleter.{ ArgumentDelimiter, ArgumentList }
-
-class JLineDelimiter extends ArgumentDelimiter {
- def toJLine(args: List[String], cursor: Int) = args match {
- case Nil => new ArgumentList(new Array[String](0), 0, 0, cursor)
- case xs => new ArgumentList(xs.toArray, xs.size - 1, xs.last.length, cursor)
- }
-
- def delimit(buffer: CharSequence, cursor: Int) = {
- val p = Parsed(buffer.toString, cursor)
- toJLine(p.args, cursor)
- }
- def isDelimiter(buffer: CharSequence, cursor: Int) = Parsed(buffer.toString, cursor).isDelimiter
-}
-
-trait Delimited {
- self: Parsed =>
-
- def delimited: Char => Boolean
- def escapeChars: List[Char] = List('\\')
-
- /** Break String into args based on delimiting function.
- */
- protected def toArgs(s: String): List[String] =
- if (s == "") Nil
- else (s indexWhere isDelimiterChar) match {
- case -1 => List(s)
- case idx => (s take idx) :: toArgs(s drop (idx + 1))
- }
-
- def isDelimiterChar(ch: Char) = delimited(ch)
- def isEscapeChar(ch: Char): Boolean = escapeChars contains ch
-}
diff --git a/src/repl/scala/tools/nsc/interpreter/Formatting.scala b/src/repl/scala/tools/nsc/interpreter/Formatting.scala
index 43e653edfd..844997429c 100644
--- a/src/repl/scala/tools/nsc/interpreter/Formatting.scala
+++ b/src/repl/scala/tools/nsc/interpreter/Formatting.scala
@@ -8,28 +8,25 @@ package interpreter
import util.stringFromWriter
-trait Formatting {
- def prompt: String
+class Formatting(indent: Int) {
- def spaces(code: String): String = {
+ private val indentation = " " * indent
+
+ private def indenting(code: String): Boolean = {
/** Heuristic to avoid indenting and thereby corrupting """-strings and XML literals. */
val tokens = List("\"\"\"", "</", "/>")
val noIndent = (code contains "\n") && (tokens exists code.contains)
- if (noIndent) ""
- else prompt drop 1 map (_ => ' ')
+ !noIndent
}
/** Indent some code by the width of the scala> prompt.
* This way, compiler error messages read better.
*/
- def indentCode(code: String) = {
- val indent = spaces(code)
- stringFromWriter(str =>
- for (line <- code.lines) {
- str print indent
- str print (line + "\n")
- str.flush()
- }
- )
- }
+ def indentCode(code: String) = stringFromWriter(str =>
+ for (line <- code.lines) {
+ if (indenting(code)) str print indentation
+ str println line
+ str.flush()
+ }
+ )
}
diff --git a/src/repl/scala/tools/nsc/interpreter/ILoop.scala b/src/repl/scala/tools/nsc/interpreter/ILoop.scala
index 4221126caa..525609171e 100644
--- a/src/repl/scala/tools/nsc/interpreter/ILoop.scala
+++ b/src/repl/scala/tools/nsc/interpreter/ILoop.scala
@@ -26,6 +26,8 @@ import scala.concurrent.{ ExecutionContext, Await, Future, future }
import ExecutionContext.Implicits._
import java.io.{ BufferedReader, FileReader }
+import scala.util.{Try, Success, Failure}
+
/** The Scala interactive shell. It provides a read-eval-print loop
* around the Interpreter class.
* After instantiation, clients should call the main() method.
@@ -109,11 +111,10 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter)
}
class ILoopInterpreter extends IMain(settings, out) {
- outer =>
-
- override lazy val formatting = new Formatting {
- def prompt = ILoop.this.prompt
- }
+ // the expanded prompt but without color escapes and without leading newline, for purposes of indenting
+ override lazy val formatting: Formatting = new Formatting(
+ (replProps.promptString format Properties.versionNumberString).lines.toList.last.length
+ )
override protected def parentClassLoader =
settings.explicitParentLoader.getOrElse( classOf[ILoop].getClassLoader )
}
@@ -197,10 +198,8 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter)
echo("%d %s".format(index + offset, line))
}
- private val currentPrompt = Properties.shellPromptString
-
/** Prompt to print when awaiting input */
- def prompt = currentPrompt
+ def prompt = replProps.prompt
import LoopCommand.{ cmd, nullary }
@@ -410,14 +409,8 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter)
}
private def readOneLine() = {
- import scala.io.AnsiColor.{ MAGENTA, RESET }
out.flush()
- in readLine (
- if (replProps.colorOk)
- MAGENTA + prompt + RESET
- else
- prompt
- )
+ in readLine prompt
}
/** The main read-eval-print loop for the repl. It calls
@@ -503,10 +496,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter)
val errless = intp compileSources new BatchSourceFile("<pastie>", s"object pastel {\n$code\n}")
if (errless) echo("The compiler reports no errors.")
}
- def historicize(text: String) = history match {
- case jlh: JLineHistory => text.lines foreach jlh.add ; jlh.moveToEnd() ; true
- case _ => false
- }
+
def edit(text: String): Result = editor match {
case Some(ed) =>
val tmp = File.makeTemp()
@@ -522,7 +512,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter)
val res = intp interpret edited
if (res == IR.Incomplete) diagnose(edited)
else {
- historicize(edited)
+ history.historicize(edited)
Result(lineToRecord = Some(edited), keepRunning = true)
}
case None => echo("Can't read edited text. Did you delete it?")
@@ -533,7 +523,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter)
tmp.delete()
}
case None =>
- if (historicize(text)) echo("Placing text in recent history.")
+ if (history.historicize(text)) echo("Placing text in recent history.")
else echo(f"No EDITOR defined and you can't change history, echoing your text:%n$text")
}
@@ -565,10 +555,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter)
}
import scala.collection.JavaConverters._
val index = (start - 1) max 0
- val text = history match {
- case jlh: JLineHistory => jlh.entries(index).asScala.take(len) map (_.value) mkString "\n"
- case _ => history.asStrings.slice(index, index + len) mkString "\n"
- }
+ val text = history.asStrings(index, index + len) mkString "\n"
edit(text)
} catch {
case _: NumberFormatException => echo(s"Bad range '$what'")
@@ -774,8 +761,13 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter)
}
private object paste extends Pasted {
+ import scala.util.matching.Regex.quote
val ContinueString = " | "
- val PromptString = "scala> "
+ val PromptString = prompt.lines.toList.last
+ val anyPrompt = s"""\\s*(?:${quote(PromptString.trim)}|${quote(AltPromptString.trim)})\\s*""".r
+
+ def isPrompted(line: String) = matchesPrompt(line)
+ def isPromptOnly(line: String) = line match { case anyPrompt() => true ; case _ => false }
def interpret(line: String): Unit = {
echo(line.trim)
@@ -785,10 +777,17 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter)
def transcript(start: String) = {
echo("\n// Detected repl transcript paste: ctrl-D to finish.\n")
- apply(Iterator(start) ++ readWhile(_.trim != PromptString.trim))
+ apply(Iterator(start) ++ readWhile(!isPromptOnly(_)))
}
+
+ def unapply(line: String): Boolean = isPrompted(line)
+ }
+
+ private object invocation {
+ def unapply(line: String): Boolean = Completion.looksLikeInvocation(line)
}
- import paste.{ ContinueString, PromptString }
+
+ private val lineComment = """\s*//.*""".r // all comment
/** Interpret expressions starting with the first line.
* Read lines until a complete compilation unit is available
@@ -800,53 +799,42 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter)
// signal completion non-completion input has been received
in.completion.resetVerbosity()
- def reallyInterpret = {
- val reallyResult = intp.interpret(code)
- (reallyResult, reallyResult match {
- case IR.Error => None
- case IR.Success => Some(code)
- case IR.Incomplete =>
- if (in.interactive && code.endsWith("\n\n")) {
- echo("You typed two blank lines. Starting a new command.")
+ def reallyInterpret = intp.interpret(code) match {
+ case IR.Error => None
+ case IR.Success => Some(code)
+ case IR.Incomplete if in.interactive && code.endsWith("\n\n") =>
+ echo("You typed two blank lines. Starting a new command.")
+ None
+ case IR.Incomplete =>
+ in.readLine(paste.ContinueString) match {
+ case null =>
+ // we know compilation is going to fail since we're at EOF and the
+ // parser thinks the input is still incomplete, but since this is
+ // a file being read non-interactively we want to fail. So we send
+ // it straight to the compiler for the nice error message.
+ intp.compileString(code)
None
- }
- else in.readLine(ContinueString) match {
- case null =>
- // we know compilation is going to fail since we're at EOF and the
- // parser thinks the input is still incomplete, but since this is
- // a file being read non-interactively we want to fail. So we send
- // it straight to the compiler for the nice error message.
- intp.compileString(code)
- None
-
- case line => interpretStartingWith(code + "\n" + line)
- }
- })
+
+ case line => interpretStartingWith(code + "\n" + line)
+ }
}
- /** Here we place ourselves between the user and the interpreter and examine
- * the input they are ostensibly submitting. We intervene in several cases:
+ /* Here we place ourselves between the user and the interpreter and examine
+ * the input they are ostensibly submitting. We intervene in several cases:
*
- * 1) If the line starts with "scala> " it is assumed to be an interpreter paste.
- * 2) If the line starts with "." (but not ".." or "./") it is treated as an invocation
- * on the previous result.
- * 3) If the Completion object's execute returns Some(_), we inject that value
- * and avoid the interpreter, as it's likely not valid scala code.
+ * 1) If the line starts with "scala> " it is assumed to be an interpreter paste.
+ * 2) If the line starts with "." (but not ".." or "./") it is treated as an invocation
+ * on the previous result.
+ * 3) If the Completion object's execute returns Some(_), we inject that value
+ * and avoid the interpreter, as it's likely not valid scala code.
*/
- if (code == "") None
- else if (!paste.running && code.trim.startsWith(PromptString)) {
- paste.transcript(code)
- None
- }
- else if (Completion.looksLikeInvocation(code) && intp.mostRecentVar != "") {
- interpretStartingWith(intp.mostRecentVar + code)
- }
- else if (code.trim startsWith "//") {
- // line comment, do nothing
- None
+ code match {
+ case "" => None
+ case lineComment() => None // line comment, do nothing
+ case paste() if !paste.running => paste.transcript(code) ; None
+ case invocation() if intp.mostRecentVar != "" => interpretStartingWith(intp.mostRecentVar + code)
+ case _ => reallyInterpret
}
- else
- reallyInterpret._2
}
// runs :load `file` on any files passed via -i
@@ -866,16 +854,36 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter)
* with SimpleReader.
*/
def chooseReader(settings: Settings): InteractiveReader = {
- if (settings.Xnojline || Properties.isEmacsShell)
- SimpleReader()
- else try new JLineReader(
- if (settings.noCompletion) NoCompletion
- else new JLineCompletion(intp)
- )
- catch {
- case ex @ (_: Exception | _: NoClassDefFoundError) =>
- echo(f"Failed to created JLineReader: ${ex}%nFalling back to SimpleReader.")
- SimpleReader()
+ if (settings.Xnojline || Properties.isEmacsShell) SimpleReader()
+ else {
+ type Completer = () => Completion
+ type ReaderMaker = Completer => InteractiveReader
+
+ def instantiate(className: String): ReaderMaker = completer => {
+ if (settings.debug) Console.println(s"Trying to instantiate a InteractiveReader from $className")
+ Class.forName(className).getConstructor(classOf[Completer]).
+ newInstance(completer).
+ asInstanceOf[InteractiveReader]
+ }
+
+ def mkReader(maker: ReaderMaker) =
+ if (settings.noCompletion) maker(() => NoCompletion)
+ else maker(() => new JLineCompletion(intp)) // JLineCompletion is a misnomer -- it's not tied to jline
+
+ def internalClass(kind: String) = s"scala.tools.nsc.interpreter.$kind.InteractiveReader"
+ val readerClasses = sys.props.get("scala.repl.reader").toStream ++ Stream(internalClass("jline"), internalClass("jline_embedded"))
+ val readers = readerClasses map (cls => Try { mkReader(instantiate(cls)) })
+
+ val reader = (readers collect { case Success(reader) => reader } headOption) getOrElse SimpleReader()
+
+ if (settings.debug) {
+ val readerDiags = (readerClasses, readers).zipped map {
+ case (cls, Failure(e)) => s" - $cls --> " + e.getStackTrace.mkString(e.toString+"\n\t", "\n\t","\n")
+ case (cls, Success(_)) => s" - $cls OK"
+ }
+ Console.println(s"All InteractiveReaders tried: ${readerDiags.mkString("\n","\n","\n")}")
+ }
+ reader
}
}
@@ -896,10 +904,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter)
asyncMessage(power.banner)
}
// SI-7418 Now, and only now, can we enable TAB completion.
- in match {
- case x: JLineReader => x.consoleReader.postInit
- case _ =>
- }
+ in.postInit()
}
// start an interpreter with the given settings
diff --git a/src/repl/scala/tools/nsc/interpreter/IMain.scala b/src/repl/scala/tools/nsc/interpreter/IMain.scala
index c281126d5f..2550a5dc57 100644
--- a/src/repl/scala/tools/nsc/interpreter/IMain.scala
+++ b/src/repl/scala/tools/nsc/interpreter/IMain.scala
@@ -69,6 +69,8 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
// Used in a test case.
def showDirectory() = replOutput.show(out)
+ lazy val isClassBased: Boolean = settings.Yreplclassbased.value
+
private[nsc] var printResults = true // whether to print result lines
private[nsc] var totalSilence = false // whether to print anything
private var _initializeComplete = false // compiler is initialized
@@ -110,12 +112,13 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
def this(factory: ScriptEngineFactory) = this(factory, new Settings())
def this() = this(new Settings())
- lazy val formatting: Formatting = new Formatting {
- val prompt = Properties.shellPromptString
- }
+ // the expanded prompt but without color escapes and without leading newline, for purposes of indenting
+ lazy val formatting: Formatting = new Formatting(
+ (replProps.promptString format Properties.versionNumberString).lines.toList.last.length
+ )
lazy val reporter: ReplReporter = new ReplReporter(this)
- import formatting._
+ import formatting.indentCode
import reporter.{ printMessage, printUntruncatedMessage }
// This exists mostly because using the reporter too early leads to deadlock.
@@ -310,8 +313,14 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
}
def originalPath(name: String): String = originalPath(TermName(name))
- def originalPath(name: Name): String = typerOp path name
- def originalPath(sym: Symbol): String = typerOp path sym
+ def originalPath(name: Name): String = translateOriginalPath(typerOp path name)
+ def originalPath(sym: Symbol): String = translateOriginalPath(typerOp path sym)
+ /** For class based repl mode we use an .INSTANCE accessor. */
+ val readInstanceName = if(isClassBased) ".INSTANCE" else ""
+ def translateOriginalPath(p: String): String = {
+ val readName = java.util.regex.Matcher.quoteReplacement(sessionNames.read)
+ p.replaceFirst(readName, readName + readInstanceName)
+ }
def flatPath(sym: Symbol): String = flatOp shift sym.javaClassName
def translatePath(path: String) = {
@@ -460,7 +469,7 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
}
private def requestFromLine(line: String, synthetic: Boolean): Either[IR.Result, Request] = {
- val content = indentCode(line)
+ val content = line //indentCode(line)
val trees = parse(content) match {
case parse.Incomplete => return Left(IR.Incomplete)
case parse.Error => return Left(IR.Error)
@@ -758,11 +767,13 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
// object and we can do that much less wrapping.
def packageDecl = "package " + packageName
+ def pathToInstance(name: String) = packageName + "." + name + readInstanceName
def pathTo(name: String) = packageName + "." + name
def packaged(code: String) = packageDecl + "\n\n" + code
- def readPath = pathTo(readName)
- def evalPath = pathTo(evalName)
+ def readPathInstance = pathToInstance(readName)
+ def readPath = pathTo(readName)
+ def evalPath = pathTo(evalName)
def call(name: String, args: Any*): AnyRef = {
val m = evalMethod(name)
@@ -802,7 +813,8 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
/** The innermost object inside the wrapper, found by
* following accessPath into the outer one.
*/
- def resolvePathToSymbol(accessPath: String): Symbol = {
+ def resolvePathToSymbol(fullAccessPath: String): Symbol = {
+ val accessPath = fullAccessPath.stripPrefix(readPath)
val readRoot = readRootPath(readPath) // the outermost wrapper
(accessPath split '.').foldLeft(readRoot: Symbol) {
case (sym, "") => sym
@@ -849,7 +861,6 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
def defines = defHandlers flatMap (_.definedSymbols)
def imports = importedSymbols
def value = Some(handlers.last) filter (h => h.definesValue) map (h => definedSymbols(h.definesTerm.get)) getOrElse NoSymbol
-
val lineRep = new ReadEvalPrint()
private var _originalLine: String = null
@@ -858,6 +869,11 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
/** handlers for each tree in this request */
val handlers: List[MemberHandler] = trees map (memberHandlers chooseHandler _)
+ val definesClass = handlers.exists {
+ case _: ClassHandler => true
+ case _ => false
+ }
+
def defHandlers = handlers collect { case x: MemberDefHandler => x }
/** list of names used by this expression */
@@ -875,13 +891,13 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
* append to objectName to access anything bound by request.
*/
lazy val ComputedImports(importsPreamble, importsTrailer, accessPath) =
- exitingTyper(importsCode(referencedNames.toSet, ObjectSourceCode))
+ exitingTyper(importsCode(referencedNames.toSet, ObjectSourceCode, definesClass))
/** the line of code to compute */
def toCompute = line
/** The path of the value that contains the user code. */
- def fullAccessPath = s"${lineRep.readPath}$accessPath"
+ def fullAccessPath = s"${lineRep.readPathInstance}$accessPath"
/** The path of the given member of the wrapping instance. */
def fullPath(vname: String) = s"$fullAccessPath.`$vname`"
@@ -894,10 +910,10 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
else List("def %s = %s".format("$line", tquoted(originalLine)), "def %s = Nil".format("$trees"))
}
def preamble = s"""
- |$preambleHeader
- |%s%s%s
- """.stripMargin.format(lineRep.readName, envLines.map(" " + _ + ";\n").mkString,
- importsPreamble, indentCode(toCompute))
+ |${preambleHeader format lineRep.readName}
+ |${envLines mkString (" ", ";\n ", ";\n")}
+ |$importsPreamble
+ |${indentCode(toCompute)}""".stripMargin
val generate = (m: MemberHandler) => m extraCodeToEvaluate Request.this
@@ -911,7 +927,7 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
def postwrap: String
}
- private class ObjectBasedWrapper extends Wrapper {
+ class ObjectBasedWrapper extends Wrapper {
def preambleHeader = "object %s {"
def postamble = importsTrailer + "\n}"
@@ -919,13 +935,16 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
def postwrap = "}\n"
}
- private class ClassBasedWrapper extends Wrapper {
- def preambleHeader = "class %s extends Serializable {"
+ class ClassBasedWrapper extends Wrapper {
+ def preambleHeader = "class %s extends Serializable { "
/** Adds an object that instantiates the outer wrapping class. */
- def postamble = s"""$importsTrailer
+ def postamble = s"""
+ |$importsTrailer
+ |}
+ |object ${lineRep.readName} {
+ | val INSTANCE = new ${lineRep.readName}();
|}
- |object ${lineRep.readName} extends ${lineRep.readName}
|""".stripMargin
import nme.{ INTERPRETER_IMPORT_WRAPPER => iw }
@@ -935,7 +954,7 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
}
private lazy val ObjectSourceCode: Wrapper =
- if (settings.Yreplclassbased) new ClassBasedWrapper else new ObjectBasedWrapper
+ if (isClassBased) new ClassBasedWrapper else new ObjectBasedWrapper
private object ResultObjectSourceCode extends IMain.CodeAssembler[MemberHandler] {
/** We only want to generate this code when the result
@@ -994,7 +1013,7 @@ class IMain(@BeanProperty val factory: ScriptEngineFactory, initialSettings: Set
}
}
- lazy val resultSymbol = lineRep.resolvePathToSymbol(accessPath)
+ lazy val resultSymbol = lineRep.resolvePathToSymbol(fullAccessPath)
def applyToResultMember[T](name: Name, f: Symbol => T) = exitingTyper(f(resultSymbol.info.nonPrivateDecl(name)))
/* typeOf lookup with encoding */
diff --git a/src/repl/scala/tools/nsc/interpreter/Imports.scala b/src/repl/scala/tools/nsc/interpreter/Imports.scala
index 5244858a62..3ec77e46f1 100644
--- a/src/repl/scala/tools/nsc/interpreter/Imports.scala
+++ b/src/repl/scala/tools/nsc/interpreter/Imports.scala
@@ -92,7 +92,7 @@ trait Imports {
* last one imported is actually usable.
*/
case class ComputedImports(prepend: String, append: String, access: String)
- protected def importsCode(wanted: Set[Name], wrapper: Request#Wrapper): ComputedImports = {
+ protected def importsCode(wanted: Set[Name], wrapper: Request#Wrapper, definesClass: Boolean): 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.
@@ -107,6 +107,8 @@ trait Imports {
// Single symbol imports might be implicits! See bug #1752. Rather than
// try to finesse this, we will mimic all imports for now.
def keepHandler(handler: MemberHandler) = handler match {
+ /* While defining classes in class based mode - implicits are not needed. */
+ case h: ImportHandler if isClassBased && definesClass => h.importedNames.exists(x => wanted.contains(x))
case _: ImportHandler => true
case x => x.definesImplicit || (x.definedNames exists wanted)
}
@@ -146,7 +148,10 @@ trait Imports {
// loop through previous requests, adding imports for each one
wrapBeforeAndAfter {
+ // Reusing a single temporary value when import from a line with multiple definitions.
+ val tempValLines = mutable.Set[Int]()
for (ReqAndHandler(req, handler) <- reqsToUse) {
+ val objName = req.lineRep.readPathInstance
handler match {
// If the user entered an import, then just use it; add an import wrapping
// level if the import might conflict with some other import
@@ -157,6 +162,23 @@ trait Imports {
code append (x.member + "\n")
currentImps ++= x.importedNames
+ case x if isClassBased =>
+ for (imv <- x.definedNames) {
+ if (!currentImps.contains(imv)) {
+ x match {
+ case _: ClassHandler =>
+ code.append("import " + objName + req.accessPath + ".`" + imv + "`\n")
+ case _ =>
+ val valName = req.lineRep.packageName + req.lineRep.readName
+ if (!tempValLines.contains(req.lineRep.lineId)) {
+ code.append(s"val $valName = $objName\n")
+ tempValLines += req.lineRep.lineId
+ }
+ code.append(s"import $valName${req.accessPath}.`$imv`;\n")
+ }
+ currentImps += imv
+ }
+ }
// For other requests, import each defined name.
// import them explicitly instead of with _, so that
// ambiguity errors will not be generated. Also, quote
diff --git a/src/repl/scala/tools/nsc/interpreter/InteractiveReader.scala b/src/repl/scala/tools/nsc/interpreter/InteractiveReader.scala
index ed69d449cb..71753a3e39 100644
--- a/src/repl/scala/tools/nsc/interpreter/InteractiveReader.scala
+++ b/src/repl/scala/tools/nsc/interpreter/InteractiveReader.scala
@@ -13,6 +13,8 @@ import Properties.isMac
/** Reads lines from an input stream */
trait InteractiveReader {
+ def postInit(): Unit = {}
+
val interactive: Boolean
def reset(): Unit
diff --git a/src/repl/scala/tools/nsc/interpreter/JLineCompletion.scala b/src/repl/scala/tools/nsc/interpreter/JLineCompletion.scala
index c1122d4223..d878988e26 100644
--- a/src/repl/scala/tools/nsc/interpreter/JLineCompletion.scala
+++ b/src/repl/scala/tools/nsc/interpreter/JLineCompletion.scala
@@ -12,6 +12,7 @@ import scala.reflect.internal.util.StringOps.longestCommonPrefix
// REPL completor - queries supplied interpreter for valid
// completions based on current contents of buffer.
+// TODO: change class name to reflect it's not specific to jline (nor does it depend on it)
class JLineCompletion(val intp: IMain) extends Completion with CompletionOutput {
val global: intp.global.type = intp.global
import global._
diff --git a/src/repl/scala/tools/nsc/interpreter/JLineReader.scala b/src/repl/scala/tools/nsc/interpreter/JLineReader.scala
deleted file mode 100644
index b6e834a1ed..0000000000
--- a/src/repl/scala/tools/nsc/interpreter/JLineReader.scala
+++ /dev/null
@@ -1,75 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2013 LAMP/EPFL
- * @author Stepan Koltsov
- */
-
-package scala.tools.nsc
-package interpreter
-
-import jline.console.ConsoleReader
-import jline.console.completer._
-import session._
-import Completion._
-
-/**
- * Reads from the console using JLine.
- */
-class JLineReader(_completion: => Completion) extends InteractiveReader {
- val interactive = true
- val consoleReader = new JLineConsoleReader()
-
- lazy val completion = _completion
- lazy val history: JLineHistory = JLineHistory()
-
- private def term = consoleReader.getTerminal()
- def reset() = term.reset()
-
- def scalaToJline(tc: ScalaCompleter): Completer = new Completer {
- def complete(_buf: String, cursor: Int, candidates: JList[CharSequence]): Int = {
- val buf = if (_buf == null) "" else _buf
- val Candidates(newCursor, newCandidates) = tc.complete(buf, cursor)
- newCandidates foreach (candidates add _)
- newCursor
- }
- }
-
- class JLineConsoleReader extends ConsoleReader with ConsoleReaderHelper with VariColumnTabulator {
- val isAcross = interpreter.`package`.isAcross
-
- this setPaginationEnabled interpreter.`package`.isPaged
-
- // ASAP
- this setExpandEvents false
-
- // working around protected/trait/java insufficiencies.
- def goBack(num: Int): Unit = back(num)
- if ((history: History) ne NoHistory)
- this setHistory history
-
- def readOneKey(prompt: String) = {
- this.print(prompt)
- this.flush()
- this.readCharacter()
- }
- def eraseLine() = consoleReader.resetPromptLine("", "", 0)
- def redrawLineAndFlush(): Unit = { flush() ; drawLine() ; flush() }
-
- // A hook for running code after the repl is done initializing.
- lazy val postInit: Unit = {
- this setBellEnabled false
-
- if (completion ne NoCompletion) {
- val argCompletor: ArgumentCompleter =
- new ArgumentCompleter(new JLineDelimiter, scalaToJline(completion.completer()))
- argCompletor setStrict false
-
- this addCompleter argCompletor
- this setAutoprintThreshold 400 // max completion candidates without warning
- }
- }
- }
-
- def redrawLine() = consoleReader.redrawLineAndFlush()
- def readOneLine(prompt: String) = consoleReader readLine prompt
- def readOneKey(prompt: String) = consoleReader readOneKey prompt
-}
diff --git a/src/repl/scala/tools/nsc/interpreter/Parsed.scala b/src/repl/scala/tools/nsc/interpreter/Parsed.scala
index 672a6fd28f..5e58d3a2c4 100644
--- a/src/repl/scala/tools/nsc/interpreter/Parsed.scala
+++ b/src/repl/scala/tools/nsc/interpreter/Parsed.scala
@@ -8,6 +8,25 @@ package interpreter
import util.returning
+trait Delimited {
+ self: Parsed =>
+
+ def delimited: Char => Boolean
+ def escapeChars: List[Char] = List('\\')
+
+ /** Break String into args based on delimiting function.
+ */
+ protected def toArgs(s: String): List[String] =
+ if (s == "") Nil
+ else (s indexWhere isDelimiterChar) match {
+ case -1 => List(s)
+ case idx => (s take idx) :: toArgs(s drop (idx + 1))
+ }
+
+ def isDelimiterChar(ch: Char) = delimited(ch)
+ def isEscapeChar(ch: Char): Boolean = escapeChars contains ch
+}
+
/** One instance of a command buffer.
*/
class Parsed private (
diff --git a/src/repl/scala/tools/nsc/interpreter/Pasted.scala b/src/repl/scala/tools/nsc/interpreter/Pasted.scala
index f5db3d9e3a..5f388eb15b 100644
--- a/src/repl/scala/tools/nsc/interpreter/Pasted.scala
+++ b/src/repl/scala/tools/nsc/interpreter/Pasted.scala
@@ -16,17 +16,21 @@ package interpreter
* the same result.
*/
abstract class Pasted {
+ def interpret(line: String): Unit
def ContinueString: String
def PromptString: String
- def interpret(line: String): Unit
+ def AltPromptString: String = "scala> "
+
+ private val testBoth = PromptString != AltPromptString
+ private val spacey = " \t".toSet
- def matchesPrompt(line: String) = matchesString(line, PromptString)
+ def matchesPrompt(line: String) = matchesString(line, PromptString) || testBoth && matchesString(line, AltPromptString)
def matchesContinue(line: String) = matchesString(line, ContinueString)
def running = isRunning
private def matchesString(line: String, target: String): Boolean = (
(line startsWith target) ||
- (line.nonEmpty && " \t".toSet(line.head) && matchesString(line.tail, target))
+ (line.nonEmpty && spacey(line.head) && matchesString(line.tail, target))
)
private def stripString(line: String, target: String) = line indexOf target match {
case -1 => line
@@ -39,7 +43,9 @@ abstract class Pasted {
private class PasteAnalyzer(val lines: List[String]) {
val referenced = lines flatMap (resReference findAllIn _.trim.stripPrefix("res")) toSet
- val cmds = lines reduceLeft append split PromptString filterNot (_.trim == "") toList
+ val ActualPromptString = lines find matchesPrompt map (s =>
+ if (matchesString(s, PromptString)) PromptString else AltPromptString) getOrElse PromptString
+ val cmds = lines reduceLeft append split ActualPromptString filterNot (_.trim == "") toList
/** If it's a prompt or continuation line, strip the formatting bits and
* assemble the code. Otherwise ship it off to be analyzed for res references
@@ -67,10 +73,10 @@ abstract class Pasted {
*/
def fixResRefs(code: String, line: String) = line match {
case resCreation(resName) if referenced(resName) =>
- code.lastIndexOf(PromptString) match {
+ code.lastIndexOf(ActualPromptString) match {
case -1 => code
case idx =>
- val (str1, str2) = code splitAt (idx + PromptString.length)
+ val (str1, str2) = code splitAt (idx + ActualPromptString.length)
str2 match {
case resAssign(`resName`) => code
case _ => "%sval %s = { %s }".format(str1, resName, str2)
@@ -79,10 +85,10 @@ abstract class Pasted {
case _ => code
}
- def run() {
+ def run(): Unit = {
println("// Replaying %d commands from transcript.\n" format cmds.size)
cmds foreach { cmd =>
- print(PromptString)
+ print(ActualPromptString)
interpret(cmd)
}
}
diff --git a/src/repl/scala/tools/nsc/interpreter/ReplProps.scala b/src/repl/scala/tools/nsc/interpreter/ReplProps.scala
index 8c4faf7278..df65e9974d 100644
--- a/src/repl/scala/tools/nsc/interpreter/ReplProps.scala
+++ b/src/repl/scala/tools/nsc/interpreter/ReplProps.scala
@@ -6,12 +6,13 @@
package scala.tools.nsc
package interpreter
+import Properties.shellPromptString
import scala.sys._
import Prop._
class ReplProps {
private def bool(name: String) = BooleanProp.keyExists(name)
- private def int(name: String) = IntProp(name)
+ private def int(name: String) = Prop[Int](name)
// This property is used in TypeDebugging. Let's recycle it.
val colorOk = bool("scala.color")
@@ -21,6 +22,14 @@ class ReplProps {
val trace = bool("scala.repl.trace")
val power = bool("scala.repl.power")
+ // Handy system prop for shell prompt, or else pick it up from compiler.properties
+ val promptString = Prop[String]("scala.repl.prompt").option getOrElse (if (info) "%nscala %s> " else shellPromptString)
+ val prompt = {
+ import scala.io.AnsiColor.{ MAGENTA, RESET }
+ val p = promptString format Properties.versionNumberString
+ if (colorOk) s"$MAGENTA$p$RESET" else p
+ }
+
/** CSV of paged,across to enable pagination or `-x` style
* columns, "across" instead of down the column. Since
* pagination turns off columnar output, these flags are
diff --git a/src/repl/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala b/src/repl/scala/tools/nsc/interpreter/Tabulators.scala
index a8d537e314..75bec168eb 100644
--- a/src/repl/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala
+++ b/src/repl/scala/tools/nsc/interpreter/Tabulators.scala
@@ -3,60 +3,7 @@
* @author Paul Phillips
*/
-package scala.tools.nsc
-package interpreter
-
-import jline.console.{ ConsoleReader, CursorBuffer }
-
-trait ConsoleReaderHelper { _: ConsoleReader with Tabulator =>
- def isAcross: Boolean
-
- def terminal = getTerminal()
- def width = terminal.getWidth()
- def height = terminal.getHeight()
-
- def readOneKey(prompt: String): Int
- def eraseLine(): Unit
-
- val marginSize = 3
-
- private def morePrompt = "--More--"
- private def emulateMore(): Int = {
- val key = readOneKey(morePrompt)
- try key match {
- case '\r' | '\n' => 1
- case 'q' => -1
- case _ => height - 1
- }
- finally {
- eraseLine()
- // TODO: still not quite managing to erase --More-- and get
- // back to a scala prompt without another keypress.
- if (key == 'q') {
- putString(getPrompt())
- redrawLine()
- flush()
- }
- }
- }
-
- override def printColumns(items: JCollection[_ <: CharSequence]): Unit =
- printColumns_(items: List[String])
-
- private def printColumns_(items: List[String]): Unit = if (items exists (_ != "")) {
- val grouped = tabulate(items)
- var linesLeft = if (isPaginationEnabled()) height - 1 else Int.MaxValue
- grouped foreach { xs =>
- println(xs.mkString)
- linesLeft -= 1
- if (linesLeft <= 0) {
- linesLeft = emulateMore()
- if (linesLeft < 0)
- return
- }
- }
- }
-}
+package scala.tools.nsc.interpreter
trait Tabulator {
def isAcross: Boolean
@@ -72,7 +19,7 @@ trait Tabulator {
)
protected def columnize(ss: Seq[String]): Seq[Seq[String]] = ss map (s => Seq(s))
protected def printMultiLineColumns(items: Seq[String]): Seq[Seq[String]] = {
- import SimpleMath._
+ import scala.tools.nsc.interpreter.SimpleMath._
val longest = (items map (_.length)).max
val columnWidth = longest + marginSize
val maxcols = (
@@ -101,7 +48,7 @@ trait Tabulator {
/** Adjust the column width and number of columns to minimize the row count. */
trait VariColumnTabulator extends Tabulator {
override protected def printMultiLineColumns(items: Seq[String]): Seq[Seq[String]] = {
- import SimpleMath._
+ import scala.tools.nsc.interpreter.SimpleMath._
val longest = (items map (_.length)).max
val shortest = (items map (_.length)).min
val fattest = longest + marginSize
diff --git a/src/repl/scala/tools/nsc/interpreter/session/FileBackedHistory.scala b/src/repl/scala/tools/nsc/interpreter/session/FileBackedHistory.scala
deleted file mode 100644
index dddfb1b8f6..0000000000
--- a/src/repl/scala/tools/nsc/interpreter/session/FileBackedHistory.scala
+++ /dev/null
@@ -1,84 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2013 LAMP/EPFL
- * @author Paul Phillips
- */
-
-package scala.tools.nsc
-package interpreter
-package session
-
-import scala.tools.nsc.io._
-import FileBackedHistory._
-
-/** TODO: file locking.
- */
-trait FileBackedHistory extends JLineHistory with JPersistentHistory {
- def maxSize: Int
- protected lazy val historyFile: File = defaultFile
- private var isPersistent = true
-
- locally {
- load()
- }
-
- def withoutSaving[T](op: => T): T = {
- val saved = isPersistent
- isPersistent = false
- try op
- finally isPersistent = saved
- }
- def addLineToFile(item: CharSequence): Unit = {
- if (isPersistent)
- append(item + "\n")
- }
-
- /** Overwrites the history file with the current memory. */
- protected def sync(): Unit = {
- val lines = asStrings map (_ + "\n")
- historyFile.writeAll(lines: _*)
- }
- /** Append one or more lines to the history file. */
- protected def append(lines: String*): Unit = {
- historyFile.appendAll(lines: _*)
- }
-
- def load(): Unit = {
- if (!historyFile.canRead)
- historyFile.createFile()
-
- val lines: IndexedSeq[String] = {
- try historyFile.lines().toIndexedSeq
- catch {
- // It seems that control characters in the history file combined
- // with the default codec can lead to nio spewing exceptions. Rather
- // than abandon hope we'll try to read it as ISO-8859-1
- case _: Exception =>
- try historyFile.lines("ISO-8859-1").toIndexedSeq
- catch { case _: Exception => Vector() }
- }
- }
-
- repldbg("Loading " + lines.size + " into history.")
-
- // avoid writing to the history file
- withoutSaving(lines takeRight maxSize foreach add)
- // truncate the history file if it's too big.
- if (lines.size > maxSize) {
- repldbg("File exceeds maximum size: truncating to " + maxSize + " entries.")
- sync()
- }
- moveToEnd()
- }
-
- def flush(): Unit = ()
- def purge(): Unit = historyFile.truncate()
-}
-
-object FileBackedHistory {
- // val ContinuationChar = '\003'
- // val ContinuationNL: String = Array('\003', '\n').mkString
- import Properties.userHome
-
- def defaultFileName = ".scala_history"
- def defaultFile: File = File(Path(userHome) / defaultFileName)
-}
diff --git a/src/repl/scala/tools/nsc/interpreter/session/History.scala b/src/repl/scala/tools/nsc/interpreter/session/History.scala
index 794d41adc7..2028a13dfd 100644
--- a/src/repl/scala/tools/nsc/interpreter/session/History.scala
+++ b/src/repl/scala/tools/nsc/interpreter/session/History.scala
@@ -11,7 +11,10 @@ package session
* reference to the jline classes. Very sparse right now.
*/
trait History {
+ def historicize(text: String): Boolean = false
+
def asStrings: List[String]
+ def asStrings(from: Int, to: Int): List[String] = asStrings.slice(from, to)
def index: Int
def size: Int
}
diff --git a/src/repl/scala/tools/nsc/interpreter/session/JLineHistory.scala b/src/repl/scala/tools/nsc/interpreter/session/JLineHistory.scala
deleted file mode 100644
index 18e0ee7c85..0000000000
--- a/src/repl/scala/tools/nsc/interpreter/session/JLineHistory.scala
+++ /dev/null
@@ -1,49 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2013 LAMP/EPFL
- * @author Paul Phillips
- */
-
-package scala.tools.nsc
-package interpreter
-package session
-
-/** A straight scalification of the jline interface which mixes
- * in the sparse jline-independent one too.
- */
-trait JLineHistory extends JHistory with History {
- def size: Int
- def isEmpty: Boolean
- def index: Int
- def clear(): Unit
- def get(index: Int): CharSequence
- def add(line: CharSequence): Unit
- def replace(item: CharSequence): Unit
-
- def entries(index: Int): JListIterator[JEntry]
- def entries(): JListIterator[JEntry]
- def iterator: JIterator[JEntry]
-
- def current(): CharSequence
- def previous(): Boolean
- def next(): Boolean
- def moveToFirst(): Boolean
- def moveToLast(): Boolean
- def moveTo(index: Int): Boolean
- def moveToEnd(): Unit
-}
-
-object JLineHistory {
- class JLineFileHistory extends SimpleHistory with FileBackedHistory {
- override def add(item: CharSequence): Unit = {
- if (!isEmpty && last == item)
- repldbg("Ignoring duplicate entry '" + item + "'")
- else {
- super.add(item)
- addLineToFile(item)
- }
- }
- override def toString = "History(size = " + size + ", index = " + index + ")"
- }
-
- def apply(): JLineHistory = try new JLineFileHistory catch { case x: Exception => new SimpleHistory() }
-}
diff --git a/src/repl/scala/tools/nsc/interpreter/session/SimpleHistory.scala b/src/repl/scala/tools/nsc/interpreter/session/SimpleHistory.scala
index 7c49b91296..504d0d30ee 100644
--- a/src/repl/scala/tools/nsc/interpreter/session/SimpleHistory.scala
+++ b/src/repl/scala/tools/nsc/interpreter/session/SimpleHistory.scala
@@ -10,10 +10,9 @@ package session
import scala.collection.mutable.{ Buffer, ListBuffer }
import scala.collection.JavaConverters._
-class SimpleHistory extends JLineHistory {
+class SimpleHistory extends History {
private var _index: Int = 0
- private val buf: Buffer[String] = new ListBuffer[String]
- private def toEntries(): Seq[JEntry] = buf.zipWithIndex map { case (x, i) => Entry(i, x) }
+ protected val buf: Buffer[String] = new ListBuffer[String]
private def setTo(num: Int) = { _index = num ; true }
private def minusOne = { _index -= 1 ; true }
private def plusOne = { _index += 1 ; true }
@@ -25,10 +24,6 @@ class SimpleHistory extends JLineHistory {
""
}
- case class Entry(index: Int, value: CharSequence) extends JEntry {
- override def toString = value
- }
-
def maxSize: Int = 2500
def last = if (isEmpty) fail("last") else buf.last
@@ -42,9 +37,6 @@ class SimpleHistory extends JLineHistory {
buf trimEnd 1
add(item)
}
- def entries(idx: Int): JListIterator[JEntry] = toEntries().asJava.listIterator(idx)
- def entries(): JListIterator[JEntry] = toEntries().asJava.listIterator()
- def iterator: JIterator[JEntry] = toEntries().iterator.asJava
def remove(idx: Int): CharSequence = buf remove idx
def removeFirst(): CharSequence = buf remove 0
diff --git a/src/repl/scala/tools/nsc/interpreter/session/package.scala b/src/repl/scala/tools/nsc/interpreter/session/package.scala
index a3d7312c98..06e7f6207b 100644
--- a/src/repl/scala/tools/nsc/interpreter/session/package.scala
+++ b/src/repl/scala/tools/nsc/interpreter/session/package.scala
@@ -14,10 +14,5 @@ package object session {
type JIterator[T] = java.util.Iterator[T]
type JListIterator[T] = java.util.ListIterator[T]
- type JEntry = jline.console.history.History.Entry
- type JHistory = jline.console.history.History
- type JMemoryHistory = jline.console.history.MemoryHistory
- type JPersistentHistory = jline.console.history.PersistentHistory
-
private[interpreter] implicit def charSequenceFix(x: CharSequence): String = x.toString
}