Skip to content

Commit ab1da64

Browse files
authored
Merge pull request #5958 from dotty-staging/fix-if-block
Fix #444: be more conservative on when Block and If types should be recomputed
2 parents 16d37a2 + ff7a67c commit ab1da64

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

compiler/src/dotty/tools/dotc/ast/tpd.scala

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -572,15 +572,25 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo {
572572
override def Block(tree: Tree)(stats: List[Tree], expr: Tree)(implicit ctx: Context): Block = {
573573
val tree1 = untpdCpy.Block(tree)(stats, expr)
574574
tree match {
575-
case tree: Block if expr.tpe eq tree.expr.tpe => tree1.withTypeUnchecked(tree.tpe)
575+
case tree: Block if (expr.tpe eq tree.expr.tpe) && (expr.tpe eq tree.tpe) =>
576+
// the second guard is needed in case avoid somehow widened the type.
577+
// if it did it could potentially need to rewiden it
578+
// eg {val s = ...; s}
579+
// changing type of s should change type of block, though type of expr is unchanged - TermRef(s)
580+
tree1.withTypeUnchecked(tree.tpe)
576581
case _ => ta.assignType(tree1, stats, expr)
577582
}
578583
}
579584

580585
override def If(tree: Tree)(cond: Tree, thenp: Tree, elsep: Tree)(implicit ctx: Context): If = {
581586
val tree1 = untpdCpy.If(tree)(cond, thenp, elsep)
582587
tree match {
583-
case tree: If if (thenp.tpe eq tree.thenp.tpe) && (elsep.tpe eq tree.elsep.tpe) => tree1.withTypeUnchecked(tree.tpe)
588+
case tree: If if (thenp.tpe eq tree.thenp.tpe) && (elsep.tpe eq tree.elsep.tpe) &&
589+
((tree.tpe eq thenp.tpe) || (tree.tpe eq elsep.tpe)) =>
590+
// last guard is needed in case previous if had computed a widened ORType that needs to be recomputed
591+
// eg {val a = ...; val b = ...; if(...) a else b}
592+
// changing type of a or b should change type of if, though types of both trees remain unchanged
593+
tree1.withTypeUnchecked(tree.tpe)
584594
case _ => ta.assignType(tree1, thenp, elsep)
585595
}
586596
}

0 commit comments

Comments
 (0)