Skip to content

Commit 549dcbd

Browse files
committed
REPL - invoke pprint reflectively
fixes #24111
1 parent 9d428fd commit 549dcbd

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

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

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,32 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None):
2626

2727
var myClassLoader: AbstractFileClassLoader = uninitialized
2828

29+
private var BlackWhite: AnyRef = uninitialized
30+
private var BlackWhite_apply: java.lang.reflect.Method = uninitialized
31+
private var FansiStr_plainText: java.lang.reflect.Method = uninitialized
32+
private var pprintLoaded: Boolean = false
33+
private def pprintRender(value: Any, width: Int, height: Int, initialOffset: Int)(using Context): String = {
34+
val cl = classLoader()
35+
if !pprintLoaded then
36+
val pprintCls = Class.forName("dotty.shaded.pprint.PPrinter$BlackWhite$", false, cl)
37+
BlackWhite = pprintCls.getField("MODULE$").get(null)
38+
BlackWhite_apply = pprintCls.getMethod("apply",
39+
classOf[Any], // value
40+
classOf[Int], // width
41+
classOf[Int], // height
42+
classOf[Int], // indentation
43+
classOf[Int], // initialOffset
44+
classOf[Boolean], // escape Unicode
45+
classOf[Boolean], // show field names
46+
)
47+
val fansiStrCls = Class.forName("dotty.shaded.fansi.Str", false, cl)
48+
FansiStr_plainText = fansiStrCls.getMethod("plainText")
49+
pprintLoaded = true // final statement to guard for exceptions
50+
end if
51+
val fansiStr = BlackWhite_apply.invoke(BlackWhite, value, width, height, 2, initialOffset, false, true)
52+
FansiStr_plainText.invoke(fansiStr).asInstanceOf[String]
53+
}
54+
2955

3056
/** Class loader used to load compiled code */
3157
private[repl] def classLoader()(using Context) =
@@ -44,6 +70,7 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None):
4470
}
4571

4672
myClassLoader = new AbstractFileClassLoader(ctx.settings.outputDir.value, parent)
73+
pprintLoaded = false // reset pprint if we change classloader
4774
myClassLoader
4875
}
4976

@@ -55,7 +82,8 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None):
5582
/** Return a String representation of a value we got from `classLoader()`. */
5683
private[repl] def replStringOf(sym: Symbol, value: Object)(using Context): String = {
5784
// pretty-print things with 100 cols 50 rows by default,
58-
dotty.shaded.pprint.PPrinter.BlackWhite.apply(value, width = 100, height = 50).plainText
85+
// dotty.shaded.pprint.PPrinter.BlackWhite.apply(value, width = 100, height = 50).plainText
86+
pprintRender(value, width = 100, height = 50, initialOffset = 0 /* TODO: include offset */)
5987
}
6088

6189
/** Load the value of the symbol using reflection.

0 commit comments

Comments
 (0)