Skip to content

Commit afce192

Browse files
committed
Constant fold shortcut boolean evaluations
This is useful for keeping code small.
1 parent 9a7ea3c commit afce192

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

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

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ class FirstTransform extends MiniPhaseTransform with InfoTransformer with Annota
203203
constToLiteral(tree)
204204

205205
override def transformApply(tree: Apply)(implicit ctx: Context, info: TransformerInfo) =
206-
constToLiteral(tree)
206+
constToLiteral(foldCondition(tree))
207207

208208
override def transformTyped(tree: Typed)(implicit ctx: Context, info: TransformerInfo) =
209209
constToLiteral(tree)
@@ -217,6 +217,20 @@ class FirstTransform extends MiniPhaseTransform with InfoTransformer with Annota
217217
case _ => tree
218218
}
219219

220+
private def foldCondition(tree: Apply)(implicit ctx: Context) = tree.fun match {
221+
case Select(x @ Literal(Constant(c: Boolean)), op) =>
222+
tree.args match {
223+
case y :: Nil if y.tpe.widen.isRef(defn.BooleanClass) =>
224+
op match {
225+
case nme.ZAND => if (c) y else x
226+
case nme.ZOR => if (c) x else y
227+
case _ => tree
228+
}
229+
case _ => tree
230+
}
231+
case _ => tree
232+
}
233+
220234
// invariants: all modules have companion objects
221235
// all types are TypeTrees
222236
// all this types are explicit

0 commit comments

Comments
 (0)