Skip to content

Backport "WUnused: Fix for symbols with synthetic names and unused transparent inlines" #17250

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

Closed
wants to merge 13 commits into from
Closed
71 changes: 50 additions & 21 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 @@ -355,30 +360,27 @@ object CheckUnused:

/** Register an import */
def registerImport(imp: tpd.Import)(using Context): Unit =
if !tpd.languageImport(imp.expr).nonEmpty && !imp.isGeneratedByEnum then
if !tpd.languageImport(imp.expr).nonEmpty && !imp.isGeneratedByEnum && !isTransparentAndInline(imp) then
impInScope.top += imp
unusedImport ++= imp.selectors.filter { s =>
!shouldSelectorBeReported(imp, s) && !isImportExclusion(s)
}

/** 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 @@ -423,6 +425,7 @@ object CheckUnused:
else
exists
}

// if there's an outer scope
if usedInScope.nonEmpty then
// we keep the symbols not referencing an import in this scope
Expand All @@ -441,6 +444,7 @@ object CheckUnused:
*/
def getUnused(using Context): UnusedResult =
popScope()

val sortedImp =
if ctx.settings.WunusedHas.imports || ctx.settings.WunusedHas.strictNoImplicitWarn then
unusedImport.map(d => d.srcPos -> WarnTypes.Imports).toList
Expand All @@ -450,34 +454,41 @@ 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})
.filterNot(d => containsSyntheticSuffix(d.symbol))
.map(d => d.namePos -> WarnTypes.LocalDefs).toList
else
Nil
val sortedExplicitParams =
if ctx.settings.WunusedHas.explicits then
explicitParamInScope
.filterNot(d => d.symbol.usedDefContains)
.filterNot(d => containsSyntheticSuffix(d.symbol))
.map(d => d.namePos -> WarnTypes.ExplicitParams).toList
else
Nil
val sortedImplicitParams =
if ctx.settings.WunusedHas.implicits then
implicitParamInScope
.filterNot(d => d.symbol.usedDefContains)
.filterNot(d => containsSyntheticSuffix(d.symbol))
.map(d => d.namePos -> WarnTypes.ImplicitParams).toList
else
Nil
val sortedPrivateDefs =
if ctx.settings.WunusedHas.privates then
privateDefInScope
.filterNot(d => d.symbol.usedDefContains)
.filterNot(d => containsSyntheticSuffix(d.symbol))
.map(d => d.namePos -> WarnTypes.PrivateMembers).toList
else
Nil
val sortedPatVars =
if ctx.settings.WunusedHas.patvars then
patVarsInScope
.filterNot(d => d.symbol.usedDefContains)
.filterNot(d => containsSyntheticSuffix(d.symbol))
.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 All @@ -489,6 +500,23 @@ object CheckUnused:
end getUnused
//============================ HELPERS ====================================


/**
* Checks if import selects a def that is transparent and inline
*/
private def isTransparentAndInline(imp: tpd.Import)(using Context): Boolean =
imp.selectors.exists { sel =>
val qual = imp.expr
val importedMembers = qual.tpe.member(sel.name).alternatives.map(_.symbol)
importedMembers.exists(s => s.is(Transparent) && s.is(Inline))
}

/**
* Heuristic to detect synthetic suffixes in names of symbols
*/
private def containsSyntheticSuffix(symbol: Symbol)(using Context): Boolean =
symbol.name.mangledString.contains("$")

/**
* Is the the constructor of synthetic package object
* Should be ignored as it is always imported/used in package
Expand Down Expand Up @@ -578,10 +606,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 +642,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
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,9 @@ trait Anonymous {
trait Context[A]
trait Implicits {
def f[A](implicit ctx: Context[A]) = answer // error
def g[A: Context] = answer // error
def g[A: Context] = answer // OK
}
class Bound[A: Context] // error
class Bound[A: Context] // OK
object Answers {
def answer: Int = 42
}
Expand Down
2 changes: 1 addition & 1 deletion tests/neg-custom-args/fatal-warnings/i15503b.scala
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ package foo.scala2.tests:

object Types {
def l1() = {
object HiObject { def f = this } // error
object HiObject { def f = this } // OK
class Hi { // error
def f1: Hi = new Hi
def f2(x: Hi) = x
Expand Down
5 changes: 3 additions & 2 deletions tests/neg-custom-args/fatal-warnings/i15503f.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ val default_int = 1

def f1(a: Int) = a // OK
def f2(a: Int) = 1 // OK
def f3(a: Int)(using Int) = a // error
def f4(a: Int)(using Int) = default_int // error
def f3(a: Int)(using Int) = a // OK
def f4(a: Int)(using Int) = default_int // OK
def f6(a: Int)(using Int) = summon[Int] // OK
def f7(a: Int)(using Int) = summon[Int] + a // OK
def f8(a: Int)(using foo: Int) = a // error

4 changes: 2 additions & 2 deletions tests/neg-custom-args/fatal-warnings/i15503g.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ val default_int = 1

def f1(a: Int) = a // OK
def f2(a: Int) = default_int // error
def f3(a: Int)(using Int) = a // error
def f4(a: Int)(using Int) = default_int // error // error
def f3(a: Int)(using Int) = a // OK
def f4(a: Int)(using Int) = default_int // error
def f6(a: Int)(using Int) = summon[Int] // error
def f7(a: Int)(using Int) = summon[Int] + a // OK

Expand Down
Loading