Skip to content

Commit 9282a66

Browse files
authored
Liftables: refactor; differentiate matcher body (#2893)
1 parent 7374b2d commit 9282a66

File tree

1 file changed

+15
-17
lines changed

1 file changed

+15
-17
lines changed

scalameta/common/shared/src/main/scala/org/scalameta/adt/Liftables.scala

+15-17
Original file line numberDiff line numberDiff line change
@@ -59,25 +59,25 @@ class LiftableMacros(val c: Context) extends AdtReflection {
5959
val defNames =
6060
adts.map(adt => c.freshName(TermName("lift" + adt.prefix.capitalize.replace(".", ""))))
6161
val liftAdts = adts.zip(defNames).map { case (adt, defName) =>
62-
val matcher: DefDef = customMatcher(adt, defName, localName).getOrElse({
62+
val matcher: DefDef = customMatcher(adt, defName, localName).getOrElse {
6363
val init = q"""$u.Ident($u.TermName("_root_"))""": Tree
64-
val namePath = adt.sym.fullName
65-
.split('.')
66-
.foldLeft(init)((acc, part) => q"$u.Select($acc, $u.TermName($part))")
67-
val fields = adt match { case leaf: Leaf => leaf.fields; case _ => Nil }
68-
val args = fields.map(f => {
69-
val fieldName = q"$u.Ident($u.TermName(${f.name.toString}))"
70-
val fieldValue =
64+
def getNamePath(parts: Iterable[String]): Tree =
65+
parts.foldLeft(init) { (acc, part) => q"$u.Select($acc, $u.TermName($part))" }
66+
val nameParts = adt.sym.fullName.split('.')
67+
val body = if (adt.sym.isClass) {
68+
val fields = adt match { case leaf: Leaf => leaf.fields; case _ => Nil }
69+
val args = fields.map { f =>
7170
q"_root_.scala.Predef.implicitly[$u.Liftable[${f.tpe}]].apply($localName.${f.name})"
7271
// NOTE: we can't really use AssignOrNamedArg here, sorry
7372
// Test.scala:10: warning: type-checking the invocation of method apply checks if the named argument expression 'stats = ...' is a valid assignment
7473
// in the current scope. The resulting type inference error (see above) can be fixed by providing an explicit type in the local definition for stats.
7574
// q"$u.AssignOrNamedArg($fieldName, $fieldValue)"
76-
q"$fieldValue"
77-
})
78-
val body = if (adt.sym.isClass) q"$u.Apply($namePath, $args)" else q"$namePath"
75+
}
76+
val namePath = getNamePath(nameParts)
77+
q"""$u.Apply($namePath, $args)"""
78+
} else getNamePath(nameParts)
7979
q"def $defName($localName: ${adt.tpe}): $u.Tree = $body"
80-
})
80+
}
8181
val body: Tree = customWrapper(adt, defName, localName, matcher.rhs).getOrElse(matcher.rhs)
8282
treeCopy.DefDef(
8383
matcher,
@@ -89,11 +89,9 @@ class LiftableMacros(val c: Context) extends AdtReflection {
8989
body
9090
)
9191
}
92-
val clauses = adts
93-
.zip(defNames)
94-
.map({ case (adt, name) =>
95-
cq"$localName: ${adt.tpe} => $name($localName.asInstanceOf[${adt.tpe}])"
96-
})
92+
val clauses = adts.zip(defNames).map { case (adt, name) =>
93+
cq"$localName: ${adt.tpe} => $name($localName.asInstanceOf[${adt.tpe}])"
94+
}
9795
q"""
9896
$u.Liftable(($mainParam: ${weakTypeOf[T]}) => {
9997
object $mainModule {

0 commit comments

Comments
 (0)