Skip to content

Fix Constant tag of Expr(null: String) #23064

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion compiler/src/scala/quoted/runtime/impl/QuotesImpl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2529,7 +2529,12 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
end StringConstantTypeTest

object StringConstant extends StringConstantModule:
def apply(x: String): StringConstant = dotc.core.Constants.Constant(x)
def apply(x: String): StringConstant =
require(x != null, "StringConstant cannot be null")
// A `null` constant must be represented as a `NullConstant`, c.f. a
// constant with `tag == NullTag`, which is not a `StringConstant`.
// See issue 23008.
dotc.core.Constants.Constant(x)
def unapply(constant: StringConstant): Some[String] = Some(constant.stringValue)
end StringConstant

Expand Down
8 changes: 7 additions & 1 deletion library/src/scala/quoted/ToExpr.scala
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,13 @@ object ToExpr {
given StringToExpr[T <: String]: ToExpr[T] with {
def apply(x: T)(using Quotes) =
import quotes.reflect.*
Literal(StringConstant(x)).asExpr.asInstanceOf[Expr[T]]
val literal =
if (x: Any) == null then
// Can happen if called from code without `-Yexplicit-nulls`.
Literal(NullConstant())
else
Literal(StringConstant(x))
literal.asExpr.asInstanceOf[Expr[T]]
}

/** Default implementation of `ToExpr[Class[T]]` */
Expand Down
1 change: 1 addition & 0 deletions tests/run-macros/i23008.check
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
null
12 changes: 12 additions & 0 deletions tests/run-macros/i23008/Macros_1.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import scala.quoted.*

object Macros {
inline def buildString = ${buildStringCode}

def buildStringCode(using Quotes): Expr[String] = {
import quotes.reflect.*
val str: String = null
val exprString = Expr(str)
Expr(exprString.show)
}
}
2 changes: 2 additions & 0 deletions tests/run-macros/i23008/Test_2.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
@main def Test =
println(Macros.buildString)
Loading