Skip to content

Commit f9af73d

Browse files
committed
Add error message for companion and class/module name clash
1 parent 4dc4bd6 commit f9af73d

File tree

4 files changed

+32
-3
lines changed

4 files changed

+32
-3
lines changed

compiler/src/dotty/tools/dotc/reporting/diagnostic/ErrorMessageID.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ public enum ErrorMessageID {
103103
ExtendFinalClassID,
104104
EnumCaseDefinitionInNonEnumOwnerID,
105105
ExpectedTypeBoundOrEqualsID,
106+
ClassAndCompanionNameClashID,
106107
;
107108

108109
public int errorNumber() {

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1804,4 +1804,14 @@ object messages {
18041804
|refers to a subtype of type ${"A"}.
18051805
|"""
18061806
}
1807+
1808+
case class ClassAndCompanionNameClash(cls: Symbol)(implicit ctx: Context)
1809+
extends Message(ClassAndCompanionNameClashID) {
1810+
val kind = "Syntax"
1811+
val msg = hl"Naming clash, ${cls.owner} and it's companion object defines $cls"
1812+
val explanation =
1813+
s"""It is not allowed to define a class or module with the same
1814+
|name inside a class and companion object.
1815+
"""
1816+
}
18071817
}

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

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,7 @@ object RefChecks {
115115
if (!(cls.owner is ModuleClass)) {
116116
val other = cls.owner.linkedClass.info.decl(cls.name)
117117
if (other.symbol.isClass)
118-
ctx.error(s"name clash: ${cls.owner} defines $cls" + "\n" +
119-
s"and its companion ${cls.owner.companionModule} also defines $other",
120-
cls.pos)
118+
ctx.error(ClassAndCompanionNameClash(cls))
121119
}
122120

123121
// Override checking ------------------------------------------------------------

compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTests.scala

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1038,4 +1038,24 @@ class ErrorMessagesTests extends ErrorMessagesTest {
10381038
val ExpectedTypeBoundOrEquals(found) :: Nil = messages
10391039
assertEquals(Tokens.IDENTIFIER, found)
10401040
}
1041+
1042+
@Test def classAndCompanionNameClash =
1043+
checkMessagesAfter("refchecks") {
1044+
"""
1045+
|class T {
1046+
| class G {}
1047+
|}
1048+
|object T {
1049+
| class G {}
1050+
|}
1051+
""".stripMargin
1052+
}.expect { (ictx, messages) =>
1053+
implicit val ctx: Context = ictx
1054+
1055+
assertMessageCount(1, messages)
1056+
val ClassAndCompanionNameClash(symbol) :: Nil = messages
1057+
1058+
assertEquals("class T", symbol.owner.show)
1059+
assertEquals("class G", symbol.show)
1060+
}
10411061
}

0 commit comments

Comments
 (0)