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

UnconditionalJumpStatementInLoop: don't report a conditional break in a single body expression #6443

Merged
merged 2 commits into from
Aug 31, 2023
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 @@ -9,6 +9,7 @@ import io.gitlab.arturbosch.detekt.api.Rule
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtBreakExpression
import org.jetbrains.kotlin.psi.KtContinueExpression
import org.jetbrains.kotlin.psi.KtLoopExpression
Expand Down Expand Up @@ -55,8 +56,13 @@ class UnconditionalJumpStatementInLoop(config: Config = Config.empty) : Rule(con
super.visitLoopExpression(loopExpression)
}

private fun KtLoopExpression.hasJumpStatements(): Boolean =
body?.isJumpStatement() == true || body?.children?.any { it.isJumpStatement() } == true
private fun KtLoopExpression.hasJumpStatements(): Boolean {
val body = this.body ?: return false
return when (body) {
is KtBlockExpression -> body.children.any { it.isJumpStatement() }
else -> body.isJumpStatement()
}
}

private fun PsiElement.isJumpStatement(): Boolean =
this is KtReturnExpression && !isFollowedByElvisJump() && !isAfterConditionalJumpStatement() ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -352,4 +352,17 @@ class UnconditionalJumpStatementInLoopSpec {

assertThat(findings).isEmpty()
}

// https://github.com/detekt/detekt/issues/6442
@Test
fun `does not report a conditional break in a single body expression`() {
val code = """
import java.util.concurrent.BlockingQueue

fun <T> BlockingQueue<T>.pollEach(action: (T) -> Unit) {
while (true) this.poll()?.let { action(it) } ?: break
}
""".trimIndent()
assertThat(subject.compileAndLint(code)).isEmpty()
}
}