Skip to content

Commit 6d06cce

Browse files
authored
Merge pull request #3940 from dotty-staging/fix-repl-scripted
Override Console.out and Console.err the REPL
2 parents 0cf569f + f068bea commit 6d06cce

File tree

2 files changed

+24
-16
lines changed

2 files changed

+24
-16
lines changed

compiler/src/dotty/tools/repl/ReplDriver.scala

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ case class Completions(cursor: Int,
8181

8282
/** Main REPL instance, orchestrating input, compilation and presentation */
8383
class ReplDriver(settings: Array[String],
84-
protected val out: PrintStream = System.out,
84+
protected val out: PrintStream = Console.out,
8585
protected val classLoader: Option[ClassLoader] = None) extends Driver {
8686

8787
/** Overridden to `false` in order to not have to give sources on the
@@ -135,26 +135,32 @@ class ReplDriver(settings: Array[String],
135135
* observable outside of the CLI, for this reason, most helper methods are
136136
* `protected final` to facilitate testing.
137137
*/
138-
@tailrec final def runUntilQuit(state: State = initState): State = {
139-
val res = readLine()(state)
138+
final def runUntilQuit(): State = {
139+
@tailrec def loop(state: State): State = {
140+
val res = readLine()(state)
140141

141-
if (res == Quit) {
142-
out.println()
143-
state
144-
}
145-
else {
146-
// readLine potentially destroys the run, so a new one is needed for the
147-
// rest of the interpretation:
148-
implicit val freshState = state.newRun(compiler, rootCtx)
149-
runUntilQuit(interpret(res))
142+
if (res == Quit) {
143+
out.println()
144+
state
145+
}
146+
else {
147+
// readLine potentially destroys the run, so a new one is needed for the
148+
// rest of the interpretation:
149+
implicit val freshState = state.newRun(compiler, rootCtx)
150+
loop(interpret(res))
151+
}
150152
}
153+
154+
withRedirectedOutput { loop(initState) }
151155
}
152156

153-
final def run(input: String)(implicit state: State): State =
154-
run(ParseResult(input)(state.run.runContext))(state.newRun(compiler, rootCtx))
157+
final def run(input: String)(implicit state: State): State = withRedirectedOutput {
158+
val parsed = ParseResult(input)(state.run.runContext)
159+
interpret(parsed)(state.newRun(compiler, rootCtx))
160+
}
155161

156-
final def run(res: ParseResult)(implicit state: State): State =
157-
interpret(res)
162+
private def withRedirectedOutput(op: => State): State =
163+
Console.withOut(out) { Console.withErr(out) { op } }
158164

159165
/** Extract possible completions at the index of `cursor` in `expr` */
160166
protected[this] final def completions(cursor: Int, expr: String, state0: State): Completions = {
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
scala> println("Hello World!")
2+
Hello World!

0 commit comments

Comments
 (0)