diff --git a/compiler/src/dotty/tools/dotc/reporting/diagnostic/ErrorMessageID.java b/compiler/src/dotty/tools/dotc/reporting/diagnostic/ErrorMessageID.java index f91f19b23014..2d653d581e3c 100644 --- a/compiler/src/dotty/tools/dotc/reporting/diagnostic/ErrorMessageID.java +++ b/compiler/src/dotty/tools/dotc/reporting/diagnostic/ErrorMessageID.java @@ -98,6 +98,7 @@ public enum ErrorMessageID { ExpectedStartOfTopLevelDefinitionID, MissingReturnTypeWithReturnStatementID, NoReturnFromInlineID, + ReturnOutsideMethodDefinitionID, ; 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 b471a6b2453c..e45c581cea1a 100644 --- a/compiler/src/dotty/tools/dotc/reporting/diagnostic/messages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/diagnostic/messages.scala @@ -1747,4 +1747,15 @@ object messages { |returned from a method. |""" } + + case class ReturnOutsideMethodDefinition(owner: Symbol)(implicit ctx: Context) + extends Message(ReturnOutsideMethodDefinitionID) { + val kind = "Syntax" + val msg = hl"${"return"} outside method definition" + val explanation = + hl"""You used ${"return"} in ${owner}. + |${"return"} is a keyword and may only be used within method declarations. + |""" + } + } diff --git a/compiler/src/dotty/tools/dotc/typer/Typer.scala b/compiler/src/dotty/tools/dotc/typer/Typer.scala index 10eab6cc31cf..ab63b6f51580 100644 --- a/compiler/src/dotty/tools/dotc/typer/Typer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Typer.scala @@ -980,7 +980,7 @@ class Typer extends Namer with TypeAssigner with Applications with Implicits wit def enclMethInfo(cx: Context): (Tree, Type) = { val owner = cx.owner if (owner.isType) { - ctx.error("return outside method definition", tree.pos) + ctx.error(ReturnOutsideMethodDefinition(owner), tree.pos) (EmptyTree, WildcardType) } else if (owner != cx.outer.owner && owner.isRealMethod) { diff --git a/compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTests.scala b/compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTests.scala index 90497f54f8b4..a5a2fff1ba5f 100644 --- a/compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTests.scala +++ b/compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTests.scala @@ -985,4 +985,17 @@ class ErrorMessagesTests extends ErrorMessagesTest { val NoReturnFromInline(method) :: Nil = messages assertEquals("method usesReturn", method.show) } + + @Test def returnOutsideMethodDefinition = + checkMessagesAfter("frontend") { + """object A { + | return 5 + |} + """.stripMargin + }.expect { (ictx, messages) => + implicit val ctx: Context = ictx + assertMessageCount(1, messages) + val ReturnOutsideMethodDefinition(owner) :: Nil = messages + assertEquals("object A", owner.show) + } }