Skip to content

Backport "WUnused: Fix unused warning in synthetic symbols" #17248

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 14, 2023
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
45 changes: 25 additions & 20 deletions compiler/src/dotty/tools/dotc/transform/CheckUnused.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ import dotty.tools.dotc.ast.untpd.ImportSelector
import dotty.tools.dotc.config.ScalaSettings
import dotty.tools.dotc.core.Contexts.*
import dotty.tools.dotc.core.Decorators.{em, i}
import dotty.tools.dotc.core.Flags._
import dotty.tools.dotc.core.Flags.*
import dotty.tools.dotc.core.Phases.Phase
import dotty.tools.dotc.core.StdNames
import dotty.tools.dotc.report
import dotty.tools.dotc.reporting.Message
import dotty.tools.dotc.typer.ImportInfo
import dotty.tools.dotc.util.Property
import dotty.tools.dotc.util.{Property, SrcPos}
import dotty.tools.dotc.core.Mode
import dotty.tools.dotc.core.Types.TypeTraverser
import dotty.tools.dotc.core.Types.Type
Expand All @@ -28,6 +28,7 @@ import dotty.tools.dotc.core.Types.ConstantType
import dotty.tools.dotc.core.NameKinds.WildcardParamName
import dotty.tools.dotc.core.Types.TermRef
import dotty.tools.dotc.core.Types.NameFilter
import dotty.tools.dotc.core.Symbols.Symbol



Expand Down Expand Up @@ -81,7 +82,7 @@ class CheckUnused extends MiniPhase:
ctx

override def prepareForIdent(tree: tpd.Ident)(using Context): Context =
if tree.symbol.exists then
if tree.symbol.exists then
_key.unusedDataApply(_.registerUsed(tree.symbol, Some(tree.name)))
else if tree.hasType then
_key.unusedDataApply(_.registerUsed(tree.tpe.classSymbol, Some(tree.name)))
Expand All @@ -103,7 +104,8 @@ class CheckUnused extends MiniPhase:
override def prepareForValDef(tree: tpd.ValDef)(using Context): Context =
_key.unusedDataApply{ud =>
// do not register the ValDef generated for `object`
if !tree.symbol.is(Module) then
traverseAnnotations(tree.symbol)
if !tree.symbol.is(Module) then
ud.registerDef(tree)
ud.addIgnoredUsage(tree.symbol)
}
Expand All @@ -112,18 +114,21 @@ class CheckUnused extends MiniPhase:
_key.unusedDataApply{ ud =>
import ud.registerTrivial
tree.registerTrivial
traverseAnnotations(tree.symbol)
ud.registerDef(tree)
ud.addIgnoredUsage(tree.symbol)
}

override def prepareForTypeDef(tree: tpd.TypeDef)(using Context): Context =
_key.unusedDataApply{ ud =>
if !tree.symbol.is(Param) then // Ignore type parameter (as Scala 2)
traverseAnnotations(tree.symbol)
ud.registerDef(tree)
ud.addIgnoredUsage(tree.symbol)
}

override def prepareForBind(tree: tpd.Bind)(using Context): Context =
traverseAnnotations(tree.symbol)
_key.unusedDataApply(_.registerPatVar(tree))

override def prepareForTypeTree(tree: tpd.TypeTree)(using Context): Context =
Expand Down Expand Up @@ -232,6 +237,10 @@ class CheckUnused extends MiniPhase:
case AnnotatedType(_, annot) => dt(_.registerUsed(annot.symbol, None))
case _ => traverseChildren(tp)

/** This traverse the annotations of the symbol */
private def traverseAnnotations(sym: Symbol)(using Context): Unit =
sym.denot.annotations.foreach(annot => traverser.traverse(annot.tree))

/** Do the actual reporting given the result of the anaylsis */
private def reportUnused(res: UnusedData.UnusedResult)(using Context): Unit =
import CheckUnused.WarnTypes
Expand Down Expand Up @@ -274,7 +283,6 @@ object CheckUnused:
private class UnusedData:
import dotty.tools.dotc.transform.CheckUnused.UnusedData.UnusedResult
import collection.mutable.{Set => MutSet, Map => MutMap, Stack => MutStack}
import dotty.tools.dotc.core.Symbols.Symbol
import UnusedData.ScopeType

/** The current scope during the tree traversal */
Expand All @@ -289,6 +297,7 @@ object CheckUnused:
* See the `isAccessibleAsIdent` extension method below in the file
*/
private val usedInScope = MutStack(MutSet[(Symbol,Boolean, Option[Name])]())
private val usedInPosition = MutSet[(SrcPos, Name)]()
/* unused import collected during traversal */
private val unusedImport = MutSet[ImportSelector]()

Expand Down Expand Up @@ -324,25 +333,21 @@ object CheckUnused:
execInNewScope
popScope()

/** Register all annotations of this symbol's denotation */
def registerUsedAnnotation(sym: Symbol)(using Context): Unit =
val annotSym = sym.denot.annotations.map(_.symbol)
annotSym.foreach(s => registerUsed(s, None))

/**
* Register a found (used) symbol along with its name
*
* The optional name will be used to target the right import
* as the same element can be imported with different renaming
*/
def registerUsed(sym: Symbol, name: Option[Name])(using Context): Unit =
def registerUsed(sym: Symbol, name: Option[Name])(using Context): Unit =
if !isConstructorOfSynth(sym) && !doNotRegister(sym) then
if sym.isConstructor && sym.exists then
registerUsed(sym.owner, None) // constructor are "implicitly" imported with the class
else
usedInScope.top += ((sym, sym.isAccessibleAsIdent, name))
usedInScope.top += ((sym.companionModule, sym.isAccessibleAsIdent, name))
usedInScope.top += ((sym.companionClass, sym.isAccessibleAsIdent, name))
name.map(n => usedInPosition += ((sym.sourcePos, n)))

/** Register a symbol that should be ignored */
def addIgnoredUsage(sym: Symbol)(using Context): Unit =
Expand All @@ -363,22 +368,19 @@ object CheckUnused:

/** Register (or not) some `val` or `def` according to the context, scope and flags */
def registerDef(memDef: tpd.MemberDef)(using Context): Unit =
// register the annotations for usage
registerUsedAnnotation(memDef.symbol)
if memDef.isValidMemberDef then
if memDef.isValidParam then
if memDef.symbol.isOneOf(GivenOrImplicit) then
implicitParamInScope += memDef
else
explicitParamInScope += memDef
else if currScopeType.top == ScopeType.Local then
else if currScopeType.top == ScopeType.Local then
localDefInScope += memDef
else if memDef.shouldReportPrivateDef then
privateDefInScope += memDef

/** Register pattern variable */
def registerPatVar(patvar: tpd.Bind)(using Context): Unit =
registerUsedAnnotation(patvar.symbol)
if !patvar.symbol.isUnusedAnnot then
patVarsInScope += patvar

Expand Down Expand Up @@ -450,6 +452,7 @@ object CheckUnused:
if ctx.settings.WunusedHas.locals then
localDefInScope
.filterNot(d => d.symbol.usedDefContains)
.filterNot(d => usedInPosition.exists { case (pos, name) => d.span.contains(pos.span) && name == d.symbol.name})
.map(d => d.namePos -> WarnTypes.LocalDefs).toList
else
Nil
Expand Down Expand Up @@ -478,6 +481,7 @@ object CheckUnused:
if ctx.settings.WunusedHas.patvars then
patVarsInScope
.filterNot(d => d.symbol.usedDefContains)
.filterNot(d => usedInPosition.exists { case (pos, name) => d.span.contains(pos.span) && name == d.symbol.name})
.map(d => d.namePos -> WarnTypes.PatVars).toList
else
Nil
Expand Down Expand Up @@ -578,10 +582,10 @@ object CheckUnused:
else
false

private def usedDefContains(using Context): Boolean =
private def usedDefContains(using Context): Boolean =
sym.everySymbol.exists(usedDef.apply)

private def everySymbol(using Context): List[Symbol] =
private def everySymbol(using Context): List[Symbol] =
List(sym, sym.companionClass, sym.companionModule, sym.moduleClass).filter(_.exists)

end extension
Expand Down Expand Up @@ -614,10 +618,11 @@ object CheckUnused:
private def isValidParam(using Context): Boolean =
val sym = memDef.symbol
(sym.is(Param) || sym.isAllOf(PrivateParamAccessor | Local, butNot = CaseAccessor)) &&
!isSyntheticMainParam(sym) &&
!sym.shouldNotReportParamOwner
!isSyntheticMainParam(sym) &&
!sym.shouldNotReportParamOwner &&
(!sym.exists || !sym.owner.isAllOf(Synthetic | PrivateLocal))

private def shouldReportPrivateDef(using Context): Boolean =
private def shouldReportPrivateDef(using Context): Boolean =
currScopeType.top == ScopeType.Template && !memDef.symbol.isConstructor && memDef.symbol.is(Private, butNot = SelfName | Synthetic | CaseAccessor)

extension (imp: tpd.Import)
Expand Down
46 changes: 40 additions & 6 deletions tests/neg-custom-args/fatal-warnings/i15503i.scala
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,13 @@ package foo.test.companionprivate:
package foo.test.i16678:
def foo(func: Int => String, value: Int): String = func(value) // OK

def run =
def run =
println(foo(number => number.toString, value = 5)) // OK
println(foo(number => "<number>", value = 5)) // error
println(foo(func = number => "<number>", value = 5)) // error
println(foo(func = number => number.toString, value = 5)) // OK
println(foo(func = _.toString, value = 5)) // OK

package foo.test.possibleclasses:
case class AllCaseClass(
k: Int, // OK
Expand All @@ -93,7 +93,7 @@ package foo.test.possibleclasses:
s: Int, // error /* But not these */
val t: Int, // OK
private val z: Int // error
)
)

case class AllCaseUsed(
k: Int, // OK
Expand All @@ -113,7 +113,7 @@ package foo.test.possibleclasses:
s: Int, // error
val t: Int, // OK
private val z: Int // error
)
)

class AllUsed(
k: Int, // OK
Expand All @@ -124,10 +124,44 @@ package foo.test.possibleclasses:
private val z: Int // OK
) {
def a = k + y + s + t + z
}
}

package foo.test.from.i16675:
case class PositiveNumber private (i: Int) // OK
object PositiveNumber:
def make(i: Int): Option[PositiveNumber] = //OK
def make(i: Int): Option[PositiveNumber] = //OK
Option.when(i >= 0)(PositiveNumber(i)) // OK

package foo.test.i16822:
enum ExampleEnum {
case Build(context: String) // OK
case List // OK
}

def demo = {
val x = ExampleEnum.List // OK
println(x) // OK
}

package foo.test.i16877:
import scala.collection.immutable.HashMap // OK
import scala.annotation.StaticAnnotation // OK

class ExampleAnnotation(val a: Object) extends StaticAnnotation // OK

@ExampleAnnotation(new HashMap()) // OK
class Test //OK

package foo.test.i16926:
def hello(): Unit =
for {
i <- (0 to 10).toList
(a, b) = "hello" -> "world" // OK
} yield println(s"$a $b")

package foo.test.i16925:
def hello =
for {
i <- 1 to 2 if true
_ = println(i) // OK
} yield ()