IDEA-164880 Refactoring to function composition methods

This commit is contained in:
Tagir Valeev
2016-12-06 12:23:05 +07:00
parent d76aee1576
commit d7cb4edc8d
17 changed files with 297 additions and 0 deletions
@@ -0,0 +1,117 @@
/*
* Copyright 2000-2016 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 com.intellij.codeInsight.intention.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.ig.psiutils.CommentTracker;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
public class ComposeFunctionChainAction extends PsiElementBaseIntentionAction {
private static final Logger LOG = Logger.getInstance(ComposeFunctionChainAction.class.getName());
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull final PsiElement element) {
PsiMethodCallExpression call =
PsiTreeUtil.getParentOfType(element, PsiMethodCallExpression.class, false, PsiStatement.class, PsiLambdaExpression.class);
if(call == null) return false;
if(!"apply".equals(call.getMethodExpression().getReferenceName())) return false;
PsiMethod method = call.resolveMethod();
if(method == null) return false;
PsiClass aClass = method.getContainingClass();
if(aClass == null) return false;
if(!CommonClassNames.JAVA_UTIL_FUNCTION_FUNCTION.equals(aClass.getQualifiedName()) &&
!CommonClassNames.JAVA_UTIL_FUNCTION_BIFUNCTION.equals(aClass.getQualifiedName())) {
return false;
}
PsiElement parent = PsiUtil.skipParenthesizedExprUp(call.getParent());
if (!(parent instanceof PsiExpressionList) || ((PsiExpressionList)parent).getExpressions().length != 1) return false;
PsiElement gParent = parent.getParent();
if (!(gParent instanceof PsiMethodCallExpression)) return false;
PsiMethod outerMethod = ((PsiMethodCallExpression)gParent).resolveMethod();
if (outerMethod == null ||
!Arrays.stream(outerMethod.getThrowsList().getReferencedTypes()).allMatch(ExceptionUtil::isUncheckedException)) {
return false;
}
return true;
}
@NotNull
@Override
public String getText() {
return CodeInsightBundle.message("intention.compose.function.text");
}
@Override
@NotNull
public String getFamilyName() {
return CodeInsightBundle.message("intention.compose.function.family");
}
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
PsiMethodCallExpression call =
PsiTreeUtil.getParentOfType(element, PsiMethodCallExpression.class, false, PsiStatement.class, PsiLambdaExpression.class);
if(call == null) return;
PsiElement outer = call.getParent().getParent();
if(!(outer instanceof PsiMethodCallExpression)) return;
PsiMethodCallExpression outerCall = (PsiMethodCallExpression)outer;
PsiMethod outerMethod = outerCall.resolveMethod();
if(outerMethod == null) return;
PsiClass outerClass = outerMethod.getContainingClass();
if(outerClass == null) return;
String outerClassName = outerClass.getQualifiedName();
PsiExpression qualifier = call.getMethodExpression().getQualifierExpression();
PsiExpression outerQualifier = outerCall.getMethodExpression().getQualifierExpression();
CommentTracker ct = new CommentTracker();
String reference;
if(outerMethod.getName().equals("apply") && CommonClassNames.JAVA_UTIL_FUNCTION_FUNCTION.equals(outerClassName)) {
reference = outerQualifier == null ? "this" : ct.text(outerQualifier);
} else if(outerMethod.hasModifierProperty(PsiModifier.STATIC)) {
reference = outerClassName + "::" + outerMethod.getName();
} else {
reference = outerQualifier == null ? "this" : ct.text(outerQualifier)+"::"+outerMethod.getName();
}
String resultQualifier = qualifier != null ? ct.text(qualifier) + "." : "";
String replacement = resultQualifier + "andThen(" + reference + ").apply" + ct.text(call.getArgumentList());
PsiElement result =
ct.replaceAndRestoreComments(outer, JavaPsiFacade.getElementFactory(project).createExpressionFromText(replacement, outer));
result = CodeStyleManager.getInstance(project).reformat(result);
PsiElement applyElement = ((PsiMethodCallExpression)result).getMethodExpression().getReferenceNameElement();
if(applyElement != null) {
editor.getCaretModel().moveToOffset(applyElement.getTextOffset() + applyElement.getTextLength());
}
}
}
@@ -0,0 +1,17 @@
// "Replace nested function call with andThen call" "true"
import java.util.Collections;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.UnaryOperator;
public class Main {
private void testFn() {
Function<String, Integer> lookup = Integer::parseInt;
UnaryOperator<String> selector = String::trim;
BinaryOperator<Integer> min = Math::min;
String foo = "xyz";
int res = min.andThen(Math::abs).apply(-1, -2);
}
}
@@ -0,0 +1,19 @@
// "Replace nested function call with andThen call" "true"
import java.util.Collections;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.UnaryOperator;
public class Main {
private void testFn() {
Function<String, Integer> lookup = Integer::parseInt;
UnaryOperator<String> selector = String::trim;
BinaryOperator<Integer> min = Math::min;
String foo = "xyz";
/*check*/
boolean b = selector.andThen(Collections.singleton(/* "xyz" here */ "xyz")::contains).apply(/* foo here */ foo);
}
}
@@ -0,0 +1,11 @@
// "Replace nested function call with andThen call" "true"
import java.util.function.UnaryOperator;
public class Main {
private void testFn(boolean b) {
String foo = "xyz";
Integer f = (b ? (UnaryOperator<String>) String::trim : (UnaryOperator<String>) s -> s.substring(1)).andThen(Integer::parseInt).apply(foo);
}
}
@@ -0,0 +1,16 @@
// "Replace nested function call with andThen call" "true"
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.UnaryOperator;
public class Main {
private void testFn() {
Function<String, Integer> lookup = Integer::parseInt;
UnaryOperator<String> selector = String::trim;
BinaryOperator<Integer> min = Math::min;
String foo = "xyz";
Integer integer = selector.andThen(lookup).apply(" " + foo);
}
}
@@ -0,0 +1,17 @@
// "Replace nested function call with andThen call" "true"
import java.util.Collections;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.UnaryOperator;
public class Main {
private void testFn() {
Function<String, Integer> lookup = Integer::parseInt;
UnaryOperator<String> selector = String::trim;
BinaryOperator<Integer> min = Math::min;
String foo = "xyz";
int res = Math.abs(min.a<caret>pply(-1,-2));
}
}
@@ -0,0 +1,17 @@
// "Replace nested function call with andThen call" "true"
import java.util.Collections;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.UnaryOperator;
public class Main {
private void testFn() {
Function<String, Integer> lookup = Integer::parseInt;
UnaryOperator<String> selector = String::trim;
BinaryOperator<Integer> min = Math::min;
String foo = "xyz";
boolean b = Collections.singleton(/* "xyz" here */ "xyz").contains(/*check*/sel<caret>ector.apply(/* foo here */ foo));
}
}
@@ -0,0 +1,12 @@
// "Replace nested function call with andThen call" "true"
import java.util.function.UnaryOperator;
public class Main {
private void testFn(boolean b) {
String foo = "xyz";
Integer f = Integer.parseInt(
(b ? (UnaryOperator<String>) String::trim : (UnaryOperator<String>) s -> s.substring(1)).apply(fo<caret>o));
}
}
@@ -0,0 +1,16 @@
// "Replace nested function call with andThen call" "true"
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.UnaryOperator;
public class Main {
private void testFn() {
Function<String, Integer> lookup = Integer::parseInt;
UnaryOperator<String> selector = String::trim;
BinaryOperator<Integer> min = Math::min;
String foo = "xyz";
Integer integer = lookup.apply(sele<caret>ctor.apply(" " + foo));
}
}
@@ -0,0 +1,28 @@
/*
* Copyright 2000-2016 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 com.intellij.codeInsight.intention;
import com.intellij.codeInsight.daemon.LightIntentionActionTestCase;
public class ComposeFunctionChainActionTest extends LightIntentionActionTestCase {
public void test() throws Exception { doAllTests(); }
@Override
protected String getBasePath() {
return "/codeInsight/daemonCodeAnalyzer/quickFix/composeFunctionChain";
}
}
@@ -111,6 +111,7 @@ public interface CommonClassNames {
@NonNls String JAVA_UTIL_STREAM_COLLECTORS = "java.util.stream.Collectors";
@NonNls String JAVA_UTIL_FUNCTION_PREDICATE = "java.util.function.Predicate";
@NonNls String JAVA_UTIL_FUNCTION_FUNCTION = "java.util.function.Function";
@NonNls String JAVA_UTIL_FUNCTION_BIFUNCTION = "java.util.function.BiFunction";
@NonNls String JAVA_LANG_INVOKE_MH_POLYMORPHIC = "java.lang.invoke.MethodHandle.PolymorphicSignature";
@@ -177,6 +177,8 @@ intention.merge.filter.family=Merge filters
intention.inline.map.inline.text=Inline ''{0}'' body into the next ''{1}'' call
intention.inline.map.merge.text=Merge ''{0}'' call and ''{1}'' call
intention.inline.map.family=Inline stream mapping method
intention.compose.function.text=Replace nested function call with andThen call
intention.compose.function.family=Replace nested function call with composition
intention.introduce.variable.text=Introduce local variable
intention.encapsulate.field.text=Encapsulate field
intention.implement.abstract.method.family=Implement Abstract Method
@@ -112,6 +112,9 @@ public class CommentTracker {
if(anchor instanceof PsiLambdaExpression && anchor != result) {
anchor = ((PsiLambdaExpression)anchor).getBody();
}
if(anchor instanceof PsiVariable && anchor.getParent() instanceof PsiDeclarationStatement) {
anchor = anchor.getParent();
}
if(anchor == null) anchor = result;
insertCommentsBefore(anchor);
return result;
@@ -0,0 +1,4 @@
Function<String, String> filter = String::trim;
Function<String, Integer> converter = Integer::parseInt;
int result = filter.andThen(converter).apply(" 123 ");
@@ -0,0 +1,4 @@
Function<String, String> filter = String::trim;
Function<String, Integer> converter = Integer::parseInt;
int result = converter.apply(<spot>filter.apply(" 123 ")</spot>);
@@ -0,0 +1,9 @@
<html>
<body>
This intention allows to compose <code>Function.apply</code> and <code>BiFunction.apply</code> call with outer call.
<!-- tooltip end -->
<p>
This allows to extract the composed function after that if necessary.
</p>
</body>
</html>
+4
View File
@@ -900,6 +900,10 @@
<className>com.intellij.codeInsight.intention.impl.InlineStreamMapAction</className>
<category>Java/Streams</category>
</intentionAction>
<intentionAction>
<className>com.intellij.codeInsight.intention.impl.ComposeFunctionChainAction</className>
<category>Java/Refactorings</category>
</intentionAction>
<intentionAction>
<className>com.intellij.codeInsight.intention.impl.InvertIfConditionAction</className>
<category>Java/Control Flow</category>