New Intention Action: Replace a call to forEach function with for loop.

Replaces an expression of form x.forEach { … } with for (a in x) { … }.
This commit is contained in:
Pradyoth Kukkapalli
2014-04-07 11:47:58 -04:00
committed by Mikhael Bogdanov
parent bd056d037f
commit dbb28c571b
26 changed files with 330 additions and 2 deletions
@@ -412,6 +412,7 @@ fun main(args: Array<String>) {
model("intentions/convertIfToAssert", testMethod = "doTestConvertIfWithThrowToAssertIntention")
model("intentions/makeTypeExplicitInLambda", testMethod = "doTestMakeTypeExplicitInLambda")
model("intentions/makeTypeImplicitInLambda", testMethod = "doTestMakeTypeImplicitInLambda")
model("intentions/convertToForEachLoop", testMethod = "doTestConvertToForEachLoop")
}
testClass(javaClass<AbstractJetInspectionTest>()) {
@@ -0,0 +1,5 @@
fun foo() {
for (a in x) {
a.bar()
}
}
@@ -0,0 +1,3 @@
fun foo() {
<spot>x.forEach { a -> a.bar() }</spot>
}
@@ -0,0 +1,5 @@
<html>
<body>
This intention converts a call to the "forEach" function into a for each loop expression.
</body>
</html>
+7 -1
View File
@@ -696,7 +696,13 @@
<category>Kotlin</category>
</intentionAction>
<localInspection implementationClass="org.jetbrains.jet.plugin.inspections.ExplicitGetInspection"
<intentionAction>
<className>org.jetbrains.jet.plugin.intentions.ConvertToForEachLoopIntention</className>
<category>Kotlin</category>
</intentionAction>
<localInspection implementationClass="org.jetbrains.jet.plugin.inspections.ExplicitGetInspection"
displayName="Explicit 'get'"
groupName="Kotlin"
enabledByDefault="true"
@@ -312,6 +312,8 @@ make.type.explicit.in.lambda=Make types explicit in lambda
make.type.explicit.in.lambda.family=Make Types Explicit In Lambda
make.type.implicit.in.lambda=Make types implicit in lambda (may break code)
make.type.implicit.in.lambda.family=Make Types Implicit In Lambda (May Break Code)
convert.to.for.each.loop.intention=Replace with a For Each Loop
convert.to.for.each.loop.intention.family=Replace with a For Each Loop
property.is.implemented.too.many=Has implementations
property.is.overridden.too.many=Is overridden in subclasses
@@ -0,0 +1,121 @@
/*
* Copyright 2010-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jet.plugin.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.jet.lang.psi.JetCallExpression
import org.jetbrains.jet.lang.psi.JetFunctionLiteralExpression
import org.jetbrains.jet.lang.psi.JetPsiFactory
import org.jetbrains.jet.lang.psi.JetExpression
import org.jetbrains.jet.lang.psi.JetDotQualifiedExpression
import org.jetbrains.jet.lang.psi.JetBinaryExpression
import org.jetbrains.jet.lang.resolve.DescriptorUtils
import org.jetbrains.jet.lang.resolve.BindingContext
import org.jetbrains.jet.lang.psi.JetPsiUtil
import org.jetbrains.jet.plugin.caches.resolve.getLazyResolveSession
import org.jetbrains.jet.lang.psi.JetParenthesizedExpression
public class ConvertToForEachLoopIntention : JetSelfTargetingIntention<JetExpression>("convert.to.for.each.loop.intention", javaClass()) {
private fun getFunctionLiteralArgument(element: JetExpression): JetFunctionLiteralExpression? {
val argument = when (element) {
is JetDotQualifiedExpression -> {
val selector = element.getSelectorExpression()
when (selector) {
is JetCallExpression -> {
when {
selector.getValueArguments().size() > 0 -> selector.getValueArguments()[0]!!.getArgumentExpression()
selector.getFunctionLiteralArguments().size() > 0 -> selector.getFunctionLiteralArguments()[0]
else -> null
}
}
}
}
is JetBinaryExpression -> element.getRight()
else -> null
}
return when (argument) {
is JetFunctionLiteralExpression -> argument
else -> null
}
}
override fun isApplicableTo(element: JetExpression): Boolean {
fun isWellFormedFunctionLiteral(element: JetFunctionLiteralExpression): Boolean {
return element.getValueParameters().size() <= 1 && element.getBodyExpression() != null
}
fun checkTotalNumberOfArguments(element: JetExpression): Boolean {
return when (element) {
is JetDotQualifiedExpression -> {
val selector = element.getSelectorExpression()
when (selector) {
is JetCallExpression -> (selector.getValueArguments().size() + selector.getFunctionLiteralArguments().size()) == 1
else -> false
}
}
is JetBinaryExpression -> true
else -> false
}
}
val callee = JetPsiUtil.getCalleeExpressionIfAny(element)
val functionLiteral = getFunctionLiteralArgument(element)
if (callee != null &&
functionLiteral != null &&
isWellFormedFunctionLiteral(functionLiteral) &&
checkTotalNumberOfArguments(element)) {
val context = element.getContainingJetFile().getLazyResolveSession().resolveToElement(callee)
val resolvedCall = context[BindingContext.RESOLVED_CALL, callee]
val functionFqName = if (resolvedCall != null) DescriptorUtils.getFqName(resolvedCall.getResultingDescriptor()).toString() else null
return "kotlin.forEach".equals(functionFqName);
}
return false;
}
override fun applyTo(element: JetExpression, editor: Editor) {
fun buildLoopRangeText(receiver: JetExpression): String? {
return when (receiver) {
is JetParenthesizedExpression -> receiver.getExpression()?.getText()
else -> receiver.getText()
}
}
fun generateLoopText(receiver: JetExpression, functionLiteral: JetFunctionLiteralExpression): String {
return when {
functionLiteral.getValueParameters().size() == 0 -> "for (it in ${buildLoopRangeText(receiver)}) { ${functionLiteral.getBodyExpression()!!.getText()} }"
else -> "for (${functionLiteral.getValueParameters()[0].getText()} in ${buildLoopRangeText(receiver)}) { ${functionLiteral.getBodyExpression()!!.getText()} }"
}
}
val receiver = when (element) {
is JetDotQualifiedExpression -> element.getReceiverExpression()
is JetBinaryExpression -> element.getLeft()
else -> throw IllegalArgumentException("The expression ${element.getText()} cannot be converted to a for each loop.")
}!!
val functionLiteral = getFunctionLiteralArgument(element)!!
element.replace(JetPsiFactory.createExpression(element.getProject(), generateLoopText(receiver, functionLiteral)))
}
}
@@ -0,0 +1,6 @@
// WITH_RUNTIME
fun main() {
val x = 1..4
<caret>x.reverse().forEach { it }
}
@@ -0,0 +1,8 @@
// WITH_RUNTIME
fun main() {
val x = 1..4
for (it in x.reverse()) {
it
}
}
@@ -0,0 +1,6 @@
// WITH_RUNTIME
fun foo() {
val x = 1..4
<caret>x.forEach({ y -> y })
}
@@ -0,0 +1,8 @@
// WITH_RUNTIME
fun foo() {
val x = 1..4
for (y in x) {
y
}
}
@@ -0,0 +1,11 @@
// IS_APPLICABLE: false
// WITH_RUNTIME
class Foo {
fun forEach(predicate: (Int) -> Int, bar: Int): Int = predicate(bar)
}
fun main() {
val x = Foo()
<caret>x.forEach({ it * 2 }, 2)
}
@@ -0,0 +1,6 @@
// WITH_RUNTIME
fun foo() {
val x = 1..4
<caret>x.forEach { it }
}
@@ -0,0 +1,8 @@
// WITH_RUNTIME
fun foo() {
val x = 1..4
for (it in x) {
it
}
}
@@ -0,0 +1,6 @@
// WITH_RUNTIME
fun foo() {
val x = 1..4
<caret>x forEach { a -> a }
}
@@ -0,0 +1,8 @@
// WITH_RUNTIME
fun foo() {
val x = 1..4
for (a in x) {
a
}
}
@@ -0,0 +1,4 @@
// WITH_RUNTIME
fun main() {
<caret>(1 rangeTo 2).forEach { x -> x }
}
@@ -0,0 +1,6 @@
// WITH_RUNTIME
fun main() {
for (x in 1 rangeTo 2) {
x
}
}
@@ -0,0 +1,6 @@
// WITH_RUNTIME
fun foo() {
val x = 1..4
<caret>x.forEach { it.equals(1) }
}
@@ -0,0 +1,8 @@
// WITH_RUNTIME
fun foo() {
val x = 1..4
for (it in x) {
it.equals(1)
}
}
@@ -0,0 +1,6 @@
// WITH_RUNTIME
fun foo() {
val x = 1..4
<caret>x.forEach<Int>({ it })
}
@@ -0,0 +1,8 @@
// WITH_RUNTIME
fun foo() {
val x = 1..4
for (it in x) {
it
}
}
@@ -0,0 +1,11 @@
// IS_APPLICABLE: false
// WITH_RUNTIME
class Foo {
fun forEach(predicate: (Int) -> Int): Int = predicate(0)
}
fun main() {
val x = Foo()
<caret>x.forEach({ it * 2 })
}
@@ -0,0 +1,11 @@
// IS_APPLICABLE: false
// WITH_RUNTIME
class Foo {
fun forEach(): Int = 0
}
fun main() {
val x = Foo()
<caret>x.forEach()
}
@@ -266,6 +266,10 @@ public abstract class AbstractCodeTransformationTest extends LightCodeInsightTes
doTestIntention(path, new MakeTypeImplicitInLambdaIntention());
}
public void doTestConvertToForEachLoop(@NotNull String path) throws Exception {
doTestIntention(path, new ConvertToForEachLoopIntention());
}
private void doTestIntention(@NotNull String path, @NotNull IntentionAction intentionAction) throws Exception {
configureByFile(path);
@@ -30,7 +30,7 @@ import org.jetbrains.jet.plugin.intentions.AbstractCodeTransformationTest;
/** This class is generated by {@link org.jetbrains.jet.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@InnerTestClasses({CodeTransformationTestGenerated.DoubleBangToIfThen.class, CodeTransformationTestGenerated.IfThenToDoubleBang.class, CodeTransformationTestGenerated.ElvisToIfThen.class, CodeTransformationTestGenerated.IfThenToElvis.class, CodeTransformationTestGenerated.SafeAccessToIfThen.class, CodeTransformationTestGenerated.IfThenToSafeAccess.class, CodeTransformationTestGenerated.IfToAssignment.class, CodeTransformationTestGenerated.IfToReturn.class, CodeTransformationTestGenerated.IfToReturnAsymmetrically.class, CodeTransformationTestGenerated.WhenToAssignment.class, CodeTransformationTestGenerated.WhenToReturn.class, CodeTransformationTestGenerated.AssignmentToIf.class, CodeTransformationTestGenerated.AssignmentToWhen.class, CodeTransformationTestGenerated.PropertyToIf.class, CodeTransformationTestGenerated.PropertyToWhen.class, CodeTransformationTestGenerated.ReturnToIf.class, CodeTransformationTestGenerated.ReturnToWhen.class, CodeTransformationTestGenerated.IfToWhen.class, CodeTransformationTestGenerated.WhenToIf.class, CodeTransformationTestGenerated.Flatten.class, CodeTransformationTestGenerated.Merge.class, CodeTransformationTestGenerated.IntroduceSubject.class, CodeTransformationTestGenerated.EliminateSubject.class, CodeTransformationTestGenerated.Split.class, CodeTransformationTestGenerated.Join.class, CodeTransformationTestGenerated.ConvertMemberToExtension.class, CodeTransformationTestGenerated.ReconstructedType.class, CodeTransformationTestGenerated.RemoveUnnecessaryParentheses.class, CodeTransformationTestGenerated.ReplaceWithDotQualifiedMethodCall.class, CodeTransformationTestGenerated.ReplaceWithInfixFunctionCall.class, CodeTransformationTestGenerated.RemoveCurlyBracesFromTemplate.class, CodeTransformationTestGenerated.MoveLambdaInsideParentheses.class, CodeTransformationTestGenerated.MoveLambdaOutsideParentheses.class, CodeTransformationTestGenerated.ReplaceExplicitFunctionLiteralParamWithIt.class, CodeTransformationTestGenerated.ReplaceItWithExplicitFunctionLiteralParam.class, CodeTransformationTestGenerated.RemoveBraces.class, CodeTransformationTestGenerated.AddBraces.class, CodeTransformationTestGenerated.ReplaceGetIntention.class, CodeTransformationTestGenerated.ReplaceContainsIntention.class, CodeTransformationTestGenerated.ReplaceBinaryInfixIntention.class, CodeTransformationTestGenerated.ReplaceUnaryPrefixIntention.class, CodeTransformationTestGenerated.ReplaceInvokeIntention.class, CodeTransformationTestGenerated.SimplifyNegatedBinaryExpressionIntention.class, CodeTransformationTestGenerated.ConvertNegatedBooleanSequence.class, CodeTransformationTestGenerated.ConvertNegatedExpressionWithDemorgansLaw.class, CodeTransformationTestGenerated.SwapBinaryExpression.class, CodeTransformationTestGenerated.SplitIf.class, CodeTransformationTestGenerated.ReplaceWithOperatorAssign.class, CodeTransformationTestGenerated.ReplaceWithTraditionalAssignment.class, CodeTransformationTestGenerated.SimplifyBooleanWithConstants.class, CodeTransformationTestGenerated.InsertExplicitTypeArguments.class, CodeTransformationTestGenerated.RemoveExplicitTypeArguments.class, CodeTransformationTestGenerated.ConvertAssertToIf.class, CodeTransformationTestGenerated.ConvertIfToAssert.class, CodeTransformationTestGenerated.MakeTypeExplicitInLambda.class, CodeTransformationTestGenerated.MakeTypeImplicitInLambda.class})
@InnerTestClasses({CodeTransformationTestGenerated.DoubleBangToIfThen.class, CodeTransformationTestGenerated.IfThenToDoubleBang.class, CodeTransformationTestGenerated.ElvisToIfThen.class, CodeTransformationTestGenerated.IfThenToElvis.class, CodeTransformationTestGenerated.SafeAccessToIfThen.class, CodeTransformationTestGenerated.IfThenToSafeAccess.class, CodeTransformationTestGenerated.IfToAssignment.class, CodeTransformationTestGenerated.IfToReturn.class, CodeTransformationTestGenerated.IfToReturnAsymmetrically.class, CodeTransformationTestGenerated.WhenToAssignment.class, CodeTransformationTestGenerated.WhenToReturn.class, CodeTransformationTestGenerated.AssignmentToIf.class, CodeTransformationTestGenerated.AssignmentToWhen.class, CodeTransformationTestGenerated.PropertyToIf.class, CodeTransformationTestGenerated.PropertyToWhen.class, CodeTransformationTestGenerated.ReturnToIf.class, CodeTransformationTestGenerated.ReturnToWhen.class, CodeTransformationTestGenerated.IfToWhen.class, CodeTransformationTestGenerated.WhenToIf.class, CodeTransformationTestGenerated.Flatten.class, CodeTransformationTestGenerated.Merge.class, CodeTransformationTestGenerated.IntroduceSubject.class, CodeTransformationTestGenerated.EliminateSubject.class, CodeTransformationTestGenerated.Split.class, CodeTransformationTestGenerated.Join.class, CodeTransformationTestGenerated.ConvertMemberToExtension.class, CodeTransformationTestGenerated.ReconstructedType.class, CodeTransformationTestGenerated.RemoveUnnecessaryParentheses.class, CodeTransformationTestGenerated.ReplaceWithDotQualifiedMethodCall.class, CodeTransformationTestGenerated.ReplaceWithInfixFunctionCall.class, CodeTransformationTestGenerated.RemoveCurlyBracesFromTemplate.class, CodeTransformationTestGenerated.MoveLambdaInsideParentheses.class, CodeTransformationTestGenerated.MoveLambdaOutsideParentheses.class, CodeTransformationTestGenerated.ReplaceExplicitFunctionLiteralParamWithIt.class, CodeTransformationTestGenerated.ReplaceItWithExplicitFunctionLiteralParam.class, CodeTransformationTestGenerated.RemoveBraces.class, CodeTransformationTestGenerated.AddBraces.class, CodeTransformationTestGenerated.ReplaceGetIntention.class, CodeTransformationTestGenerated.ReplaceContainsIntention.class, CodeTransformationTestGenerated.ReplaceBinaryInfixIntention.class, CodeTransformationTestGenerated.ReplaceUnaryPrefixIntention.class, CodeTransformationTestGenerated.ReplaceInvokeIntention.class, CodeTransformationTestGenerated.SimplifyNegatedBinaryExpressionIntention.class, CodeTransformationTestGenerated.ConvertNegatedBooleanSequence.class, CodeTransformationTestGenerated.ConvertNegatedExpressionWithDemorgansLaw.class, CodeTransformationTestGenerated.SwapBinaryExpression.class, CodeTransformationTestGenerated.SplitIf.class, CodeTransformationTestGenerated.ReplaceWithOperatorAssign.class, CodeTransformationTestGenerated.ReplaceWithTraditionalAssignment.class, CodeTransformationTestGenerated.SimplifyBooleanWithConstants.class, CodeTransformationTestGenerated.InsertExplicitTypeArguments.class, CodeTransformationTestGenerated.RemoveExplicitTypeArguments.class, CodeTransformationTestGenerated.ConvertAssertToIf.class, CodeTransformationTestGenerated.ConvertIfToAssert.class, CodeTransformationTestGenerated.MakeTypeExplicitInLambda.class, CodeTransformationTestGenerated.MakeTypeImplicitInLambda.class, CodeTransformationTestGenerated.ConvertToForEachLoop.class})
public class CodeTransformationTestGenerated extends AbstractCodeTransformationTest {
@TestMetadata("idea/testData/intentions/branched/doubleBangToIfThen")
public static class DoubleBangToIfThen extends AbstractCodeTransformationTest {
@@ -4124,6 +4124,59 @@ public class CodeTransformationTestGenerated extends AbstractCodeTransformationT
}
@TestMetadata("idea/testData/intentions/convertToForEachLoop")
public static class ConvertToForEachLoop extends AbstractCodeTransformationTest {
public void testAllFilesPresentInConvertToForEachLoop() throws Exception {
JetTestUtils.assertAllTestsPresentByMetadata(this.getClass(), "org.jetbrains.jet.generators.tests.TestsPackage", new File("idea/testData/intentions/convertToForEachLoop"), Pattern.compile("^(.+)\\.kt$"), true);
}
@TestMetadata("complexReceiver.kt")
public void testComplexReceiver() throws Exception {
doTestConvertToForEachLoop("idea/testData/intentions/convertToForEachLoop/complexReceiver.kt");
}
@TestMetadata("explicitFunctionLiteral.kt")
public void testExplicitFunctionLiteral() throws Exception {
doTestConvertToForEachLoop("idea/testData/intentions/convertToForEachLoop/explicitFunctionLiteral.kt");
}
@TestMetadata("extraArguments.kt")
public void testExtraArguments() throws Exception {
doTestConvertToForEachLoop("idea/testData/intentions/convertToForEachLoop/extraArguments.kt");
}
@TestMetadata("implicitFunctionLiteralParameter.kt")
public void testImplicitFunctionLiteralParameter() throws Exception {
doTestConvertToForEachLoop("idea/testData/intentions/convertToForEachLoop/implicitFunctionLiteralParameter.kt");
}
@TestMetadata("infixCall.kt")
public void testInfixCall() throws Exception {
doTestConvertToForEachLoop("idea/testData/intentions/convertToForEachLoop/infixCall.kt");
}
@TestMetadata("simple.kt")
public void testSimple() throws Exception {
doTestConvertToForEachLoop("idea/testData/intentions/convertToForEachLoop/simple.kt");
}
@TestMetadata("typeArgumentPresent.kt")
public void testTypeArgumentPresent() throws Exception {
doTestConvertToForEachLoop("idea/testData/intentions/convertToForEachLoop/typeArgumentPresent.kt");
}
@TestMetadata("userDefined.kt")
public void testUserDefined() throws Exception {
doTestConvertToForEachLoop("idea/testData/intentions/convertToForEachLoop/userDefined.kt");
}
@TestMetadata("zeroArguments.kt")
public void testZeroArguments() throws Exception {
doTestConvertToForEachLoop("idea/testData/intentions/convertToForEachLoop/zeroArguments.kt");
}
}
public static Test suite() {
TestSuite suite = new TestSuite("CodeTransformationTestGenerated");
suite.addTestSuite(DoubleBangToIfThen.class);
@@ -4182,6 +4235,7 @@ public class CodeTransformationTestGenerated extends AbstractCodeTransformationT
suite.addTestSuite(ConvertIfToAssert.class);
suite.addTestSuite(MakeTypeExplicitInLambda.class);
suite.addTestSuite(MakeTypeImplicitInLambda.class);
suite.addTestSuite(ConvertToForEachLoop.class);
return suite;
}
}