Skip to content

Commit

Permalink
AsyncAndSyncRule
Browse files Browse the repository at this point in the history
### What's done:
   Fixed after review
  • Loading branch information
kentr0w committed Jan 15, 2021
1 parent 2d21217 commit 2f6df59
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@ import org.cqfn.diktat.ruleset.constants.Warnings.RUN_BLOCKING_INSIDE_ASYNC

import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.ast.ElementType.CALL_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.FILE
import com.pinterest.ktlint.core.ast.ElementType.FUN
import com.pinterest.ktlint.core.ast.ElementType.LAMBDA_ARGUMENT
import com.pinterest.ktlint.core.ast.ElementType.REFERENCE_EXPRESSION
import com.pinterest.ktlint.core.ast.parent
import org.cqfn.diktat.ruleset.utils.hasChildOfType
import org.cqfn.diktat.ruleset.utils.prettyPrint
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.psiUtil.hasSuspendModifier
import org.jetbrains.kotlin.psi.psiUtil.isLambdaOutsideParentheses

/**
* This rule finds if using runBlocking in asynchronous code
Expand Down Expand Up @@ -42,5 +49,5 @@ class AsyncAndSyncRule(private val configRules: List<RulesConfig>) : Rule("sync-

private fun ASTNode.isSuspend() = this.elementType == FUN && (this.psi as KtFunction).modifierList?.hasSuspendModifier() ?: false

private fun ASTNode.isRunBlocking() = this.elementType == REFERENCE_EXPRESSION && this.text == "runBlocking"
private fun ASTNode.isRunBlocking() = this.elementType == REFERENCE_EXPRESSION && this.text == "runBlocking" && this.treeParent.hasChildOfType(LAMBDA_ARGUMENT)
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,30 @@ class AsyncAndSyncRuleTest : LintTestBase(::AsyncAndSyncRule) {
LintError(18, 4, ruleId, "${RUN_BLOCKING_INSIDE_ASYNC.warnText()} runBlocking", false)
)
}

@Test
@Tag(WarningNames.RUN_BLOCKING_INSIDE_ASYNC)
fun `test dot qualified expression case`() {
lintMethod(
"""
|fun foo() {
| GlobalScope.async {
| node.runBlocking()
| runBlocking {
| n++
| }
| }
|}
|
|fun goo() {
| runBlocking {
| GlobalScope.async {
| n++
| }
| }
|}
""".trimMargin(),
LintError(4, 8, ruleId, "${RUN_BLOCKING_INSIDE_ASYNC.warnText()} runBlocking", false)
)
}
}
2 changes: 1 addition & 1 deletion info/guide/guide-chapter-5.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ private fun foo() {
#### <a name="r5.2.4"></a> 5.2.4 Synchronizing code inside asynchronous code
Try to avoid using runBlocking in asynchronous code

**Example**:
**Invalid example**:
```kotlin
GlobalScope.async {
runBlocking {
Expand Down

0 comments on commit 2f6df59

Please sign in to comment.