Skip to content

Commit c521dae

Browse files
committed
Warn if extension receiver has matching member
1 parent b67e269 commit c521dae

File tree

11 files changed

+60
-4
lines changed

11 files changed

+60
-4
lines changed

compiler/src/dotty/tools/dotc/core/SymDenotations.scala

+1
Original file line numberDiff line numberDiff line change
@@ -1348,6 +1348,7 @@ object SymDenotations {
13481348
* inClass <-- find denot.symbol class C { <-- symbol is here
13491349
*
13501350
* site: Subtype of both inClass and C
1351+
* } <-- balance the brace
13511352
*/
13521353
final def matchingDecl(inClass: Symbol, site: Type)(using Context): Symbol = {
13531354
var denot = inClass.info.nonPrivateDecl(name)

compiler/src/dotty/tools/dotc/reporting/ErrorMessageID.scala

+1
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@ enum ErrorMessageID(val isActive: Boolean = true) extends java.lang.Enum[ErrorMe
195195
case MatchTypeScrutineeCannotBeHigherKindedID // errorNumber: 179
196196
case AmbiguousExtensionMethodID // errorNumber 180
197197
case UnqualifiedCallToAnyRefMethodID // errorNumber: 181
198+
case ExtensionNullifiedByMemberID // errorNumber: 182
198199

199200
def errorNumber = ordinal - 1
200201

compiler/src/dotty/tools/dotc/reporting/messages.scala

+9
Original file line numberDiff line numberDiff line change
@@ -2298,6 +2298,15 @@ class UnqualifiedCallToAnyRefMethod(stat: untpd.Tree, method: Symbol)(using Cont
22982298
|you intended."""
22992299
}
23002300

2301+
class ExtensionNullifiedByMember(method: Symbol, target: Symbol)(using Context)
2302+
extends Message(ExtensionNullifiedByMemberID):
2303+
def kind = MessageKind.PotentialIssue
2304+
def msg(using Context) = i"Suspicious extension ${hl(method.name.toString)} is already a member of ${hl(target.name.toString)}"
2305+
def explain(using Context) =
2306+
i"""Extension method ${hl(method.name.toString)} will never be selected
2307+
|because ${hl(target.name.toString)} already has a member with the same name.
2308+
|It can be called as a regular method, but should probably be defined that way."""
2309+
23012310
class TraitCompanionWithMutableStatic()(using Context)
23022311
extends SyntaxMsg(TraitCompanionWithMutableStaticID) {
23032312
def msg(using Context) = i"Companion of traits cannot define mutable @static fields"

compiler/src/dotty/tools/dotc/typer/Typer.scala

+8-1
Original file line numberDiff line numberDiff line change
@@ -2486,7 +2486,14 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
24862486
linkConstructorParams(sym, tparamSyms, rhsCtx)
24872487

24882488
if sym.isInlineMethod then rhsCtx.addMode(Mode.InlineableBody)
2489-
if sym.is(ExtensionMethod) then rhsCtx.addMode(Mode.InExtensionMethod)
2489+
if sym.is(ExtensionMethod) then
2490+
if ctx.phase.isTyper then
2491+
val ValDef(_, paramTpt, _) = termParamssIn(paramss1).head.head
2492+
if !paramTpt.symbol.denot.isAliasType && !paramTpt.symbol.denot.isOpaqueAlias then
2493+
val other = paramTpt.tpe.nonPrivateMember(name)
2494+
if other.exists && sym.denot.info.resultType.matches(other.info) then
2495+
report.warning(ExtensionNullifiedByMember(sym, paramTpt.symbol), ddef.srcPos)
2496+
rhsCtx.addMode(Mode.InExtensionMethod)
24902497
val rhs1 = PrepareInlineable.dropInlineIfError(sym,
24912498
if sym.isScala2Macro then typedScala2MacroBody(ddef.rhs)(using rhsCtx)
24922499
else typedExpr(ddef.rhs, tpt1.tpe.widenExpr)(using rhsCtx))

compiler/test/dotty/tools/dotc/printing/PrintingTest.scala

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import java.io.File
2525
class PrintingTest {
2626

2727
def options(phase: String, flags: List[String]) =
28-
List(s"-Xprint:$phase", "-color:never", "-classpath", TestConfiguration.basicClasspath) ::: flags
28+
List(s"-Xprint:$phase", "-color:never", "-nowarn", "-classpath", TestConfiguration.basicClasspath) ::: flags
2929

3030
private def compileFile(path: JPath, phase: String): Boolean = {
3131
val baseFilePath = path.toString.stripSuffix(".scala")

compiler/test/dotty/tools/scripting/ScriptTestEnv.scala

+1
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ object ScriptTestEnv {
218218
def toUrl: String = Paths.get(absPath).toUri.toURL.toString
219219

220220
// Treat norm paths with a leading '/' as absolute (Windows java.io.File#isAbsolute treats them as relative)
221+
@annotation.nowarn // hidden by Path#isAbsolute?
221222
def isAbsolute = p.norm.startsWith("/") || (isWin && p.norm.secondChar == ":")
222223
}
223224

scaladoc-testcases/src/tests/implicitConversions.scala

+2-2
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ class B {
4545
class C {
4646
def extensionInCompanion: String = ???
4747
}
48-
48+
@annotation.nowarn // extensionInCompanion
4949
object C {
5050
implicit def companionConversion(c: C): B = ???
5151

@@ -70,4 +70,4 @@ package nested {
7070
}
7171

7272
class Z
73-
}
73+
}

scaladoc-testcases/src/tests/inheritedMembers1.scala

+1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package tests
22
package inheritedMembers1
33

44

5+
/*<-*/@annotation.nowarn/*->*/
56
class A
67
{
78
def A: String

tests/neg-custom-args/fatal-warnings/i9241.scala

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ final class Baz private (val x: Int) extends AnyVal {
2020
}
2121

2222
extension (x: Int)
23+
@annotation.nowarn
2324
def unary_- : Int = ???
2425
def unary_+[T] : Int = ???
2526
def unary_!() : Int = ??? // error

tests/neg/i16743.check

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
-- [E182] Potential Issue Error: tests/neg/i16743.scala:7:21 -----------------------------------------------------------
2+
7 |extension (x: T) def t = 27 // error
3+
| ^^^^^^^^^^
4+
| Suspicious extension t is already a member of T
5+
|---------------------------------------------------------------------------------------------------------------------
6+
| Explanation (enabled by `-explain`)
7+
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
8+
| Extension method t will never be selected
9+
| because T already has a member with the same name.
10+
| It can be called as a regular method, but should probably be defined that way.
11+
---------------------------------------------------------------------------------------------------------------------

tests/neg/i16743.scala

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
2+
// scalac: -Werror -explain
3+
4+
trait T:
5+
def t = 42
6+
7+
extension (x: T) def t = 27 // error
8+
9+
@main def test() =
10+
val x = new T {}
11+
println:
12+
x.t
13+
14+
trait Foo:
15+
type X
16+
extension (x: X) def t: Int
17+
18+
trait Bar extends Foo:
19+
type X = T
20+
extension (x: X) def t = x.t
21+
22+
opaque type IArray[+T] = Array[_ <: T]
23+
object IArray:
24+
extension (arr: IArray[Byte]) def length: Int = arr.asInstanceOf[Array[Byte]].length

0 commit comments

Comments
 (0)