KT-6159: generate Unit while code inlining when needed

This commit is contained in:
Mikhail Glukhikh
2017-03-23 18:57:19 +03:00
parent 7de0197a60
commit b6803af746
4 changed files with 12 additions and 8 deletions
@@ -25,7 +25,6 @@ import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import java.util.* import java.util.*
internal abstract class ReplacementPerformer<TElement : KtElement>( internal abstract class ReplacementPerformer<TElement : KtElement>(
@@ -85,14 +84,16 @@ internal class ExpressionReplacementPerformer(
elementToBeReplaced.replace(codeToInline.mainExpression!!) elementToBeReplaced.replace(codeToInline.mainExpression!!)
} }
else { else {
val bindingContext = elementToBeReplaced.analyze(BodyResolveMode.FULL) // NB: Unit is never used as expression
val canDropElementToBeReplaced = !elementToBeReplaced.isUsedAsExpression(bindingContext) val stub = elementToBeReplaced.replace(psiFactory.createExpression("0")) as KtExpression
val bindingContext = stub.analyze()
val canDropElementToBeReplaced = !stub.isUsedAsExpression(bindingContext)
if (canDropElementToBeReplaced) { if (canDropElementToBeReplaced) {
elementToBeReplaced.delete() stub.delete()
null null
} }
else { else {
elementToBeReplaced.replace(psiFactory.createExpression("Unit")) stub.replace(psiFactory.createExpression("Unit"))
} }
} }
@@ -2,9 +2,9 @@ fun <T> doIt(p: () -> T): T = TODO()
fun g(p: String?) { fun g(p: String?) {
p?.let { } p?.let { Unit }
} }
fun h() = Unit fun h() = Unit
fun x() = doIt { } fun x() = doIt { Unit }
@@ -9,6 +9,7 @@ class C {
p?.let { p?.let {
println(3) println(3)
println(4) println(4)
Unit
} }
if (other != null) { if (other != null) {
@@ -25,5 +26,6 @@ class C {
fun x() = doIt { fun x() = doIt {
println(9) println(9)
println(10) println(10)
Unit
} }
} }
@@ -9,6 +9,7 @@ fun g(p: String?) {
p?.let { p?.let {
println(3) println(3)
nonUnit(4) nonUnit(4)
Unit
} }
} }
@@ -20,5 +21,5 @@ fun h() {
fun x() = doIt { fun x() = doIt {
println(7) println(7)
nonUnit(8) nonUnit(8)
// Unit should be here Unit
} }