Skip to content

Commit e0fbfde

Browse files
committed
Accept null in StringToExpr but not in StringConstant
1 parent bbe2dde commit e0fbfde

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

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

+6-1
Original file line numberDiff line numberDiff line change
@@ -2529,7 +2529,12 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
25292529
end StringConstantTypeTest
25302530

25312531
object StringConstant extends StringConstantModule:
2532-
def apply(x: String): StringConstant = dotc.core.Constants.Constant(x: Any)
2532+
def apply(x: String): StringConstant =
2533+
require(x != null, "StringConstant cannot be null")
2534+
// A `null` constant must be represented as a `NullConstant`, c.f. a
2535+
// constant with `tag == NullTag`, which is not a `StringConstant`.
2536+
// See issue 23008.
2537+
dotc.core.Constants.Constant(x)
25332538
def unapply(constant: StringConstant): Some[String] = Some(constant.stringValue)
25342539
end StringConstant
25352540

library/src/scala/quoted/ToExpr.scala

+7-1
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)