Skip to content

Commit 983ce8d

Browse files
committed
Pruning branch of constant type condition.
As done in inliner.
1 parent ea93259 commit 983ce8d

File tree

3 files changed

+25
-5
lines changed

3 files changed

+25
-5
lines changed

compiler/src/dotty/tools/dotc/transform/FirstTransform.scala

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import dotty.tools.dotc.transform.TreeTransforms._
99
import ast.Trees._
1010
import Flags._
1111
import Types._
12-
import Constants.Constant
12+
import Constants._
1313
import Contexts.Context
1414
import Symbols._
1515
import SymDenotations._
@@ -34,6 +34,8 @@ import StdNames._
3434
* - drops branches of ifs using the rules
3535
* if (true) A else B --> A
3636
* if (false) A else B --> B
37+
* if (C: true) A else B --> C; A
38+
* if (C: false) A else B --> C; B
3739
*/
3840
class FirstTransform extends MiniPhaseTransform with InfoTransformer with AnnotationTransformer { thisTransformer =>
3941
import ast.tpd._
@@ -190,11 +192,16 @@ class FirstTransform extends MiniPhaseTransform with InfoTransformer with Annota
190192
override def transformBlock(tree: Block)(implicit ctx: Context, info: TransformerInfo) =
191193
constToLiteral(tree)
192194

193-
override def transformIf(tree: If)(implicit ctx: Context, info: TransformerInfo) =
194-
tree.cond match {
195-
case Literal(Constant(c: Boolean)) => if (c) tree.thenp else tree.elsep
196-
case _ => tree
195+
override def transformIf(tree: If)(implicit ctx: Context, info: TransformerInfo) = {
196+
tree.cond.tpe.widenTermRefExpr match {
197+
case ConstantType(Constant(condVal: Boolean)) =>
198+
val selected = if (condVal) tree.thenp else tree.elsep
199+
if (isPureExpr(tree.cond)) selected
200+
else Block(tree.cond :: Nil, selected)
201+
case _ =>
202+
tree
197203
}
204+
}
198205

199206
// invariants: all modules have companion objects
200207
// all types are TypeTrees

tests/run/if-with-constant-cond.check

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
cond1
2+
then1
3+
cond2
4+
else2

tests/run/if-with-constant-cond.scala

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
2+
object Test {
3+
4+
def main(args: Array[String]): Unit = {
5+
if ({ println("cond1"); true }: true) println("then1") else println("else1")
6+
if ({ println("cond2"); false }: false) println("then2") else println("else2")
7+
}
8+
9+
}

0 commit comments

Comments
 (0)