Skip to content

Commit b77abad

Browse files
committed
REPL selectively trims prefix/suffix newline
ScalaRunTime.replStringOf adds extra newlines. Try not to trim more than was added. New API will not include the newlines.
1 parent abbbcef commit b77abad

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

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

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,29 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None) {
5555
// We need to use the ScalaRunTime class coming from the scala-library
5656
// on the user classpath, and not the one available in the current
5757
// classloader, so we use reflection instead of simply calling
58-
// `ScalaRunTime.replStringOf`.
58+
// `ScalaRunTime.replStringOf`. Probe for new API without extraneous newlines.
59+
// For old API, try to clean up extraneous newlines by stripping suffix and maybe prefix newline.
5960
val scalaRuntime = Class.forName("scala.runtime.ScalaRunTime", true, myClassLoader)
60-
val meth = scalaRuntime.getMethod("replStringOf", classOf[Object], classOf[Int])
61-
62-
(value: Object) => meth.invoke(null, value, Integer.valueOf(MaxStringElements)).asInstanceOf[String]
61+
try {
62+
val meth = scalaRuntime.getMethod("replStringOf", classOf[Object], classOf[Int], classOf[Boolean])
63+
val truly = java.lang.Boolean.TRUE
64+
65+
(value: Object) => meth.invoke(null, value, Integer.valueOf(MaxStringElements), truly).asInstanceOf[String]
66+
} catch {
67+
case _: NoSuchMethodException =>
68+
val meth = scalaRuntime.getMethod("replStringOf", classOf[Object], classOf[Int])
69+
70+
(value: Object) => {
71+
val res = meth.invoke(null, value, Integer.valueOf(MaxStringElements)).asInstanceOf[String]
72+
val len = res.length()
73+
if len == 0 || res.charAt(len-1) != '\n' then
74+
res
75+
else if len == 1 || res.charAt(0) != '\n' then
76+
res.substring(0, len-1)
77+
else
78+
res.substring(1, len-1)
79+
}
80+
}
6381
}
6482
myClassLoader
6583
}
@@ -82,7 +100,7 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None) {
82100
resObj
83101
.getDeclaredMethods.find(_.getName == sym.name.encode.toString)
84102
.map(_.invoke(null))
85-
val string = value.map(replStringOf(_).trim)
103+
val string = value.map(replStringOf(_))
86104
if (!sym.is(Flags.Method) && sym.info == defn.UnitType)
87105
None
88106
else

0 commit comments

Comments
 (0)