Skip to content

Commit

Permalink
[KT] Always bring over the test expression in an instanceof check
Browse files Browse the repository at this point in the history
Currently we statically evaluate the instanceof result if the test expression
is a primitive, which is totally fine. However, we neglect the test expressions,
which may have side-effects.

We simply need to bring over that expression as well by utilizing a
multiexpression.

PiperOrigin-RevId: 718161764
  • Loading branch information
kevinoconnor7 authored and copybara-github committed Jan 22, 2025
1 parent 0cf1806 commit 17b4896
Showing 1 changed file with 9 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1275,19 +1275,15 @@ class CompilationUnitBuilder(
if (typeDescriptor.isTypeVariable) typeDescriptor.toRawTypeDescriptor() else typeDescriptor

if (expressionTypeDescriptor.isPrimitive) {
// Kotlin only allows non-nullable primitive instanceOf type if the type is assignable, hence
// only if the instanceOf is true. `1 is Int` is valid but `1 is Double` is rejected by the
// compiler. However after inlining inline function with reified type parameters, the program
// can contain this kind of instanceOf expression.
// Ex:
// inline fun <reified T> instanceOf(o: Any) = o is T
// The following call site:
// val b = instanceOf<String>(1)
// is inlined as:
// val b = 1 is String
return BooleanLiteral.get(
expressionTypeDescriptor.toBoxedType().isAssignableTo(testTypeDescriptor)
)
// If the expression is a primitive we can statically compute the instanceof result rather
// than box it.
val result =
BooleanLiteral.get(
expressionTypeDescriptor.toBoxedType().isAssignableTo(testTypeDescriptor)
)
return MultiExpression.newBuilder()
.addExpressions(convertExpression(expression), result)
.build()
}
return InstanceOfExpression.newBuilder()
.setExpression(convertExpression(expression))
Expand Down

0 comments on commit 17b4896

Please sign in to comment.