Skip to content

Commit 2328fdf

Browse files
committed
Better error message for ifs that miss an else branch
1 parent 3d26c53 commit 2328fdf

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ package typer
55
import ast._
66
import core._
77
import Types._, ProtoTypes._, Contexts._, Decorators._, Denotations._, Symbols._
8-
import Implicits._, Flags._
8+
import Implicits._, Flags._, Constants.Constant
99
import util.Spans._
1010
import util.SourcePosition
1111
import java.util.regex.Matcher.quoteReplacement
@@ -98,7 +98,13 @@ object ErrorReporting {
9898
val normTp = normalize(tree.tpe, pt)
9999
val treeTp = if (normTp <:< pt) tree.tpe else normTp
100100
// use normalized type if that also shows an error, original type otherwise
101-
errorTree(tree, TypeMismatch(treeTp, pt, implicitFailure.whyNoConversion))
101+
def missingElse = tree match
102+
case If(_, _, elsep @ Literal(Constant(()))) if elsep.span.isSynthetic =>
103+
"\nMaybe you are missing an else part for the conditional?"
104+
case _ => ""
105+
val addendum = List(implicitFailure.whyNoConversion, missingElse)
106+
.find(!_.isEmpty).getOrElse("")
107+
errorTree(tree, TypeMismatch(treeTp, pt, addendum))
102108
}
103109

104110
/** A subtype log explaining why `found` does not conform to `expected` */

tests/neg/if-error.check

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
-- [E007] Type Mismatch Error: tests/neg/if-error.scala:2:2 ------------------------------------------------------------
2+
2 | if ??? then System.in.read() // error
3+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4+
| Found: Unit
5+
| Required: Int
6+
| Maybe you are missing an else part for the conditional?

tests/neg/if-error.scala

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
val x: Int =
2+
if ??? then System.in.read() // error

0 commit comments

Comments
 (0)