Skip to content

Commit 83bacf2

Browse files
committed
Add null-check to <id>Show method
Previously if user code was equal to null, then the accompanying show method would in effect call `null.show` which would crash the repl in a mysterious way.
1 parent 2fd10d9 commit 83bacf2

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

repl/src/dotty/tools/repl/ReplCompiler.scala

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import dotc.ast.{ untpd, tpd }
88
import dotc.{ Run, CompilationUnit, Compiler }
99
import dotc.core.Decorators._, dotc.core.Flags._, dotc.core.Phases
1010
import dotc.core.Names._, dotc.core.Contexts._, dotc.core.StdNames._
11+
import dotc.core.Constants.Constant
1112
import dotc.util.SourceFile
1213
import dotc.typer.{ ImportInfo, FrontEnd }
1314
import backend.jvm.GenBCode
@@ -68,7 +69,13 @@ class ReplCompiler(val directory: AbstractFile) extends Compiler {
6869
def createShow(name: TermName, pos: Position) = {
6970
val showName = name ++ "Show"
7071
val select = Select(Ident(name), "show".toTermName)
71-
DefDef(showName, Nil, Nil, TypeTree(), select).withFlags(Synthetic).withPos(pos)
72+
val valAsAnyRef = TypeApply(Select(Ident(name), nme.asInstanceOf_),
73+
List(Ident(tpnme.AnyRef)))
74+
val cond = InfixOp(valAsAnyRef,
75+
Ident(nme.EQ),
76+
Literal(Constant(null)))
77+
val showWithNullCheck = If(cond, Literal(Constant("null")), select)
78+
DefDef(showName, Nil, Nil, TypeTree(), showWithNullCheck).withFlags(Synthetic).withPos(pos)
7279
}
7380

7481
val (exps, other) = trees.partition(_.isTerm)
@@ -181,6 +188,8 @@ class ReplCompiler(val directory: AbstractFile) extends Compiler {
181188
defs <- definitions(parsed.trees, state)
182189
unit <- createUnit(defs, parsed.sourceCode)
183190
state <- runCompilation(unit, defs.state)
191+
_ = println(unit.untpdTree.show(state.run.runContext))
192+
_ = println(unit.tpdTree.show(state.run.runContext))
184193
} yield (unit, state)
185194
}
186195

repl/test-resources/repl/renderNull

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
scala> val x: String = null
2+
val x: String = null

0 commit comments

Comments
 (0)