Skip to content
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

Fix macro crash when handling sealed case classes #634

Merged
merged 2 commits into from
Sep 28, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -219,12 +219,14 @@ object Macros {
fail(tpe, _),
)


val sealedClassSymbol: Option[Symbol] = sealedParents.find(_ == tpe.typeSymbol)
val segments =
sealedParents
sealedClassSymbol.toList.map(_.fullName.split('.')) ++
sealedParents
.flatMap(_.asClass.knownDirectSubclasses)
.map(_.fullName.split('.'))


// -1 because even if there is only one subclass, and so no name segments
// are needed to differentiate between them, we want to keep at least
// the rightmost name segment
Expand Down
7 changes: 5 additions & 2 deletions upickle/implicits/src-3/upickle/implicits/macros.scala
Original file line number Diff line number Diff line change
Expand Up @@ -309,12 +309,15 @@ def tagNameImpl0[T](transform: String => String)(using Quotes, Type[T]): Expr[St
inline def shortTagName[T]: String = ${ shortTagNameImpl[T] }
def shortTagNameImpl[T](using Quotes, Type[T]): Expr[String] =
import quotes.reflect._
val sym = TypeTree.of[T].symbol
val sealedClassSymbol = if (TypeRepr.of[T].baseClasses.contains(TypeRepr.of[T].typeSymbol))
Some(TypeRepr.of[T].typeSymbol.fullName.split('.'))
else None
val segments = TypeRepr.of[T].baseClasses
.filter(_.flags.is(Flags.Sealed))
.flatMap(_.children)
.filter(_.flags.is(Flags.Case))
.map(_.fullName.split('.'))
.map(_.fullName.split('.')) ++
sealedClassSymbol.toList

val identicalSegmentCount = Range(0, segments.map(_.length).max - 1)
.takeWhile(i => segments.map(_.lift(i)).distinct.size == 1)
Expand Down
9 changes: 9 additions & 0 deletions upickle/test/src/upickle/MacroTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ import upickle.default.{read, write, ReadWriter => RW}

case class Trivial(a: Int = 1)

sealed case class SealedClass(i: Int, s: String)
object SealedClass {
implicit val rw: RW[SealedClass] = upickle.default.macroRW
}

case class KeyedPerson(
@upickle.implicits.key("first_name") firstName: String = "N/A",
@upickle.implicits.key("last_name") lastName: String)
Expand Down Expand Up @@ -872,5 +877,9 @@ object MacroTests extends TestSuite {
)

}

test("sealedClass"){
assert(write(SealedClass(3, "Hello")) == """{"$type":"SealedClass","i":3,"s":"Hello"}""")
}
}
}
Loading