Skip to content

Commit fdf2424

Browse files
committed
Redirect System.{err,out} and Console.{err,out} in REPL
1 parent 952fb20 commit fdf2424

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

src/dotty/tools/dotc/repl/CompilingInterpreter.scala

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ package dotty.tools
22
package dotc
33
package repl
44

5-
import java.io.{File, PrintWriter, StringWriter, Writer}
5+
import java.io.{
6+
File, PrintWriter, PrintStream, StringWriter, Writer, OutputStream,
7+
ByteArrayOutputStream => ByteOutputStream
8+
}
69
import java.lang.{Class, ClassLoader}
710
import java.net.{URL, URLClassLoader}
811

@@ -384,6 +387,24 @@ class CompilingInterpreter(out: PrintWriter, ictx: Context) extends Compiler wit
384387
names1 ++ names2
385388
}
386389

390+
/** Sets both System.{out,err} and Console.{out,err} to supplied
391+
* `os: OutputStream`
392+
*/
393+
private def withOutput[T](os: ByteOutputStream)(op: ByteOutputStream => T) = {
394+
val ps = new PrintStream(os)
395+
val oldOut = System.out
396+
val oldErr = System.err
397+
System.setOut(ps)
398+
System.setErr(ps)
399+
400+
try {
401+
Console.withOut(os)(Console.withErr(os)(op(os)))
402+
} finally {
403+
System.setOut(oldOut)
404+
System.setErr(oldErr)
405+
}
406+
}
407+
387408
/** load and run the code using reflection.
388409
* @return A pair consisting of the run's result as a string, and
389410
* a boolean indicating whether the run succeeded without throwing
@@ -392,20 +413,20 @@ class CompilingInterpreter(out: PrintWriter, ictx: Context) extends Compiler wit
392413
def loadAndRun(): (List[String], Boolean) = {
393414
val interpreterResultObject: Class[_] =
394415
Class.forName(resultObjectName, true, classLoader)
395-
val resultValMethod: java.lang.reflect.Method =
416+
val valMethodRes: java.lang.reflect.Method =
396417
interpreterResultObject.getMethod("result")
397418
try {
398-
val ps = new java.io.ByteArrayOutputStream()
399-
Console.withOut(ps) {
400-
val res = SyntaxHighlighting(resultValMethod.invoke(interpreterResultObject).toString).toArray
401-
val prints = ps.toString("utf-8")
419+
withOutput(new ByteOutputStream) { ps =>
420+
val rawRes = valMethodRes.invoke(interpreterResultObject).toString
421+
val res = new String(SyntaxHighlighting(rawRes).toArray)
422+
val prints = ps.toString("utf-8")
402423
val printList =
403424
if (prints == "") Nil
404425
else prints :: Nil
405426

406427
if (!delayOutput) out.print(prints)
407428

408-
(printList :+ new String(res), true)
429+
(printList :+ res, true)
409430
}
410431
} catch {
411432
case NonFatal(ex) =>

0 commit comments

Comments
 (0)