Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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 @@ -9,7 +9,11 @@ class ExplicitGenerics(g: Global) extends AnalyzerRule(g, "explicitGenerics") {

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

def analyze(unit: CompilationUnit) = if (explicitGenericsAnnotTpe != NoType) {

private def fail(pos: Position, symbol: Symbol): Unit =
report(pos, s"$symbol requires that its type arguments are explicit (not inferred)")

def analyze(unit: CompilationUnit): Unit = if (explicitGenericsAnnotTpe != NoType) {
def requiresExplicitGenerics(sym: Symbol): Boolean =
sym != NoSymbol && (sym :: sym.overrides).flatMap(_.annotations).exists(_.tree.tpe <:< explicitGenericsAnnotTpe)

Expand All @@ -22,7 +26,18 @@ class ExplicitGenerics(g: Global) extends AnalyzerRule(g, "explicitGenerics") {
case _ => false
}
if (inferredTypeParams) {
report(t.pos, s"${pre.symbol} requires that its type arguments are explicit (not inferred)")
fail(t.pos, pre.symbol)
}
case n@New(tpt) if requiresExplicitGenerics(tpt.tpe.typeSymbol) =>
val explicitTypeArgsProvided = tpt match {
case tt: TypeTree => tt.original match {
case AppliedTypeTree(_, args) if args.nonEmpty => true
case _ => false
}
case _ => false
}
if (!explicitTypeArgsProvided) {
fail(n.pos, tpt.tpe.typeSymbol)
}
case _ =>
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,22 @@ final class ExplicitGenericsTest extends AnyFunSuite with AnalyzerTest {
|val x = TestUtils.genericMacro[Int](123)
|""".stripMargin)
}

test("inferred in constructor should be rejected") {
assertErrors(1,
scala"""
|import com.avsystem.commons.analyzer.TestUtils
|
|val x = new TestUtils.GenericClass()
|""".stripMargin)
}

test("explicit in constructor should not be rejected") {
assertNoErrors(
scala"""
|import com.avsystem.commons.analyzer.TestUtils
|
|val x = new TestUtils.GenericClass[Int]()
|""".stripMargin)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,9 @@ object TestUtils {
def genericMethod[T](arg: T): T = arg
@explicitGenerics
def genericMacro[T](arg: T): T = macro genericMacroImpl[T]

@explicitGenerics
class GenericClass[T]

case class GenericCaseClass[T](arg: T)
}