New Intention Action: Replace with operator assign

Replaces a statement of the form a = a + b with a statement of the form
a += b.
This commit is contained in:
Pradyoth Kukkapalli
2014-04-05 01:03:12 -04:00
parent 8777ab9ee8
commit 249af96d3c
23 changed files with 265 additions and 1 deletions
@@ -386,6 +386,7 @@ fun main(args: Array<String>) {
model("intentions/convertNegatedExpressionWithDemorgansLaw", testMethod = "doTestConvertNegatedExpressionWithDemorgansLaw")
model("intentions/swapBinaryExpression", testMethod = "doTestSwapBinaryExpression")
model("intentions/splitIf", testMethod = "doTestSplitIf")
model("intentions/replaceWithOperatorAssign", testMethod = "doTestReplaceWithOperatorAssign")
}
testClass(javaClass<AbstractJetInspectionTest>()) {
@@ -0,0 +1,4 @@
fun foo(x: Int) {
var y = 1
y += x
}
@@ -0,0 +1,4 @@
fun foo(x: Int) {
var y = 1
<spot>y = y + x</spot>
}
@@ -0,0 +1,5 @@
<html>
<body>
This intention converts an expression that modifies a variable's value and reassigns it to itself to an operation-assign expression.
</body>
</html>
+5
View File
@@ -645,6 +645,11 @@
<category>Kotlin</category>
</intentionAction>
<intentionAction>
<className>org.jetbrains.jet.plugin.intentions.ReplaceWithOperatorAssignIntention</className>
<category>Kotlin</category>
</intentionAction>
<project.converterProvider implementation="org.jetbrains.jet.plugin.converters.JetRunConfigurationSettingsFormatConverterProvider"/>
</extensions>
@@ -287,6 +287,8 @@ convert.negated.expression.with.demorgans.law=Convert negated expression to DeMo
convert.negated.expression.with.demorgans.law.family=Convert negated expression to DeMorgan's equivalent
split.if=Split into 2 if's
split.if.family=Split If
replace.with.operator.assign.intention=Replace with an Operator-Assign Expression
replace.with.operator.assign.intention.family=Replace with an Operator-Assign Expression
property.is.implemented.too.many=Has implementations
property.is.overridden.too.many=Is overridden in subclasses
@@ -0,0 +1,116 @@
/*
* 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 org.jetbrains.jet.lang.psi.JetBinaryExpression
import com.intellij.openapi.editor.Editor
import org.jetbrains.jet.lexer.JetTokens
import org.jetbrains.jet.lang.psi.JetPsiFactory
import org.jetbrains.jet.lang.psi.JetSimpleNameExpression
import org.jetbrains.jet.plugin.project.AnalyzerFacadeWithCache
import org.jetbrains.jet.lang.resolve.BindingContext
import org.jetbrains.jet.plugin.util.JetPsiMatcher
import org.jetbrains.jet.lang.descriptors.ClassDescriptor
import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns
public class ReplaceWithOperatorAssignIntention : JetSelfTargetingIntention<JetBinaryExpression>("replace.with.operator.assign.intention", javaClass()) {
/*
* setText() is a protected function, which is inaccessible from this class.
* This override is a workaround for this issue.
*
* (Related to Issue KT-4617)
*/
override fun setText(text: String) {
super<JetSelfTargetingIntention>.setText(text)
}
override fun isApplicableTo(element: JetBinaryExpression): Boolean {
fun isWellFormedAssignment(element : JetBinaryExpression): Boolean {
val leftExpression = element.getLeft()
val rightExpression = element.getRight()
return leftExpression is JetSimpleNameExpression &&
element.getOperationToken() == JetTokens.EQ &&
rightExpression is JetBinaryExpression &&
rightExpression.getLeft() != null &&
rightExpression.getRight() != null
}
fun checkExpressionRepeat(variableExpression: JetSimpleNameExpression, expression: JetBinaryExpression): Boolean {
val context = AnalyzerFacadeWithCache.getContextForElement(expression)
val descriptor = context[BindingContext.REFERENCE_TARGET, expression.getOperationReference()]?.getContainingDeclaration()
val isPrimitiveOperation = descriptor is ClassDescriptor && KotlinBuiltIns.getInstance().isPrimitiveType(descriptor.getDefaultType())
when {
JetPsiMatcher.checkElementMatch(variableExpression, expression.getLeft()) -> {
val validity = expression.getOperationToken() == JetTokens.PLUS ||
expression.getOperationToken() == JetTokens.MINUS ||
expression.getOperationToken() == JetTokens.MUL ||
expression.getOperationToken() == JetTokens.DIV ||
expression.getOperationToken() == JetTokens.PERC
if (validity) {
setText("Replace with ${expression.getOperationReference().getText()}= Expression")
}
return validity
}
JetPsiMatcher.checkElementMatch(variableExpression, expression.getRight()) -> {
val validity = (expression.getOperationToken() == JetTokens.PLUS ||
expression.getOperationToken() == JetTokens.MUL) &&
isPrimitiveOperation
if (validity) {
setText("Replace with ${expression.getOperationReference().getText()}= Expression")
}
return validity
}
expression.getLeft() is JetBinaryExpression -> return isPrimitiveOperation && checkExpressionRepeat(variableExpression, expression.getLeft() as JetBinaryExpression)
else -> return false
}
}
if (isWellFormedAssignment(element)) {
return checkExpressionRepeat(element.getLeft() as JetSimpleNameExpression, element.getRight() as JetBinaryExpression)
} else {
return false
}
}
override fun applyTo(element: JetBinaryExpression, editor: Editor) {
[tailRecursive]
fun buildReplacement(variableExpression: JetSimpleNameExpression, expression: JetBinaryExpression, replacementBuilder: StringBuilder): String {
when {
JetPsiMatcher.checkElementMatch(variableExpression, expression.getLeft()) -> {
return "${variableExpression.getText()} ${expression.getOperationReference().getText()}= ${expression.getRight()!!.getText()} ${replacementBuilder.toString()}"
}
JetPsiMatcher.checkElementMatch(variableExpression, expression.getRight()) -> {
return "${variableExpression.getText()} ${expression.getOperationReference().getText()}= ${expression.getLeft()!!.getText()} ${replacementBuilder.toString()}"
}
expression.getLeft() is JetBinaryExpression -> {
return buildReplacement(variableExpression, expression.getLeft() as JetBinaryExpression, StringBuilder("${expression.getOperationReference().getText()} ${expression.getRight()!!.getText()} ${replacementBuilder.toString()}"))
}
else -> {
return replacementBuilder.toString()
}
}
}
element.replace(JetPsiFactory.createExpression(element.getProject(), buildReplacement(element.getLeft() as JetSimpleNameExpression, element.getRight() as JetBinaryExpression, StringBuilder())))
}
}
@@ -0,0 +1,5 @@
// IS_APPLICABLE: false
fun foo() {
var x = 0
x = x / 1 + 1
}
@@ -0,0 +1,6 @@
// IS_APPLICABLE: false
fun foo() {
var x = 0
val y = 0
x = y / x + 0
}
@@ -0,0 +1,5 @@
// IS_APPLICABLE: false
fun foo() {
var x = 0
<caret>x = 1 - x
}
@@ -0,0 +1,5 @@
fun foo() {
var x = 0
var y = 0
<caret>x = x + y + 5
}
@@ -0,0 +1,5 @@
fun foo() {
var x = 0
var y = 0
x += y + 5
}
@@ -0,0 +1,5 @@
fun foo() {
var x = 0
var y = 0
<caret>x = y + x + 5
}
@@ -0,0 +1,5 @@
fun foo() {
var x = 0
var y = 0
x += y + 5
}
@@ -0,0 +1,7 @@
// IS_APPLICABLE: false
fun foo() {
var x = 0
val y = 0
val z = 0
<caret>x = y + z
}
@@ -0,0 +1,4 @@
fun foo() {
var x = 0
<caret>x = 1 + x
}
@@ -0,0 +1,4 @@
fun foo() {
var x = 0
x += 1
}
@@ -0,0 +1,5 @@
fun foo() {
var y = 0
val x = 0
<caret>y = y + x
}
@@ -0,0 +1,5 @@
fun foo() {
var y = 0
val x = 0
y += x
}
@@ -0,0 +1,4 @@
fun foo() {
var x = 0
<caret>x = x - 1
}
@@ -0,0 +1,4 @@
fun foo() {
var x = 0
x -= 1
}
@@ -219,6 +219,10 @@ public abstract class AbstractCodeTransformationTest extends LightCodeInsightTes
doTestIntention(path, new SplitIfIntention());
}
public void doTestReplaceWithOperatorAssign(@NotNull String path) throws Exception {
doTestIntention(path, new ReplaceWithOperatorAssignIntention());
}
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.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})
@InnerTestClasses({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})
public class CodeTransformationTestGenerated extends AbstractCodeTransformationTest {
@TestMetadata("idea/testData/intentions/branched/elvisToIfThen")
public static class ElvisToIfThen extends AbstractCodeTransformationTest {
@@ -3092,6 +3092,59 @@ public class CodeTransformationTestGenerated extends AbstractCodeTransformationT
}
@TestMetadata("idea/testData/intentions/replaceWithOperatorAssign")
public static class ReplaceWithOperatorAssign extends AbstractCodeTransformationTest {
public void testAllFilesPresentInReplaceWithOperatorAssign() throws Exception {
JetTestUtils.assertAllTestsPresentByMetadata(this.getClass(), "org.jetbrains.jet.generators.tests.TestsPackage", new File("idea/testData/intentions/replaceWithOperatorAssign"), Pattern.compile("^(.+)\\.kt$"), true);
}
@TestMetadata("illegalMultipleOperators.kt")
public void testIllegalMultipleOperators() throws Exception {
doTestReplaceWithOperatorAssign("idea/testData/intentions/replaceWithOperatorAssign/illegalMultipleOperators.kt");
}
@TestMetadata("illegalMultipleOperatorsMiddle.kt")
public void testIllegalMultipleOperatorsMiddle() throws Exception {
doTestReplaceWithOperatorAssign("idea/testData/intentions/replaceWithOperatorAssign/illegalMultipleOperatorsMiddle.kt");
}
@TestMetadata("invalidSubtraction.kt")
public void testInvalidSubtraction() throws Exception {
doTestReplaceWithOperatorAssign("idea/testData/intentions/replaceWithOperatorAssign/invalidSubtraction.kt");
}
@TestMetadata("multipleOperators.kt")
public void testMultipleOperators() throws Exception {
doTestReplaceWithOperatorAssign("idea/testData/intentions/replaceWithOperatorAssign/multipleOperators.kt");
}
@TestMetadata("multipleOperatorsRightSideRepeat.kt")
public void testMultipleOperatorsRightSideRepeat() throws Exception {
doTestReplaceWithOperatorAssign("idea/testData/intentions/replaceWithOperatorAssign/multipleOperatorsRightSideRepeat.kt");
}
@TestMetadata("nonRepeatingAssignment.kt")
public void testNonRepeatingAssignment() throws Exception {
doTestReplaceWithOperatorAssign("idea/testData/intentions/replaceWithOperatorAssign/nonRepeatingAssignment.kt");
}
@TestMetadata("rightSideRepeat.kt")
public void testRightSideRepeat() throws Exception {
doTestReplaceWithOperatorAssign("idea/testData/intentions/replaceWithOperatorAssign/rightSideRepeat.kt");
}
@TestMetadata("simpleAssign.kt")
public void testSimpleAssign() throws Exception {
doTestReplaceWithOperatorAssign("idea/testData/intentions/replaceWithOperatorAssign/simpleAssign.kt");
}
@TestMetadata("validSubtraction.kt")
public void testValidSubtraction() throws Exception {
doTestReplaceWithOperatorAssign("idea/testData/intentions/replaceWithOperatorAssign/validSubtraction.kt");
}
}
public static Test suite() {
TestSuite suite = new TestSuite("CodeTransformationTestGenerated");
suite.addTestSuite(ElvisToIfThen.class);
@@ -3139,6 +3192,7 @@ public class CodeTransformationTestGenerated extends AbstractCodeTransformationT
suite.addTestSuite(ConvertNegatedExpressionWithDemorgansLaw.class);
suite.addTestSuite(SwapBinaryExpression.class);
suite.addTestSuite(SplitIf.class);
suite.addTestSuite(ReplaceWithOperatorAssign.class);
return suite;
}
}