-
-
Notifications
You must be signed in to change notification settings - Fork 757
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Cast nullable to non nullable type (#5653)
* New rule: report cast of nullable variable to non-null type * Add test case for CastNullableToNonNullableType rule * Refactor KtExpression utility to TypeUtils.kt Move isNullable and descriptor common utility that was common across NullableToStringCall.kt and CastNullableToNonNullableType.kt rules * Add test for unnecessary safe check chain * Make the parameters of isNullable non nullable Handle null compilerResources at the call site * Add apis to detekt-psi-utils.api * Make KtExpression.descriptor private * Add alternate compliant code
- Loading branch information
Showing
7 changed files
with
285 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
72 changes: 72 additions & 0 deletions
72
...e/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/CastNullableToNonNullableType.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
package io.gitlab.arturbosch.detekt.rules.bugs | ||
|
||
import io.gitlab.arturbosch.detekt.api.CodeSmell | ||
import io.gitlab.arturbosch.detekt.api.Config | ||
import io.gitlab.arturbosch.detekt.api.Debt | ||
import io.gitlab.arturbosch.detekt.api.Entity | ||
import io.gitlab.arturbosch.detekt.api.Issue | ||
import io.gitlab.arturbosch.detekt.api.Rule | ||
import io.gitlab.arturbosch.detekt.api.Severity | ||
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution | ||
import io.gitlab.arturbosch.detekt.rules.isNullable | ||
import org.jetbrains.kotlin.lexer.KtTokens | ||
import org.jetbrains.kotlin.psi.KtBinaryExpressionWithTypeRHS | ||
import org.jetbrains.kotlin.psi.KtNullableType | ||
import org.jetbrains.kotlin.utils.addToStdlib.ifFalse | ||
import org.jetbrains.kotlin.utils.addToStdlib.ifTrue | ||
|
||
/** | ||
* Reports cast of nullable variable to non-null type. Cast like this can hide `null` | ||
* problems in your code. The compliant code would be that which will correctly check | ||
* for two things (nullability and type) and not just one (cast). | ||
* | ||
* <noncompliant> | ||
* fun foo(bar: Any?) { | ||
* val x = bar as String | ||
* } | ||
* </noncompliant> | ||
* | ||
* <compliant> | ||
* fun foo(bar: Any?) { | ||
* val x = checkNotNull(bar) as String | ||
* } | ||
* | ||
* // Alternative | ||
* fun foo(bar: Any?) { | ||
* val x = (bar ?: error("null assertion message")) as String | ||
* } | ||
* </compliant> | ||
*/ | ||
@RequiresTypeResolution | ||
class CastNullableToNonNullableType(config: Config = Config.empty) : Rule(config) { | ||
override val issue: Issue = Issue( | ||
javaClass.simpleName, | ||
Severity.Defect, | ||
"Nullable type to non-null type cast is found. Consider using two assertions, " + | ||
"`null` assertions and type cast", | ||
Debt.FIVE_MINS | ||
) | ||
|
||
@Suppress("ReturnCount") | ||
override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) { | ||
super.visitBinaryWithTypeRHSExpression(expression) | ||
|
||
val operationReference = expression.operationReference | ||
if (operationReference.getReferencedNameElementType() != KtTokens.AS_KEYWORD) return | ||
if (expression.left.text == KtTokens.NULL_KEYWORD.value) return | ||
val typeElement = expression.right?.typeElement ?: return | ||
(typeElement is KtNullableType).ifTrue { return } | ||
val compilerResourcesNonNull = compilerResources ?: return | ||
expression.left.isNullable( | ||
bindingContext, | ||
compilerResourcesNonNull.languageVersionSettings, | ||
compilerResourcesNonNull.dataFlowValueFactory, | ||
shouldConsiderPlatformTypeAsNullable = true, | ||
).ifFalse { return } | ||
|
||
val message = | ||
"Use separate `null` assertion and type cast like ('(${expression.left.text} ?: " + | ||
"error(\"null assertion message\")) as ${typeElement.text}') instead of '${expression.text}'." | ||
report(CodeSmell(issue, Entity.from(operationReference), message)) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
148 changes: 148 additions & 0 deletions
148
...c/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/CastNullableToNonNullableTypeSpec.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
package io.gitlab.arturbosch.detekt.rules.bugs | ||
|
||
import io.gitlab.arturbosch.detekt.rules.KotlinCoreEnvironmentTest | ||
import io.gitlab.arturbosch.detekt.test.assertThat | ||
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext | ||
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment | ||
import org.junit.jupiter.api.Test | ||
|
||
@KotlinCoreEnvironmentTest | ||
class CastNullableToNonNullableTypeSpec(private val env: KotlinCoreEnvironment) { | ||
private val subject = CastNullableToNonNullableType() | ||
|
||
@Test | ||
fun `reports casting Nullable type to NonNullable type`() { | ||
val code = """ | ||
fun foo(bar: Any?) { | ||
val x = bar as String | ||
} | ||
""".trimIndent() | ||
val findings = subject.compileAndLintWithContext(env, code) | ||
assertThat(findings).hasSize(1) | ||
assertThat(findings).hasStartSourceLocation(2, 17) | ||
assertThat(findings[0]).hasMessage( | ||
"Use separate `null` assertion and type cast like " + | ||
"('(bar ?: error(\"null assertion message\")) as String') instead of 'bar as String'." | ||
) | ||
} | ||
|
||
@Test | ||
fun `reports casting Nullable value returned from a function call to NonNullable type`() { | ||
val code = """ | ||
fun foo(bar: Any?) { | ||
bar() as Int | ||
} | ||
fun bar(): Int? { | ||
return null | ||
} | ||
""".trimIndent() | ||
val findings = subject.compileAndLintWithContext(env, code) | ||
assertThat(findings).hasSize(1) | ||
assertThat(findings).hasStartSourceLocation(2, 11) | ||
assertThat(findings[0]).hasMessage( | ||
"Use separate `null` assertion and type cast like " + | ||
"('(bar() ?: error(\"null assertion message\")) as Int') instead of 'bar() as Int'." | ||
) | ||
} | ||
|
||
@Test | ||
fun `reports casting of platform type to NonNullable type`() { | ||
val code = """ | ||
class Foo { | ||
fun test() { | ||
// getSimpleName() is not annotated with nullability information in the JDK, so compiler treats | ||
// it as a platform type with unknown nullability. | ||
val y = javaClass.simpleName as String | ||
} | ||
} | ||
""".trimIndent() | ||
val findings = subject.compileAndLintWithContext(env, code) | ||
assertThat(findings).hasSize(1) | ||
assertThat(findings).hasStartSourceLocation(5, 38) | ||
assertThat(findings[0]).hasMessage( | ||
"Use separate `null` assertion and type cast like " + | ||
"('(javaClass.simpleName ?: error(\"null assertion message\")) as String') instead of " + | ||
"'javaClass.simpleName as String'." | ||
) | ||
} | ||
|
||
@Test | ||
fun `does not report unnecessary safe check chain to NonNullable type`() { | ||
val code = """ | ||
class Foo { | ||
fun test() { | ||
val z = 1?.and(2) as Int | ||
} | ||
} | ||
""".trimIndent() | ||
val findings = subject.compileAndLintWithContext(env, code) | ||
assertThat(findings).isEmpty() | ||
} | ||
|
||
@Test | ||
fun `does not report casting of Nullable type to NonNullable expression with assertion to NonNullable type`() { | ||
val code = """ | ||
fun foo(bar: Any?) { | ||
val x = (bar ?: error("null assertion message")) as String | ||
} | ||
""".trimIndent() | ||
val findings = subject.compileAndLintWithContext(env, code) | ||
assertThat(findings).isEmpty() | ||
} | ||
|
||
@Test | ||
fun `does not report casting of Nullable type to NonNullable expression with !! assertion to NonNullable type`() { | ||
val code = """ | ||
fun foo(bar: Any?) { | ||
val x = bar!! as String | ||
} | ||
""".trimIndent() | ||
val findings = subject.compileAndLintWithContext(env, code) | ||
assertThat(findings).isEmpty() | ||
} | ||
|
||
@Test | ||
fun `does not report casting of Nullable type to NonNullable smart casted variable to NonNullable type`() { | ||
val code = """ | ||
fun foo(bar: Any?) { | ||
val x = bar?.let { bar as String } | ||
} | ||
""".trimIndent() | ||
val findings = subject.compileAndLintWithContext(env, code) | ||
assertThat(findings).isEmpty() | ||
} | ||
|
||
@Test | ||
fun `does not report casting of NonNullable type to NonNullable type`() { | ||
val code = """ | ||
fun foo(bar: Any?) { | ||
val x = bar as String? | ||
} | ||
""".trimIndent() | ||
val findings = subject.compileAndLintWithContext(env, code) | ||
assertThat(findings).isEmpty() | ||
} | ||
|
||
@Test | ||
fun `does not report safe casting of Nullable type to NonNullable type`() { | ||
val code = """ | ||
fun foo(bar: Any?) { | ||
val x = bar as? String | ||
} | ||
""".trimIndent() | ||
val findings = subject.compileAndLintWithContext(env, code) | ||
assertThat(findings).isEmpty() | ||
} | ||
|
||
@Test | ||
fun `does not report as compile error will happen when null to NonNullable type`() { | ||
val code = """ | ||
fun foo(bar: Any?) { | ||
val x = null as String | ||
} | ||
""".trimIndent() | ||
val findings = subject.compileAndLintWithContext(env, code) | ||
assertThat(findings).isEmpty() | ||
} | ||
} |