Skip to content

Commit

Permalink
Invert case class detection logic
Browse files Browse the repository at this point in the history
  • Loading branch information
OndrejSpanel committed Sep 1, 2022
1 parent fb02719 commit f2d3d4e
Showing 1 changed file with 7 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@ object QuicklensMacros {
fields: Seq[(PathSymbol.Field, Seq[PathTree])]
): Term = {
val objSymbol = obj.tpe.typeSymbol
if objSymbol.flags.is(Flags.Case) then {
if !(objSymbol.flags.is(Flags.Enum) ||
(objSymbol.flags.is(Flags.Sealed) && (objSymbol.flags.is(Flags.Trait) || objSymbol.flags.is(Flags.Abstract))))
then {
val copy = termMethodByNameUnsafe(obj, "copy")
val argsMap: Map[Int, Term] = fields.map { (field, trees) =>
val (fieldMethod, idx) = termAccessorMethodByNameUnsafe(obj, field.name)
Expand All @@ -185,11 +187,9 @@ object QuicklensMacros {
case AppliedType(_, typeParams) => Apply(TypeApply(Select(obj, copy), typeParams.map(Inferred(_))), args)
case _ => Apply(Select(obj, copy), args)
}
} else if objSymbol.flags.is(Flags.Enum) ||
(objSymbol.flags.is(Flags.Sealed) && (objSymbol.flags.is(Flags.Trait) || objSymbol.flags.is(Flags.Abstract)))
then {
} else {
// if the source is a sealed trait / sealed abstract class / enum, generating a if-then-else with a .copy for each child (implementing case class)
val cases = obj.tpe.typeSymbol.children.map { child =>
val cases = objSymbol.children.map { child =>
val subtype = TypeIdent(child)
val bind = Symbol.newBind(owner, "c", Flags.EmptyFlags, subtype.tpe)
CaseDef(Bind(bind, Typed(Ref(bind), subtype)), None, caseClassCopy(owner, mod, Ref(bind), fields))
Expand All @@ -201,7 +201,7 @@ object QuicklensMacros {
...
else throw new IllegalStateException()
*/
val ifThens = obj.tpe.typeSymbol.children.map { child =>
val ifThens = objSymbol.children.map { child =>
val ifCond = TypeApply(Select.unique(obj, "isInstanceOf"), List(TypeIdent(child)))

val ifThen = ValDef.let(owner, TypeApply(Select.unique(obj, "asInstanceOf"), List(TypeIdent(child)))) {
Expand All @@ -216,8 +216,7 @@ object QuicklensMacros {
ifThens.foldRight(elseThrow) { case ((ifCond, ifThen), ifElse) =>
If(ifCond, ifThen, ifElse)
}
} else
report.throwError(s"Unsupported source object: must be a case class or sealed trait, but got: $objSymbol")
}
}

def applyFunctionDelegate(
Expand Down

0 comments on commit f2d3d4e

Please sign in to comment.