[FIR] Forbid no then branch in if expression

#KT-59883
This commit is contained in:
Evgeniy.Zhelenskiy
2024-02-08 23:31:10 +01:00
committed by Space Team
parent 3d6af53a3b
commit 2e66954d01
3 changed files with 19 additions and 3 deletions
@@ -22,6 +22,7 @@ import org.jetbrains.kotlin.fir.declarations.utils.modality
import org.jetbrains.kotlin.fir.expressions.ExhaustivenessStatus
import org.jetbrains.kotlin.fir.expressions.FirWhenExpression
import org.jetbrains.kotlin.fir.expressions.impl.FirElseIfTrueCondition
import org.jetbrains.kotlin.fir.expressions.impl.FirEmptyExpressionBlock
import org.jetbrains.kotlin.fir.expressions.isExhaustive
import org.jetbrains.kotlin.fir.languageVersionSettings
import org.jetbrains.kotlin.fir.resolve.fullyExpandedType
@@ -37,8 +38,23 @@ object FirExhaustiveWhenChecker : FirWhenExpressionChecker(MppCheckerKind.Common
reportElseMisplaced(expression, reporter, context)
}
private fun reportEmptyThenInExpression(whenExpression: FirWhenExpression, context: CheckerContext, reporter: DiagnosticReporter) {
val source = whenExpression.source ?: return
if (source.isIfExpression && whenExpression.usedAsExpression) {
val thenBranch = whenExpression.branches.firstOrNull()
if (thenBranch == null || thenBranch.result is FirEmptyExpressionBlock) {
reporter.reportOn(source, FirErrors.INVALID_IF_AS_EXPRESSION, context)
}
}
}
private fun reportNotExhaustive(whenExpression: FirWhenExpression, context: CheckerContext, reporter: DiagnosticReporter) {
if (whenExpression.isExhaustive) return
if (whenExpression.isExhaustive) {
// whenExpression.isExhaustive is checked as otherwise the constraint is checked below
reportEmptyThenInExpression(whenExpression, context, reporter)
return
}
val source = whenExpression.source ?: return
@@ -72,7 +72,7 @@ fun blockReturnValueTypeMatch2() : Int {
return <!INVALID_IF_AS_EXPRESSION!>if<!> (1 > 2) 1
}
fun blockReturnValueTypeMatch3() : Int {
return <!RETURN_TYPE_MISMATCH!>if (1 > 2) else 1<!>
return <!RETURN_TYPE_MISMATCH!><!INVALID_IF_AS_EXPRESSION!>if<!> (1 > 2) else 1<!>
}
fun blockReturnValueTypeMatch4() : Int {
if (1 > 2)
@@ -2,7 +2,7 @@
fun example() {
val a = if (true) true else false
val b = if (true) else false
val b = <!INVALID_IF_AS_EXPRESSION!>if<!> (true) else false
val c = <!INVALID_IF_AS_EXPRESSION!>if<!> (true) true
val d = <!INVALID_IF_AS_EXPRESSION!>if<!> (true) true else;
val e = if (true) {} else false