KT-11104 extra : name validator introduced for wrap with safe let call

This commit is contained in:
Mikhail Glukhikh
2016-06-13 14:17:54 +03:00
parent 3c49b5f342
commit 230f73acc9
4 changed files with 31 additions and 2 deletions
@@ -21,6 +21,8 @@ import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.types.TypeUtils
@@ -38,8 +40,13 @@ class WrapWithSafeLetCallFix(
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val factory = KtPsiFactory(element)
val nullableText = nullableExpression.text
nullableExpression.replace(factory.createExpression("it"))
val wrapped = factory.createExpressionByPattern("$0?.let { $1 }", nullableText, element.text)
val validator = NewDeclarationNameValidator(element, nullableExpression, NewDeclarationNameValidator.Target.VARIABLES)
val name = KotlinNameSuggester.suggestNameByName("it", validator)
nullableExpression.replace(factory.createExpression(name))
val wrapped = when (name) {
"it" -> factory.createExpressionByPattern("$0?.let { $1 }", nullableText, element)
else -> factory.createExpressionByPattern("$0?.let { $1 -> $2 }", nullableText, name, element)
}
element.replace(wrapped)
}
@@ -0,0 +1,8 @@
// "Wrap with '?.let { ... }' call" "true"
// WITH_RUNTIME
fun foo(x: String?, y: String) {
y.let { bar(<caret>x, it) }
}
fun bar(s: String, t: String) = s.hashCode() + t.hashCode()
@@ -0,0 +1,8 @@
// "Wrap with '?.let { ... }' call" "true"
// WITH_RUNTIME
fun foo(x: String?, y: String) {
y.let { x?.let { it1 -> bar(it1, it) } }
}
fun bar(s: String, t: String) = s.hashCode() + t.hashCode()
@@ -8788,6 +8788,12 @@ public class QuickFixTestGenerated extends AbstractQuickFixTest {
doTest(fileName);
}
@TestMetadata("insideLet.kt")
public void testInsideLet() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/quickfix/wrapWithSafeLetCall/insideLet.kt");
doTest(fileName);
}
@TestMetadata("invokeFuncUnsafe.kt")
public void testInvokeFuncUnsafe() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/quickfix/wrapWithSafeLetCall/invokeFuncUnsafe.kt");