Skip to content

Add an error message for "invalid unapply return type" error. #3501

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ public enum ErrorMessageID {
TraitRedefinedFinalMethodFromAnyRefID,
PackageNameAlreadyDefinedID,
UnapplyInvalidNumberOfArgumentsID,
UnapplyInvalidReturnTypeID,
StaticFieldsOnlyAllowedInObjectsID,
CyclicInheritanceID,
BadSymbolicReferenceID,
Expand Down
56 changes: 56 additions & 0 deletions compiler/src/dotty/tools/dotc/reporting/diagnostic/messages.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import dotty.tools.dotc.core.Flags._
import dotty.tools.dotc.core.SymDenotations.SymDenotation
import dotty.tools.dotc.typer.ErrorReporting.Errors
import scala.util.control.NonFatal
import StdNames.nme

object messages {

Expand Down Expand Up @@ -1919,6 +1920,61 @@ object messages {
|""".stripMargin
}

case class UnapplyInvalidReturnType(unapplyResult: Type, unapplyName: Symbol#ThisName)(implicit ctx: Context)
extends Message(UnapplyInvalidReturnTypeID) {
val kind = "Type Mismatch"
val addendum =
if (ctx.scala2Mode && unapplyName == nme.unapplySeq)
"\nYou might want to try to rewrite the extractor to use `unapply` instead."
else ""
val msg = hl"""| ${Red(i"$unapplyResult")} is not a valid result type of an $unapplyName method of an ${Magenta("extractor")}.$addendum"""
val explanation = if (unapplyName.show == "unapply")
hl"""
|To be used as an extractor, an unapply method has to return a type that either:
| - has members ${Magenta("isEmpty: Boolean")} and ${Magenta("get: S")} (usually an ${Green("Option[S]")})
| - is a ${Green("Boolean")}
| - is a ${Green("Product")} (like a ${Magenta("Tuple2[T1, T2]")})
|
|class A(val i: Int)
|
|object B {
| def unapply(a: A): ${Green("Option[Int]")} = Some(a.i)
|}
|
|object C {
| def unapply(a: A): ${Green("Boolean")} = a.i == 2
|}
|
|object D {
| def unapply(a: A): ${Green("(Int, Int)")} = (a.i, a.i)
|}
|
|object Test {
| def test(a: A) = a match {
| ${Magenta("case B(1)")} => 1
| ${Magenta("case a @ C()")} => 2
| ${Magenta("case D(3, 3)")} => 3
| }
|}
""".stripMargin
else
hl"""
|To be used as an extractor, an unapplySeq method has to return a type which has members
|${Magenta("isEmpty: Boolean")} and ${Magenta("get: S")} where ${Magenta("S <: Seq[V]")} (usually an ${Green("Option[Seq[V]]")}):
|
|object CharList {
| def unapplySeq(s: String): ${Green("Option[Seq[Char]")} = Some(s.toList)
|
| "example" match {
| ${Magenta("case CharList(c1, c2, c3, c4, _, _, _)")} =>
| println(s"$$c1,$$c2,$$c3,$$c4")
| case _ =>
| println("Expected *exactly* 7 characters!")
| }
|}
""".stripMargin
}

case class StaticFieldsOnlyAllowedInObjects(member: Symbol)(implicit ctx: Context) extends Message(StaticFieldsOnlyAllowedInObjectsID) {
val msg: String = hl"${"@static"} $member in ${member.owner} must be defined inside an ${"object"}."
val kind: String = "Syntax"
Expand Down
8 changes: 2 additions & 6 deletions compiler/src/dotty/tools/dotc/typer/Applications.scala
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import TypeApplications._
import reporting.diagnostic.Message
import reporting.trace
import Constants.{Constant, IntTag, LongTag}
import dotty.tools.dotc.reporting.diagnostic.messages.{NotAnExtractor, UnapplyInvalidNumberOfArguments}
import dotty.tools.dotc.reporting.diagnostic.messages.{UnapplyInvalidReturnType, NotAnExtractor, UnapplyInvalidNumberOfArguments}
import Denotations.SingleDenotation
import annotation.constructorOnly

Expand Down Expand Up @@ -99,11 +99,7 @@ object Applications {
def getTp = extractorMemberType(unapplyResult, nme.get, pos)

def fail = {
val addendum =
if (ctx.scala2Mode && unapplyName == nme.unapplySeq)
"\nYou might want to try to rewrite the extractor to use `unapply` instead."
else ""
ctx.error(em"$unapplyResult is not a valid result type of an $unapplyName method of an extractor$addendum", pos)
ctx.error(UnapplyInvalidReturnType(unapplyResult, unapplyName), pos)
Nil
}

Expand Down
40 changes: 40 additions & 0 deletions compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1380,6 +1380,46 @@ class ErrorMessagesTests extends ErrorMessagesTest {
assertEquals("(class Int, class String)", argTypes.map(_.typeSymbol).mkString("(", ", ", ")"))
}

@Test def unapplyInvalidReturnType =
checkMessagesAfter("frontend") {
"""
|class A(val i: Int)
|
|object A {
| def unapply(a: A): Int = a.i
| def test(a: A) = a match {
| case A() => 1
| }
|}
""".stripMargin
}.expect { (ictx, messages) =>
implicit val ctx: Context = ictx
assertMessageCount(1, messages)
val UnapplyInvalidReturnType(unapplyResult, unapplyName) :: Nil = messages
assertEquals("Int", unapplyResult.show)
assertEquals("unapply", unapplyName.show)
}

@Test def unapplySeqInvalidReturnType =
checkMessagesAfter("frontend") {
"""
|class A(val i: Int)
|
|object A {
| def unapplySeq(a: A): Int = a.i
| def test(a: A) = a match {
| case A() => 1
| }
|}
""".stripMargin
}.expect { (ictx, messages) =>
implicit val ctx: Context = ictx
assertMessageCount(1, messages)
val UnapplyInvalidReturnType(unapplyResult, unapplyName) :: Nil = messages
assertEquals("Int", unapplyResult.show)
assertEquals("unapplySeq", unapplyName.show)
}

@Test def staticOnlyAllowedInsideObjects =
checkMessagesAfter(CheckStatic.name) {
"""
Expand Down