extract method object to emulate debugging for anonymous classes, lambdas, etc

This commit is contained in:
Anna Kozlova
2014-09-03 22:34:57 +04:00
parent a53fd51217
commit 64422b696d
9 changed files with 327 additions and 43 deletions
@@ -20,25 +20,18 @@
*/
package com.intellij.refactoring.extractMethod;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.psi.PsiModifier;
import com.intellij.refactoring.util.VariableData;
public abstract class AbstractExtractDialog extends DialogWrapper {
protected AbstractExtractDialog(Project project) {
super(project, true);
}
public abstract String getChosenMethodName();
public abstract VariableData[] getChosenParameters();
public interface AbstractExtractDialog {
String getChosenMethodName();
VariableData[] getChosenParameters();
@PsiModifier.ModifierConstant
public abstract String getVisibility();
String getVisibility();
boolean isMakeStatic();
boolean isChainedConstructor();
public abstract boolean isMakeStatic();
public abstract boolean isChainedConstructor();
void show();
boolean isOK();
}
@@ -21,6 +21,7 @@ import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.openapi.util.text.StringUtil;
@@ -59,7 +60,7 @@ import java.awt.event.*;
* @author Konstantin Bulenkov
*/
@SuppressWarnings("MethodMayBeStatic")
public class ExtractMethodDialog extends AbstractExtractDialog {
public class ExtractMethodDialog extends DialogWrapper implements AbstractExtractDialog {
public static final String EXTRACT_METHOD_DEFAULT_VISIBILITY = "extract.method.default.visibility";
private final Project myProject;
private final PsiType myReturnType;
@@ -96,7 +97,7 @@ public class ExtractMethodDialog extends AbstractExtractDialog {
String title,
String helpId,
final PsiElement[] elementsToExtract) {
super(project);
super(project, true);
myProject = project;
myTargetClass = targetClass;
myReturnType = returnType;
@@ -463,14 +463,14 @@ public class ExtractMethodProcessor implements MatchProvider {
protected void apply(final AbstractExtractDialog dialog) {
myMethodName = dialog.getChosenMethodName();
myVariableDatum = dialog.getChosenParameters();
myStatic |= dialog.isMakeStatic();
myStatic = isStatic() | dialog.isMakeStatic();
myIsChainedConstructor = dialog.isChainedConstructor();
myMethodVisibility = dialog.getVisibility();
}
protected AbstractExtractDialog createExtractMethodDialog(final boolean direct) {
return new ExtractMethodDialog(myProject, myTargetClass, myInputVariables, myReturnType, myTypeParameterList,
myThrownExceptions, myStatic, myCanBeStatic, myCanBeChainedConstructor,
return new ExtractMethodDialog(myProject, myTargetClass, myInputVariables, myReturnType, getTypeParameterList(),
getThrownExceptions(), isStatic(), isCanBeStatic(), myCanBeChainedConstructor,
suggestInitialMethodName(),
myRefactoringName, myHelpId, myElements) {
protected boolean areTypesDirected() {
@@ -620,7 +620,7 @@ public class ExtractMethodProcessor implements MatchProvider {
private void doExtract() throws IncorrectOperationException {
PsiMethod newMethod = generateEmptyMethod(myThrownExceptions, myStatic);
PsiMethod newMethod = generateEmptyMethod(getThrownExceptions(), isStatic());
myExpression = myInputVariables.replaceWrappedReferences(myElements, myExpression);
renameInputVariables();
@@ -991,6 +991,10 @@ public class ExtractMethodProcessor implements MatchProvider {
return myTargetClass;
}
public PsiType getReturnType() {
return myReturnType;
}
private PsiMethod generateEmptyMethod(PsiClassType[] exceptions, boolean isStatic) throws IncorrectOperationException {
PsiMethod newMethod;
if (myIsChainedConstructor) {
@@ -1001,8 +1005,8 @@ public class ExtractMethodProcessor implements MatchProvider {
PsiUtil.setModifierProperty(newMethod, PsiModifier.STATIC, isStatic);
}
PsiUtil.setModifierProperty(newMethod, myMethodVisibility, true);
if (myTypeParameterList != null) {
newMethod.getTypeParameterList().replace(myTypeParameterList);
if (getTypeParameterList() != null) {
newMethod.getTypeParameterList().replace(getTypeParameterList());
}
PsiCodeBlock body = newMethod.getBody();
LOG.assertTrue(body != null);
@@ -1400,4 +1404,28 @@ public class ExtractMethodProcessor implements MatchProvider {
public InputVariables getInputVariables() {
return myInputVariables;
}
public PsiTypeParameterList getTypeParameterList() {
return myTypeParameterList;
}
public PsiClassType[] getThrownExceptions() {
return myThrownExceptions;
}
public boolean isStatic() {
return myStatic;
}
public boolean isCanBeStatic() {
return myCanBeStatic;
}
public PsiElement[] getElements() {
return myElements;
}
public PsiVariable[] getOutputVariables() {
return myOutputVariables;
}
}
@@ -0,0 +1,144 @@
/*
* Copyright 2000-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 com.intellij.refactoring.extractMethodObject;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.refactoring.extractMethod.AbstractExtractDialog;
import com.intellij.refactoring.extractMethod.InputVariables;
import com.intellij.refactoring.util.VariableData;
import org.jetbrains.annotations.Nullable;
public class ExtractLightMethodObjectHandler {
private static final Logger LOG = Logger.getInstance("#" + ExtractLightMethodObjectHandler.class.getName());
public static class ExtractedData {
private String myGeneratedCallText;
private PsiClass myGeneratedInnerClass;
public ExtractedData(String generatedCallText, PsiClass generatedInnerClass) {
myGeneratedCallText = generatedCallText;
myGeneratedInnerClass = generatedInnerClass;
}
public String getGeneratedCallText() {
return myGeneratedCallText;
}
public PsiClass getGeneratedInnerClass() {
return myGeneratedInnerClass;
}
}
@Nullable
public static ExtractedData extractLightMethodObject(final Project project,
final Editor editor,
final PsiFile file,
final PsiElement[] elements,
final String methodName) {
if (elements == null || elements.length == 0) {
return null;
}
final PsiFile copy = PsiFileFactory.getInstance(project)
.createFileFromText(file.getName(), file.getFileType(), file.getText(), file.getModificationStamp(), true);
final PsiElement[] elementsCopy = new PsiElement[elements.length];
for (int i = 0; i < elements.length; i++) {
PsiElement element = elements[i];
final TextRange textRange = element.getTextRange();
elementsCopy[i] = CodeInsightUtil.findElementInRange(copy, textRange.getStartOffset(), textRange.getEndOffset(), element.getClass());
}
final Document document = PsiDocumentManager.getInstance(project).getDocument(copy);
LOG.assertTrue(document != null);
final int startOffset = elements[0].getTextRange().getStartOffset();
final int endOffset = elements[elements.length - 1].getTextRange().getEndOffset();
final RangeMarker callSiteMarker = document.createRangeMarker(startOffset, endOffset);
callSiteMarker.setGreedyToLeft(true);
callSiteMarker.setGreedyToRight(true);
try {
final ExtractMethodObjectProcessor extractMethodObjectProcessor = new ExtractMethodObjectProcessor(project, editor, elementsCopy, "") {
@Override
protected AbstractExtractDialog createExtractMethodObjectDialog(MyExtractMethodProcessor processor) {
return new LightExtractMethodObjectDialog(this, methodName);
}
};
extractMethodObjectProcessor.getExtractProcessor().setShowErrorDialogs(false);
ExtractMethodObjectHandler.extractMethodObject(project, editor, file, extractMethodObjectProcessor);
final String generatedCall = document.getText(new TextRange(callSiteMarker.getStartOffset(), callSiteMarker.getEndOffset()));
return new ExtractedData(generatedCall, extractMethodObjectProcessor.getInnerClass());
}
finally {
callSiteMarker.dispose();
}
}
private static class LightExtractMethodObjectDialog implements AbstractExtractDialog {
private final ExtractMethodObjectProcessor myProcessor;
private final String myMethodName;
public LightExtractMethodObjectDialog(ExtractMethodObjectProcessor processor, String methodName) {
myProcessor = processor;
myMethodName = methodName;
}
@Override
public String getChosenMethodName() {
return myMethodName;
}
@Override
public VariableData[] getChosenParameters() {
final InputVariables inputVariables = myProcessor.getExtractProcessor().getInputVariables();
return inputVariables.getInputVariables().toArray(new VariableData[inputVariables.getInputVariables().size()]);
}
@Override
public String getVisibility() {
return PsiModifier.PUBLIC;
}
@Override
public boolean isMakeStatic() {
return false;
}
@Override
public boolean isChainedConstructor() {
return false;
}
@Override
public void show() {}
@Override
public boolean isOK() {
return true;
}
}
}
@@ -19,6 +19,7 @@ import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.psi.*;
@@ -44,7 +45,7 @@ import java.awt.event.ActionListener;
import java.util.Enumeration;
public class ExtractMethodObjectDialog extends AbstractExtractDialog {
public class ExtractMethodObjectDialog extends DialogWrapper implements AbstractExtractDialog {
private final Project myProject;
private final PsiType myReturnType;
private final PsiTypeParameterList myTypeParameterList;
@@ -86,7 +87,7 @@ public class ExtractMethodObjectDialog extends AbstractExtractDialog {
public ExtractMethodObjectDialog(Project project, PsiClass targetClass, final InputVariables inputVariables, PsiType returnType,
PsiTypeParameterList typeParameterList, PsiType[] exceptions, boolean isStatic, boolean canBeStatic,
final PsiElement[] elementsToExtract, final boolean multipleExitPoints) {
super(project);
super(project, true);
myProject = project;
myTargetClass = targetClass;
myReturnType = returnType;
@@ -20,26 +20,29 @@
*/
package com.intellij.refactoring.extractMethodObject;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pass;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.extractMethod.AbstractExtractDialog;
import com.intellij.refactoring.extractMethod.ExtractMethodHandler;
import com.intellij.refactoring.extractMethod.InputVariables;
import com.intellij.refactoring.extractMethod.PrepareFailedException;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.VariableData;
import com.intellij.refactoring.util.duplicates.DuplicatesImpl;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
@@ -55,7 +58,10 @@ public class ExtractMethodObjectHandler implements RefactoringActionHandler {
});
}
private void invokeOnElements(@NotNull final Project project, @NotNull final Editor editor, @NotNull PsiFile file, @NotNull PsiElement[] elements) {
private static void invokeOnElements(@NotNull final Project project,
@NotNull final Editor editor,
@NotNull PsiFile file,
@NotNull PsiElement[] elements) {
if (elements.length == 0) {
String message = RefactoringBundle
.getCannotRefactorMessage(RefactoringBundle.message("selected.block.should.represent.a.set.of.statements.or.an.expression"));
@@ -63,7 +69,10 @@ public class ExtractMethodObjectHandler implements RefactoringActionHandler {
return;
}
final ExtractMethodObjectProcessor processor = new ExtractMethodObjectProcessor(project, editor, elements, "");
extractMethodObject(project, editor, file, new ExtractMethodObjectProcessor(project, editor, elements, ""));
}
static void extractMethodObject(Project project, Editor editor, PsiFile file, ExtractMethodObjectProcessor processor) {
final ExtractMethodObjectProcessor.MyExtractMethodProcessor extractProcessor = processor.getExtractProcessor();
try {
if (!extractProcessor.prepare()) return;
@@ -37,10 +37,13 @@ import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.controlFlow.ControlFlowUtil;
import com.intellij.psi.impl.source.PsiImmediateClassType;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.changeSignature.ChangeSignatureProcessor;
@@ -52,6 +55,7 @@ import com.intellij.refactoring.ui.MemberSelectionPanel;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.refactoring.util.classMembers.MemberInfo;
import com.intellij.refactoring.util.duplicates.Match;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewDescriptor;
import com.intellij.usageView.UsageViewUtil;
@@ -100,8 +104,12 @@ public class ExtractMethodObjectProcessor extends BaseRefactoringProcessor {
@NotNull
protected UsageInfo[] findUsages() {
final ArrayList<UsageInfo> result = new ArrayList<UsageInfo>();
final PsiClass containingClass = getMethod().getContainingClass();
final SearchScope scope = PsiUtilCore.getVirtualFile(containingClass) instanceof LightVirtualFile
? new LocalSearchScope(containingClass)
: GlobalSearchScope.projectScope(myProject);
PsiReference[] refs =
ReferencesSearch.search(getMethod(), GlobalSearchScope.projectScope(myProject), false).toArray(PsiReference.EMPTY_ARRAY);
ReferencesSearch.search(getMethod(), scope, false).toArray(PsiReference.EMPTY_ARRAY);
for (PsiReference ref : refs) {
final PsiElement element = ref.getElement();
if (element != null && element.isValid()) {
@@ -320,7 +328,7 @@ public class ExtractMethodObjectProcessor extends BaseRefactoringProcessor {
for (PsiElement declaredElement : declaredElements) {
if (declaredElement instanceof PsiVariable) {
for (PsiVariable variable : outputVariables) {
PsiLocalVariable var = (PsiLocalVariable)declaredElement;
PsiVariable var = (PsiVariable)declaredElement;
if (Comparing.strEqual(var.getName(), variable.getName())) {
final PsiExpression initializer = var.getInitializer();
if (initializer == null) {
@@ -400,8 +408,7 @@ public class ExtractMethodObjectProcessor extends BaseRefactoringProcessor {
private String getPureName(PsiVariable var) {
final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(myProject);
final VariableKind kind = var instanceof PsiLocalVariable ? VariableKind.LOCAL_VARIABLE : VariableKind.PARAMETER;
return styleManager.variableNameToPropertyName(var.getName(), kind);
return styleManager.variableNameToPropertyName(var.getName(), styleManager.getVariableKind(var));
}
public PsiExpression processMethodDeclaration( PsiExpressionList expressionList) throws IncorrectOperationException {
@@ -517,7 +524,7 @@ public class ExtractMethodObjectProcessor extends BaseRefactoringProcessor {
LOG.assertTrue(methodBody != null);
replacedMethodBody.replace(methodBody);
PsiUtil.setModifierProperty(newMethod, PsiModifier.STATIC, myInnerClass.hasModifierProperty(PsiModifier.STATIC) && notHasGeneratedFields());
myInnerMethod = (PsiMethod)myInnerClass.add(newMethod);
myInnerMethod = (PsiMethod)JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(myInnerClass.add(newMethod));
}
private boolean notHasGeneratedFields() {
@@ -624,6 +631,22 @@ public class ExtractMethodObjectProcessor extends BaseRefactoringProcessor {
return myExtractProcessor;
}
protected AbstractExtractDialog createExtractMethodObjectDialog(final MyExtractMethodProcessor processor) {
return new ExtractMethodObjectDialog(myProject, processor.getTargetClass(), processor.getInputVariables(), processor.getReturnType(),
processor.getTypeParameterList(),
processor.getThrownExceptions(), processor.isStatic(), processor.isCanBeStatic(),
processor.getElements(), myMultipleExitPoints){
@Override
protected boolean isUsedAfter(PsiVariable variable) {
return ArrayUtil.find(processor.getOutputVariables(), variable) != -1;
}
};
}
public PsiClass getInnerClass() {
return myInnerClass;
}
public class MyExtractMethodProcessor extends ExtractMethodProcessor {
public MyExtractMethodProcessor(Project project,
@@ -640,19 +663,13 @@ public class ExtractMethodObjectProcessor extends BaseRefactoringProcessor {
@Override
protected void apply(final AbstractExtractDialog dialog) {
super.apply(dialog);
myCreateInnerClass = ((ExtractMethodObjectDialog)dialog).createInnerClass();
myCreateInnerClass = !(dialog instanceof ExtractMethodObjectDialog) || ((ExtractMethodObjectDialog)dialog).createInnerClass();
myInnerClassName = myCreateInnerClass ? StringUtil.capitalize(dialog.getChosenMethodName()) : dialog.getChosenMethodName();
}
@Override
protected AbstractExtractDialog createExtractMethodDialog(final boolean direct) {
return new ExtractMethodObjectDialog(myProject, myTargetClass, myInputVariables, myReturnType, myTypeParameterList,
myThrownExceptions, myStatic, myCanBeStatic, myElements, myMultipleExitPoints){
@Override
protected boolean isUsedAfter(PsiVariable variable) {
return ArrayUtil.find(myOutputVariables, variable) != -1;
}
};
return createExtractMethodObjectDialog(this);
}
@Override
@@ -0,0 +1,7 @@
class Sample {
void foo() {
<selection>int i = 0;
int j = 0;</selection>
System.out.println(i + j);
}
}
@@ -0,0 +1,84 @@
/*
* Copyright 2000-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.
*/
/*
* User: anna
* Date: 06-May-2008
*/
package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.extractMethodObject.ExtractLightMethodObjectHandler;
import com.intellij.testFramework.IdeaTestUtil;
import org.jetbrains.annotations.NotNull;
public class ExtractMethodObject4DebuggerTest extends LightRefactoringTestCase {
@NotNull
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
}
private void doTest(String expectedCallSite, String expectedClass) throws Exception {
final String testName = getTestName(false);
configureByFile("/refactoring/extractMethodObject4Debugger/" + testName + ".java");
int startOffset = getEditor().getSelectionModel().getSelectionStart();
int endOffset = getEditor().getSelectionModel().getSelectionEnd();
PsiElement[] elements = CodeInsightUtil.findStatementsInRange(getFile(), startOffset, endOffset);
assertTrue(elements.length > 0);
final ExtractLightMethodObjectHandler.ExtractedData extractedData =
ExtractLightMethodObjectHandler.extractLightMethodObject(getProject(), getEditor(), getFile(), elements, "test");
assertNotNull(extractedData);
assertEquals(expectedCallSite, extractedData.getGeneratedCallText());
final PsiClass innerClass = extractedData.getGeneratedInnerClass();
assertEquals(expectedClass, innerClass.getText());
}
public void testSimpleGeneration() throws Exception {
doTest(" Test test = new Test().invoke();\n" +
" int i = test.getI();\n" +
" int j = test.getJ();",
"public class Test {\n" +
" private int i;\n" +
" private int j;\n" +
"\n" +
" public int getI() {\n" +
" return i;\n" +
" }\n" +
"\n" +
" public int getJ() {\n" +
" return j;\n" +
" }\n" +
"\n" +
" public Test invoke() {\n" +
" i = 0;\n" +
" j = 0;\n" +
" return this;\n" +
" }\n" +
" }");
}
@Override
protected Sdk getProjectJDK() {
return IdeaTestUtil.getMockJdk18();
}
}