diff --git a/compiler/src/dotty/tools/dotc/reporting/diagnostic/ErrorMessageID.java b/compiler/src/dotty/tools/dotc/reporting/diagnostic/ErrorMessageID.java index b7ad3692185e..bc3bec0e3bcb 100644 --- a/compiler/src/dotty/tools/dotc/reporting/diagnostic/ErrorMessageID.java +++ b/compiler/src/dotty/tools/dotc/reporting/diagnostic/ErrorMessageID.java @@ -113,6 +113,7 @@ public enum ErrorMessageID { IllegalStartOfStatementID, TraitIsExpectedID, TraitRedefinedFinalMethodFromAnyRefID, + PackageNameAlreadyDefinedID, ; public int errorNumber() { diff --git a/compiler/src/dotty/tools/dotc/reporting/diagnostic/messages.scala b/compiler/src/dotty/tools/dotc/reporting/diagnostic/messages.scala index be31e609fd2c..2a79fe54c90b 100644 --- a/compiler/src/dotty/tools/dotc/reporting/diagnostic/messages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/diagnostic/messages.scala @@ -1922,4 +1922,11 @@ object messages { val msg = hl"Traits cannot redefine final $method from ${"class AnyRef"}." val explanation = "" } + + case class PackageNameAlreadyDefined(pkg: Symbol)(implicit ctx: Context) extends Message(PackageNameAlreadyDefinedID) { + val msg = hl"${pkg} is already defined, cannot be a ${"package"}" + val kind = "Naming" + val explanation = + hl"An ${"object"} cannot have the same name as an existing ${"package"}. Rename either one of them." + } } diff --git a/compiler/src/dotty/tools/dotc/typer/Typer.scala b/compiler/src/dotty/tools/dotc/typer/Typer.scala index d7c8daee2cd6..983dfcc48e19 100644 --- a/compiler/src/dotty/tools/dotc/typer/Typer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Typer.scala @@ -1522,7 +1522,7 @@ class Typer extends Namer with TypeAssigner with Applications with Implicits wit val packageContext = if (pkg is Package) ctx.fresh.setOwner(pkg.moduleClass).setTree(tree) else { - ctx.error(em"$pkg is already defined, cannot be a package", tree.pos) + ctx.error(PackageNameAlreadyDefined(pkg), tree.pos) ctx } val stats1 = typedStats(tree.stats, pkg.moduleClass)(packageContext) diff --git a/compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTests.scala b/compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTests.scala index 4282e5aa367d..a6bc8a46fd38 100644 --- a/compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTests.scala +++ b/compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTests.scala @@ -1189,4 +1189,18 @@ class ErrorMessagesTests extends ErrorMessagesTest { assertEquals("method wait", method.show) } + + @Test def packageNameAlreadyDefined = + checkMessagesAfter("frontend") { + """ + |package bar { } + |object bar { } + | + """.stripMargin + }.expect { (ictx, messages) => + implicit val ctx: Context = ictx + + val PackageNameAlreadyDefined(pkg) = messages.head + assertEquals(pkg.show, "object bar") + } }