Skip to content
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

Add support to nullable slots in ContentSlotReused #343

Merged
merged 1 commit into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ val KnownUnstableCollectionTypesRegex = sequenceOf(
fun KtCallableDeclaration.contentSlots(
treatAsLambdaTypes: Set<String>,
treatAsComposableLambdaTypes: Set<String>,
): List<KtParameter> = valueParameters.filter { parameter ->
parameter.typeReference?.isComposableLambda(treatAsLambdaTypes, treatAsComposableLambdaTypes) == true
}
): Sequence<KtParameter> = valueParameters.asSequence()
.filter { parameter ->
parameter.typeReference?.isComposableLambda(treatAsLambdaTypes, treatAsComposableLambdaTypes) == true
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Copyright 2024 Nacho Lopez
// SPDX-License-Identifier: Apache-2.0
package io.nlopez.compose.core.util

import org.jetbrains.kotlin.psi.KtNullableType
import org.jetbrains.kotlin.psi.KtParameter

val KtParameter.isTypeNullable: Boolean
get() = typeReference?.typeElement is KtNullableType
Original file line number Diff line number Diff line change
Expand Up @@ -10,93 +10,47 @@ import io.nlopez.compose.core.util.composableLambdaTypes
import io.nlopez.compose.core.util.contentSlots
import io.nlopez.compose.core.util.findChildrenByClass
import io.nlopez.compose.core.util.findShadowingRedeclarations
import io.nlopez.compose.core.util.isTypeNullable
import io.nlopez.compose.core.util.lambdaTypes
import io.nlopez.compose.core.util.uniquePairs
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtSafeQualifiedExpression

class ContentSlotReused : ComposeKtVisitor {
override fun visitComposable(function: KtFunction, emitter: Emitter, config: ComposeKtConfig) {
val lambdaTypes = function.containingKtFile.lambdaTypes(config)
val composableLambdaTypes = function.containingKtFile.composableLambdaTypes(config)

val slots = function.contentSlots(lambdaTypes, composableLambdaTypes)
.filter { it.name?.isNotEmpty() == true }
val slotsWithMultipleUsages = function.contentSlots(lambdaTypes, composableLambdaTypes)
.filter { slot -> function.findNotShadowedUsagesOf(slot).count() >= 2 }

val slotsWithMultipleUsages = slots.filter { it.name != null }
.map { slot -> slot to function.findUsages(slot.name!!) }
.filter { (_, usages) -> usages.count() >= 2 }

// Now that we found some candidates, we need to make sure the slots being reused are in different branches
// in the ast tree. We'll need to search for parent ifs, whens, etc.
val slotsInDifferentBranches = slotsWithMultipleUsages
.filter { (_, usages) -> isSlotUsedInSeparateBranches(usages, function) }
.map { (slot, _) -> slot }

for (slot in slotsInDifferentBranches) {
emitter.report(slot, ContentSlotReusedInDifferentBranches)
for (slot in slotsWithMultipleUsages) {
emitter.report(slot, ContentSlotsShouldNotBeReused)
}
}

private fun KtFunction.findUsages(name: String): Sequence<KtCallExpression> =
findChildrenByClass<KtCallExpression>().filter { it.calleeExpression?.text == name }
// Remove shadowed usages
.filter { it.findShadowingRedeclarations(name, this).count() == 0 }

private fun isSlotUsedInSeparateBranches(slots: Sequence<KtCallExpression>, stopAt: KtFunction): Boolean =
slots.uniquePairs()
.any { (slot1, slot2) ->
findCommonAncestor(slot1, slot2, stopAt).isBranchingElement()
}

private fun findCommonAncestor(slot1: KtCallExpression, slot2: KtCallExpression, stopAt: KtFunction): KtElement {
val height1 = slot1.parents.takeWhile { it != stopAt }.count()
val height2 = slot2.parents.takeWhile { it != stopAt }.count()

var current1: KtElement = slot1
var current2: KtElement = slot2

// If the heights are different, we'll need to go up in the one that's deeper until they
when {
height1 > height2 -> {
repeat(height1 - height2) { current1 = current1.parent as KtElement }
}

height1 < height2 -> {
repeat(height2 - height1) { current2 = current2.parent as KtElement }
}
}

// Traverse up until they are at the same level
while (current1 != current2) {
current1 = current1.parent as KtElement
current2 = current2.parent as KtElement
private fun KtFunction.findNotShadowedUsagesOf(slot: KtParameter): Sequence<KtCallExpression> {
val slotName = slot.name?.takeIf { it.isNotEmpty() } ?: return emptySequence()
val slots = when {
// content?.invoke()
slot.isTypeNullable -> findChildrenByClass<KtSafeQualifiedExpression>()
.filter { it.receiverExpression.text == slotName }
.mapNotNull { it.selectorExpression as? KtCallExpression }
.filter { it.calleeExpression?.text == "invoke" }

// content()
else -> findChildrenByClass<KtCallExpression>().filter { it.calleeExpression?.text == slotName }
}

return current1
}

private fun KtElement.isBranchingElement(): Boolean = when (val current = this) {
// Always true, if not, the ancestor would have been found in then or in else expressions
is KtIfExpression -> true
// Always true, if not, the ancestor would have been found in a when entry
is KtWhenExpression -> true
// Only branching if it's an elvis operator
is KtBinaryExpression -> current.operationToken == KtTokens.ELVIS
else -> false
// Return and remove shadowed usages
return slots.filter { it.findShadowingRedeclarations(parameterName = slotName, stopAt = this).count() == 0 }
}

companion object {
val ContentSlotReusedInDifferentBranches = """
Content slots should not be reused in different code branches of a composable function (e.g. if/when/elvis).
val ContentSlotsShouldNotBeReused = """
Content slots should not be reused in different code branches/scopes of a composable function, to preserve the slot internal state.

You can wrap the usages in a remember { movableContentOf { ... }} block to make sure their internal state is preserved correctly.
You can wrap the slot in a remember { movableContentOf { ... }} block to make sure their internal state is preserved correctly.

See https://mrmans0n.github.io/compose-rules/rules/#content-slots-should-not-be-reused-in-branching-code for more information.
""".trimIndent()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class ContentSlotReusedCheck(config: Config) :
override val issue: Issue = Issue(
id = "ContentSlotReused",
severity = Severity.Defect,
description = ContentSlotReused.ContentSlotReusedInDifferentBranches,
description = ContentSlotReused.ContentSlotsShouldNotBeReused,
debt = Debt.TEN_MINS,
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class ContentSlotReusedCheckTest {
private val rule = ContentSlotReusedCheck(testConfig)

@Test
fun `errors when there is a slot being reused in different branches`() {
fun `errors when there is a slot being reused`() {
@Language("kotlin")
val code =
"""
Expand All @@ -42,6 +42,11 @@ class ContentSlotReusedCheckTest {
fun D(text: String, content: Potato) {
potato?.let { content() } ?: content()
}
@Composable
fun E(text: String, content: @Composable () -> Unit) {
val content1 = remember { movableContentOf { content() } }
val content2 = remember { movableContentOf { content() } }
}
""".trimIndent()

val errors = rule.lint(code)
Expand All @@ -51,9 +56,45 @@ class ContentSlotReusedCheckTest {
SourceLocation(6, 21),
SourceLocation(13, 21),
SourceLocation(17, 21),
SourceLocation(21, 21),
)
for (error in errors) {
assertThat(error).hasMessage(ContentSlotReused.ContentSlotsShouldNotBeReused)
}
}

@Test
fun `errors when there is a nullable slot being reused`() {
@Language("kotlin")
val code =
"""
@Composable
fun A(text: String, content: (@Composable () -> Unit)? = null) {
if (x) content?.invoke() else content?.invoke()
}
@Composable
fun B(text: String, content: (@Composable () -> Unit)? = null) {
when {
x -> content?.invoke()
else -> content?.invoke()
}
}
@Composable
fun C(text: String, content: (@Composable () -> Unit)? = null) {
val content1 = remember { movableContentOf { content?.invoke() } }
val content2 = remember { movableContentOf { content?.invoke() } }
}
""".trimIndent()

val errors = rule.lint(code)
assertThat(errors)
.hasStartSourceLocations(
SourceLocation(2, 21),
SourceLocation(6, 21),
SourceLocation(13, 21),
)
for (error in errors) {
assertThat(error).hasMessage(ContentSlotReused.ContentSlotReusedInDifferentBranches)
assertThat(error).hasMessage(ContentSlotReused.ContentSlotsShouldNotBeReused)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class ContentSlotReusedCheckTest {
private val ruleAssertThat = assertThatRule { ContentSlotReusedCheck() }

@Test
fun `errors when there is a slot being reused in different branches`() {
fun `errors when there is a slot being reused`() {
@Language("kotlin")
val code =
"""
Expand All @@ -36,6 +36,11 @@ class ContentSlotReusedCheckTest {
fun D(text: String, content: Potato) {
potato?.let { content() } ?: content()
}
@Composable
fun E(text: String, content: @Composable () -> Unit) {
val content1 = remember { movableContentOf { content() } }
val content2 = remember { movableContentOf { content() } }
}
""".trimIndent()

ruleAssertThat(code)
Expand All @@ -44,22 +49,70 @@ class ContentSlotReusedCheckTest {
LintViolation(
line = 2,
col = 21,
detail = ContentSlotReused.ContentSlotReusedInDifferentBranches,
detail = ContentSlotReused.ContentSlotsShouldNotBeReused,
),
LintViolation(
line = 6,
col = 21,
detail = ContentSlotReused.ContentSlotReusedInDifferentBranches,
detail = ContentSlotReused.ContentSlotsShouldNotBeReused,
),
LintViolation(
line = 13,
col = 21,
detail = ContentSlotReused.ContentSlotReusedInDifferentBranches,
detail = ContentSlotReused.ContentSlotsShouldNotBeReused,
),
LintViolation(
line = 17,
col = 21,
detail = ContentSlotReused.ContentSlotReusedInDifferentBranches,
detail = ContentSlotReused.ContentSlotsShouldNotBeReused,
),
LintViolation(
line = 21,
col = 21,
detail = ContentSlotReused.ContentSlotsShouldNotBeReused,
),
)
}

@Test
fun `errors when there is a nullable slot being reused`() {
@Language("kotlin")
val code =
"""
@Composable
fun A(text: String, content: (@Composable () -> Unit)? = null) {
if (x) content?.invoke() else content?.invoke()
}
@Composable
fun B(text: String, content: (@Composable () -> Unit)? = null) {
when {
x -> content?.invoke()
else -> content?.invoke()
}
}
@Composable
fun C(text: String, content: (@Composable () -> Unit)? = null) {
val content1 = remember { movableContentOf { content?.invoke() } }
val content2 = remember { movableContentOf { content?.invoke() } }
}
""".trimIndent()

ruleAssertThat(code)
.hasLintViolationsWithoutAutoCorrect(
LintViolation(
line = 2,
col = 21,
detail = ContentSlotReused.ContentSlotsShouldNotBeReused,
),
LintViolation(
line = 6,
col = 21,
detail = ContentSlotReused.ContentSlotsShouldNotBeReused,
),
LintViolation(
line = 13,
col = 21,
detail = ContentSlotReused.ContentSlotsShouldNotBeReused,
),
)
}
Expand Down