Skip to content

Commit 297baac

Browse files
committed
enhance explicit generics rule to handle companion apply methods
1 parent e218978 commit 297baac

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

analyzer/src/main/scala/com/avsystem/commons/analyzer/ExplicitGenerics.scala

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import scala.tools.nsc.Global
55

66
class ExplicitGenerics(g: Global) extends AnalyzerRule(g, "explicitGenerics") {
77

8-
import global._
8+
import global.*
99

1010
lazy val explicitGenericsAnnotTpe = classType("com.avsystem.commons.annotation.explicitGenerics")
1111

@@ -17,16 +17,29 @@ class ExplicitGenerics(g: Global) extends AnalyzerRule(g, "explicitGenerics") {
1717
def requiresExplicitGenerics(sym: Symbol): Boolean =
1818
sym != NoSymbol && (sym :: sym.overrides).flatMap(_.annotations).exists(_.tree.tpe <:< explicitGenericsAnnotTpe)
1919

20+
def applyOfAnnotatedCompanion(preSym: Symbol): Boolean = {
21+
if (preSym != NoSymbol && preSym.isMethod && preSym.name == TermName("apply")) {
22+
val owner = preSym.owner
23+
val companionCls =
24+
if (owner.isModuleClass) owner.companionClass
25+
else if (owner.isModule) owner.moduleClass.companionClass
26+
else NoSymbol
27+
requiresExplicitGenerics(companionCls)
28+
} else false
29+
}
30+
2031
def analyzeTree(tree: Tree): Unit = analyzer.macroExpandee(tree) match {
2132
case `tree` | EmptyTree =>
2233
tree match {
23-
case t@TypeApply(pre, args) if requiresExplicitGenerics(pre.symbol) =>
34+
case t@TypeApply(pre, args) if requiresExplicitGenerics(pre.symbol) || applyOfAnnotatedCompanion(pre.symbol) =>
2435
val inferredTypeParams = args.forall {
2536
case tt: TypeTree => tt.original == null || tt.original == EmptyTree
2637
case _ => false
2738
}
2839
if (inferredTypeParams) {
29-
fail(t.pos, pre.symbol)
40+
// If we're on companion.apply, report on the class symbol for clearer message
41+
val targetSym = if (applyOfAnnotatedCompanion(pre.symbol)) pre.symbol.owner.companionClass else pre.symbol
42+
fail(t.pos, targetSym)
3043
}
3144
case n@New(tpt) if requiresExplicitGenerics(tpt.tpe.typeSymbol) =>
3245
val explicitTypeArgsProvided = tpt match {
@@ -45,6 +58,7 @@ class ExplicitGenerics(g: Global) extends AnalyzerRule(g, "explicitGenerics") {
4558
case prevTree =>
4659
analyzeTree(prevTree)
4760
}
61+
4862
analyzeTree(unit.body)
4963
}
5064
}

0 commit comments

Comments
 (0)