Skip to content

Commit d926c5b

Browse files
oderskymichelou
authored andcommitted
Treat all incomplete ifs as statements
Previously only a one-armed if was treated as a statement where all parts were typed with Unit as expected type. We now extend that treatment also to multi-branch ifs that lack a final part. Fixes scala#14914
1 parent b7110d1 commit d926c5b

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

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

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1128,15 +1128,22 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
11281128
if tree.isInline then checkInInlineContext("inline if", tree.srcPos)
11291129
val cond1 = typed(tree.cond, defn.BooleanType)
11301130

1131+
def isIncomplete(tree: untpd.If): Boolean = tree.elsep match
1132+
case EmptyTree => true
1133+
case elsep: untpd.If => isIncomplete(elsep)
1134+
case _ => false
1135+
1136+
val branchPt = if isIncomplete(tree) then defn.UnitType else pt.dropIfProto
1137+
11311138
val result =
11321139
if tree.elsep.isEmpty then
1133-
val thenp1 = typed(tree.thenp, defn.UnitType)(using cond1.nullableContextIf(true))
1140+
val thenp1 = typed(tree.thenp, branchPt)(using cond1.nullableContextIf(true))
11341141
val elsep1 = tpd.unitLiteral.withSpan(tree.span.endPos)
11351142
cpy.If(tree)(cond1, thenp1, elsep1).withType(defn.UnitType)
11361143
else
11371144
val thenp1 :: elsep1 :: Nil = harmonic(harmonize, pt) {
1138-
val thenp0 = typed(tree.thenp, pt.dropIfProto)(using cond1.nullableContextIf(true))
1139-
val elsep0 = typed(tree.elsep, pt.dropIfProto)(using cond1.nullableContextIf(false))
1145+
val thenp0 = typed(tree.thenp, branchPt)(using cond1.nullableContextIf(true))
1146+
val elsep0 = typed(tree.elsep, branchPt)(using cond1.nullableContextIf(false))
11401147
thenp0 :: elsep0 :: Nil
11411148
}
11421149
assignType(cpy.If(tree)(cond1, thenp1, elsep1), thenp1, elsep1)

tests/pos/i14914.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
def Test(b: Boolean) =
3+
val a =
4+
if b then
5+
1
6+
else if !b then
7+
2
8+
val _: Unit = a

0 commit comments

Comments
 (0)