diff --git a/compiler/src/dotty/tools/dotc/transform/CheckUnused.scala b/compiler/src/dotty/tools/dotc/transform/CheckUnused.scala index 8088504cb2f3..faee3598e4e0 100644 --- a/compiler/src/dotty/tools/dotc/transform/CheckUnused.scala +++ b/compiler/src/dotty/tools/dotc/transform/CheckUnused.scala @@ -370,15 +370,15 @@ class CheckUnused private (phaseMode: PhaseMode, suffix: String) extends MiniPha var cachePoint: Context = NoContext // last context with Resolved cache var importer: ImportSelector | Null = null // non-null for import context var precedence = NoPrecedence // of current resolution + var enclosed = false // true if sym is owner of an enclosing context var done = false var cached = false val ctxs = ctx.outersIterator while !done && ctxs.hasNext do val cur = ctxs.next() - if cur.owner eq sym then - addCached(cachePoint, Definition) - return // found enclosing definition - else if isLocal then + if cur.owner.userSymbol == sym && !sym.is(Package) then + enclosed = true // found enclosing definition, don't register the reference + if isLocal then if cur.owner eq sym.owner then done = true // for local def, just checking that it is not enclosing else @@ -419,7 +419,7 @@ class CheckUnused private (phaseMode: PhaseMode, suffix: String) extends MiniPha candidate = cur importer = sel else if checkMember(cur.owner) then - if sym.srcPos.sourcePos.source == ctx.source then + if sym.is(Package) || sym.srcPos.sourcePos.source == ctx.source then precedence = Definition candidate = cur importer = null // ignore import in same scope; we can't check nesting level @@ -429,7 +429,8 @@ class CheckUnused private (phaseMode: PhaseMode, suffix: String) extends MiniPha candidate = cur end while // record usage and possibly an import - refInfos.refs.addOne(sym) + if !enclosed then + refInfos.refs.addOne(sym) if candidate != NoContext && candidate.isImportContext && importer != null then refInfos.sels.put(importer, ()) // possibly record that we have performed this look-up diff --git a/tests/warn/i23047.scala b/tests/warn/i23047.scala new file mode 100644 index 000000000000..1922797c3185 --- /dev/null +++ b/tests/warn/i23047.scala @@ -0,0 +1,25 @@ +//> using options -Wunused:imports + +package some.example: + package demo: + + import some.example // no warn because enclosing package example is not available as a simple name in some + + object Main { + + def generic[T](x: Any): T = null.asInstanceOf[T] + + def main(args: Array[String]): Unit = { + generic[example.Util](0) + + import some.example.demo.Main // warn + println(Main) + + import some.example.demo // warn because enclosing package demo is available as a simple name + println(demo.Main) + } + } + +package some.example: + + class Util