Introduce Parameter: Do not suggest containers of object and non-inner classes

This commit is contained in:
Alexey Sedunov
2015-04-07 20:40:20 +03:00
parent 80134b9b2b
commit 918eda0c9b
4 changed files with 46 additions and 1 deletions
@@ -135,6 +135,9 @@ fun IntroduceParameterDescriptor.performRefactoring() {
public open class KotlinIntroduceParameterHandler: KotlinIntroduceHandlerBase() {
open fun configure(descriptor: IntroduceParameterDescriptor): IntroduceParameterDescriptor = descriptor
private fun isObjectOrNonInnerClass(e: PsiElement): Boolean =
e is JetObjectDeclaration || (e is JetClass && !e.isInner())
fun invoke(project: Project, editor: Editor, expression: JetExpression, targetParent: JetNamedDeclaration) {
val psiFactory = JetPsiFactory(project)
@@ -170,8 +173,19 @@ public open class KotlinIntroduceParameterHandler: KotlinIntroduceHandlerBase()
.filter { it.second.isNotEmpty() }
.toMap()
val forbiddenRanges =
if (targetParent is JetClass) {
targetParent.getDeclarations().filter { isObjectOrNonInnerClass(it) }.map { it.getTextRange() }
}
else {
Collections.emptyList()
}
val occurrencesToReplace = expression.toRange()
.match(body, JetPsiUnifier.DEFAULT)
.filterNot {
val textRange = it.range.getTextRange()
forbiddenRanges.any { it.intersects(textRange) }
}
.map {
val matchedElement = it.range.elements.singleOrNull()
when (matchedElement) {
@@ -241,7 +255,12 @@ public open class KotlinIntroduceParameterHandler: KotlinIntroduceHandlerBase()
editor = editor,
file = file,
getContainers = { elements, parent ->
parent.parents(withItself = false)
val parents = parent.parents(withItself = false)
val stopAt = (parent.parents(withItself = false) zip parent.parents(withItself = false).drop(1))
.firstOrNull { isObjectOrNonInnerClass(it.first) }
?.second
(if (stopAt != null) parent.parents(withItself = false).takeWhile { it != stopAt } else parents)
.filter {
((it is JetClass && !it.isTrait() && it !is JetEnumEntry) || it is JetNamedFunction || it is JetSecondaryConstructor) &&
((it as JetNamedDeclaration).getValueParameterList() != null || it.getNameIdentifier() != null)
@@ -0,0 +1,10 @@
// TARGET:
class A {
inner class B {
fun foo() = <selection>1</selection>
}
object O {
fun foo() = 1
}
}
@@ -0,0 +1,10 @@
// TARGET:
class A(val i: Int = 1) {
inner class B {
fun foo() = i
}
object O {
fun foo() = 1
}
}
@@ -2269,6 +2269,12 @@ public class JetExtractionTestGenerated extends AbstractJetExtractionTest {
doIntroduceParameterTest(fileName);
}
@TestMetadata("forbiddenUsages.kt")
public void testForbiddenUsages() throws Exception {
String fileName = JetTestUtils.navigationMetadata("idea/testData/refactoring/introduceParameter/forbiddenUsages.kt");
doIntroduceParameterTest(fileName);
}
@TestMetadata("functionMultipleUnusedParameters.kt")
public void testFunctionMultipleUnusedParameters() throws Exception {
String fileName = JetTestUtils.navigationMetadata("idea/testData/refactoring/introduceParameter/functionMultipleUnusedParameters.kt");