-
-
Notifications
You must be signed in to change notification settings - Fork 821
Add NullableToStringCall rule #2903
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ac8d4f3
Add NullableToStringCall rule
t-kameyama 16d7dd4
Fix document
t-kameyama b066aa8
Fix test
t-kameyama 439efbc
Add dataFlowValueFactory to BaseRule
t-kameyama 041d52c
Merge branch 'master' into issue_2901
t-kameyama 01134a3
Add `@since 1.11.0`
t-kameyama beb3028
Add import for Assertions#assertThat
t-kameyama File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
91 changes: 91 additions & 0 deletions
91
...errorprone/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/NullableToStringCall.kt
This file contains hidden or 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,91 @@ | ||
| 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 org.jetbrains.kotlin.descriptors.CallableDescriptor | ||
| import org.jetbrains.kotlin.name.FqName | ||
| import org.jetbrains.kotlin.psi.KtExpression | ||
| import org.jetbrains.kotlin.psi.KtSimpleNameExpression | ||
| import org.jetbrains.kotlin.psi.KtStringTemplateEntry | ||
| import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver | ||
| import org.jetbrains.kotlin.resolve.BindingContext | ||
| import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall | ||
| import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull | ||
| import org.jetbrains.kotlin.types.isNullable | ||
|
|
||
| /** | ||
| * Turn on this rule to flag 'toString' calls with a nullable receiver that may return the string "null". | ||
| * | ||
| * <noncompliant> | ||
| * fun foo(a: Any?): String { | ||
| * return a.toString() | ||
| * } | ||
| * | ||
| * fun bar(a: Any?): String { | ||
| * return "$a" | ||
| * } | ||
| * </noncompliant> | ||
| * | ||
| * <compliant> | ||
| * fun foo(a: Any?): String { | ||
| * return a?.toString() ?: "-" | ||
| * } | ||
| * | ||
| * fun bar(a: Any?): String { | ||
| * return "${a ?: "-"}" | ||
| * } | ||
| * </compliant> | ||
| * | ||
| * @since 1.11.0 | ||
| */ | ||
| class NullableToStringCall(config: Config = Config.empty) : Rule(config) { | ||
| override val issue = Issue( | ||
| javaClass.simpleName, | ||
| Severity.Defect, | ||
| "This call may return the string \"null\"", | ||
| Debt.FIVE_MINS | ||
| ) | ||
|
|
||
| @Suppress("ReturnCount") | ||
| override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { | ||
| super.visitSimpleNameExpression(expression) | ||
|
|
||
| if (bindingContext == BindingContext.EMPTY) return | ||
|
|
||
| val qualified = expression.getQualifiedExpressionForReceiver() | ||
| when { | ||
| qualified != null -> { | ||
| if (qualified.descriptor()?.fqNameOrNull() != FqName("kotlin.toString")) return | ||
| } | ||
| expression.parent is KtStringTemplateEntry -> { | ||
| val compilerResources = compilerResources ?: return | ||
| val descriptor = expression.descriptor() ?: return | ||
| val originalType = descriptor.returnType ?.takeIf { it.isNullable() } ?: return | ||
| val dataFlowInfo = | ||
| bindingContext[BindingContext.EXPRESSION_TYPE_INFO, expression]?.dataFlowInfo ?: return | ||
| val dataFlowValue = compilerResources.dataFlowValueFactory.createDataFlowValue( | ||
| expression, originalType, bindingContext, descriptor | ||
| ) | ||
| val dataFlowTypes = | ||
| dataFlowInfo.getStableTypes(dataFlowValue, compilerResources.languageVersionSettings) | ||
| if (dataFlowTypes.any { !it.isNullable() }) return | ||
| } | ||
| else -> return | ||
| } | ||
|
|
||
| val targetExpression = qualified ?: expression.parent | ||
| val codeSmell = CodeSmell( | ||
| issue, | ||
| Entity.from(targetExpression), | ||
| "This call '${targetExpression.text}' may return the string \"null\"." | ||
| ) | ||
| report(codeSmell) | ||
| } | ||
|
|
||
| private fun KtExpression.descriptor(): CallableDescriptor? = getResolvedCall(bindingContext)?.resultingDescriptor | ||
| } | ||
This file contains hidden or 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
93 changes: 93 additions & 0 deletions
93
...rprone/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/NullableToStringCallSpec.kt
This file contains hidden or 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,93 @@ | ||
| package io.gitlab.arturbosch.detekt.rules.bugs | ||
|
|
||
| import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment | ||
| import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext | ||
| import org.assertj.core.api.Assertions.assertThat | ||
| import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment | ||
| import org.spekframework.spek2.Spek | ||
| import org.spekframework.spek2.style.specification.describe | ||
|
|
||
| object NullableToStringCallSpec: Spek({ | ||
| setupKotlinEnvironment() | ||
|
|
||
| val env: KotlinCoreEnvironment by memoized() | ||
| val subject by memoized { NullableToStringCall() } | ||
|
|
||
| describe("NullableToString rule") { | ||
| it("reports when a nullable toString is explicitly called") { | ||
| val code = """ | ||
| fun test(a: Any?) { | ||
| println(a.toString()) | ||
| } | ||
| """ | ||
| val actual = subject.compileAndLintWithContext(env, code) | ||
| assertThat(actual).hasSize(1) | ||
| assertThat(actual.first().message).isEqualTo("This call 'a.toString()' may return the string \"null\".") | ||
| } | ||
|
|
||
| it("reports when a nullable toString is implicitly called in a string template") { | ||
| val code = """ | ||
| fun test(a: Any?) { | ||
| println("${'$'}a") | ||
| } | ||
| """ | ||
| val actual = subject.compileAndLintWithContext(env, code) | ||
| assertThat(actual).hasSize(1) | ||
| assertThat(actual.first().message).isEqualTo("This call '\$a' may return the string \"null\".") | ||
| } | ||
|
|
||
| it("reports when a nullable toString is implicitly called in curly braces in a string template") { | ||
| val code = """ | ||
| fun test(a: Any?) { | ||
| println("${'$'}{a}") | ||
| } | ||
| """ | ||
| val actual = subject.compileAndLintWithContext(env, code) | ||
| assertThat(actual).hasSize(1) | ||
| assertThat(actual.first().message).isEqualTo("This call '\${a}' may return the string \"null\".") | ||
| } | ||
|
|
||
| it("reports when a nullable toString is implicitly called in a raw string template") { | ||
| val code = """ | ||
| fun test(a: Any?) { | ||
| println(${'"'}""${'$'}a""${'"'}) | ||
| } | ||
| """ | ||
| val actual = subject.compileAndLintWithContext(env, code) | ||
| assertThat(actual).hasSize(1) | ||
| assertThat(actual.first().message).isEqualTo("This call '\$a' may return the string \"null\".") | ||
| } | ||
|
|
||
| it("does not report when a nullable toString is not called") { | ||
| val code = """ | ||
| fun test(a: Any?) { | ||
| println(a?.toString()) | ||
| println("${'$'}{a ?: "-"}") | ||
| } | ||
| fun test2(a: Any) { | ||
| println(a.toString()) | ||
| println("${'$'}a") | ||
| println("${'$'}{a}") | ||
| println(${'"'}""${'$'}a""${'"'}) | ||
| } | ||
| fun test3(a: Any?) { | ||
| if (a != null) { | ||
| println(a.toString()) | ||
| println("${'$'}a") | ||
| println("${'$'}{a}") | ||
| println(${'"'}""${'$'}a""${'"'}) | ||
| } | ||
| } | ||
| fun test4(a: Any?) { | ||
| requireNotNull(a) | ||
| println(a.toString()) | ||
| println("${'$'}a") | ||
| println("${'$'}{a}") | ||
| println(${'"'}""${'$'}a""${'"'}) | ||
| } | ||
| """ | ||
| val actual = subject.compileAndLintWithContext(env, code) | ||
| assertThat(actual).isEmpty() | ||
| } | ||
| } | ||
| }) |
This file contains hidden or 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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.