@@ -2,7 +2,10 @@ package dotty.tools
2
2
package dotc
3
3
package repl
4
4
5
- import java .io .{File , PrintWriter , StringWriter , Writer }
5
+ import java .io .{
6
+ File , PrintWriter , PrintStream , StringWriter , Writer , OutputStream ,
7
+ ByteArrayOutputStream => ByteOutputStream
8
+ }
6
9
import java .lang .{Class , ClassLoader }
7
10
import java .net .{URL , URLClassLoader }
8
11
@@ -384,6 +387,24 @@ class CompilingInterpreter(out: PrintWriter, ictx: Context) extends Compiler wit
384
387
names1 ++ names2
385
388
}
386
389
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
+
387
408
/** load and run the code using reflection.
388
409
* @return A pair consisting of the run's result as a string, and
389
410
* a boolean indicating whether the run succeeded without throwing
@@ -392,20 +413,20 @@ class CompilingInterpreter(out: PrintWriter, ictx: Context) extends Compiler wit
392
413
def loadAndRun (): (List [String ], Boolean ) = {
393
414
val interpreterResultObject : Class [_] =
394
415
Class .forName(resultObjectName, true , classLoader)
395
- val resultValMethod : java.lang.reflect.Method =
416
+ val valMethodRes : java.lang.reflect.Method =
396
417
interpreterResultObject.getMethod(" result" )
397
418
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" )
402
423
val printList =
403
424
if (prints == " " ) Nil
404
425
else prints :: Nil
405
426
406
427
if (! delayOutput) out.print(prints)
407
428
408
- (printList :+ new String ( res) , true )
429
+ (printList :+ res, true )
409
430
}
410
431
} catch {
411
432
case NonFatal (ex) =>
0 commit comments