Skip to content
New issue

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

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

Already on GitHub? # to your account

Access nested defaults through this to avoid stack overflow #1238

Merged
merged 1 commit into from
Feb 11, 2022
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
21 changes: 12 additions & 9 deletions core/src/main/scala/shapeless/default.scala
Original file line number Diff line number Diff line change
Expand Up @@ -243,15 +243,18 @@ class DefaultMacros(val c: whitebox.Context) extends CaseClassMacros {
alt => alt.isMethod && hasDefaultParams(alt.asMethod)
}

def defaultsFor(fields: List[(TermName, Type)]) = for {
((_, argTpe), i) <- fields.zipWithIndex
default = tpe.companion.member(TermName(s"apply$$default$$${i + 1}")) orElse
altCompanion.member(TermName(s"$$lessinit$$greater$$default$$${i + 1}"))
} yield if (default.isTerm) {
val defaultTpe = appliedType(someTpe, devarargify(argTpe))
val defaultVal = some(q"$companion.$default")
(defaultTpe, defaultVal)
} else (noneTpe, none)
def defaultsFor(fields: List[(TermName, Type)]) = {
lazy val enclosing = ownerChain(c.internal.enclosingOwner)
for (((_, argTpe), i) <- fields.zipWithIndex) yield {
val default = tpe.companion.member(TermName(s"apply$$default$$${i + 1}")) orElse
altCompanion.member(TermName(s"$$lessinit$$greater$$default$$${i + 1}"))
if (default.isTerm) {
val owner = default.owner
val qualifier = if (!owner.isStatic && enclosing.contains(owner)) This(owner) else companion
(appliedType(someTpe, devarargify(argTpe)), some(q"$qualifier.$default"))
} else (noneTpe, none)
}
}

def mkDefault(defaults: List[(Type, Tree)]) = {
val (types, values) = defaults.unzip
Expand Down
10 changes: 10 additions & 0 deletions core/src/test/scala/shapeless/default.scala
Original file line number Diff line number Diff line change
Expand Up @@ -224,4 +224,14 @@ class DefaultTests {
assertTypedEquals[None.type :: HNil](None :: HNil, default2())
assertTypedEquals[HNil](HNil, default3())
}

@Test
def testInCompanion: Unit =
assertEquals(InCompanion.default, Some(9) :: HNil)

// Note: this has to be inside a class, not an object
case class InCompanion(a: Int = 9)
object InCompanion {
val default = Default[InCompanion].apply()
}
}