Skip to content

Commit 29d76b9

Browse files
mboveltgodzik
authored andcommitted
Accept null in StringToExpr but not in StringConstant
[Cherry-picked e0fbfde]
1 parent 3ebc82b commit 29d76b9

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

compiler/src/scala/quoted/runtime/impl/QuotesImpl.scala

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2419,7 +2419,12 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
24192419
end StringConstantTypeTest
24202420

24212421
object StringConstant extends StringConstantModule:
2422-
def apply(x: String): StringConstant = dotc.core.Constants.Constant(x: Any)
2422+
def apply(x: String): StringConstant =
2423+
require(x != null, "StringConstant cannot be null")
2424+
// A `null` constant must be represented as a `NullConstant`, c.f. a
2425+
// constant with `tag == NullTag`, which is not a `StringConstant`.
2426+
// See issue 23008.
2427+
dotc.core.Constants.Constant(x)
24232428
def unapply(constant: StringConstant): Some[String] = Some(constant.stringValue)
24242429
end StringConstant
24252430

library/src/scala/quoted/ToExpr.scala

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,13 @@ object ToExpr {
7777
given StringToExpr[T <: String]: ToExpr[T] with {
7878
def apply(x: T)(using Quotes) =
7979
import quotes.reflect.*
80-
Literal(StringConstant(x)).asExpr.asInstanceOf[Expr[T]]
80+
val literal =
81+
if (x: Any) == null then
82+
// Can happen if called from code without `-Yexplicit-nulls`.
83+
Literal(NullConstant())
84+
else
85+
Literal(StringConstant(x))
86+
literal.asExpr.asInstanceOf[Expr[T]]
8187
}
8288

8389
/** Default implementation of `ToExpr[Class[T]]` */

0 commit comments

Comments
 (0)