1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-06-07 09:46:02 +02:00

Use shared AST in Extract Constant refactoring.

This commit is contained in:
Sergey Prigogin 2012-02-16 21:16:49 -08:00
parent 4d225aac73
commit c49a852b88
25 changed files with 399 additions and 460 deletions

View file

@ -26,9 +26,9 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
* Tests for Extract Constant refactoring. * Tests for Extract Constant refactoring.
*/ */
public class ExtractConstantRefactoringTest extends RefactoringTestBase { public class ExtractConstantRefactoringTest extends RefactoringTestBase {
private ExtractConstantInfo refactoringInfo;
private String extractedConstantName = "EXTRACTED"; private String extractedConstantName = "EXTRACTED";
private VisibilityEnum visibility = VisibilityEnum.v_private; private VisibilityEnum visibility = VisibilityEnum.v_private;
private ExtractConstantRefactoring refactoring;
public ExtractConstantRefactoringTest() { public ExtractConstantRefactoringTest() {
super(); super();
@ -44,15 +44,16 @@ public class ExtractConstantRefactoringTest extends RefactoringTestBase {
@Override @Override
protected Refactoring createRefactoring() { protected Refactoring createRefactoring() {
refactoringInfo = new ExtractConstantInfo(); refactoring = new ExtractConstantRefactoring(getSelectedTranslationUnit(), getSelection(),
return new ExtractConstantRefactoring(getSelectedFile(), getSelection(), refactoringInfo,
getCProject()); getCProject());
return refactoring;
} }
@Override @Override
protected void simulateUserInput() { protected void simulateUserInput() {
refactoringInfo.setName(extractedConstantName); ExtractConstantInfo info = refactoring.getRefactoringInfo();
refactoringInfo.setVisibility(visibility); info.setName(extractedConstantName);
info.setVisibility(visibility);
} }
//A.h //A.h

View file

@ -39,6 +39,10 @@ public class MethodContext {
private IASTName declarationName; private IASTName declarationName;
private ICPPASTQualifiedName qname; private ICPPASTQualifiedName qname;
public MethodContext() {
type = ContextType.NONE;
}
public ContextType getType() { public ContextType getType() {
return type; return type;
} }

View file

@ -15,14 +15,11 @@ package org.eclipse.cdt.internal.ui.refactoring;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
/** /**
* Associate a name with a visibility and holds a list of used names. * Contains the name for a new variable and holds a list of used names.
*/ */
public class NameAndVisibilityInformation { public class VariableNameInformation {
private String name = ""; //$NON-NLS-1$ private String name = ""; //$NON-NLS-1$
private VisibilityEnum visibility = VisibilityEnum.v_public;
private final ArrayList<String> usedNames = new ArrayList<String>(); private final ArrayList<String> usedNames = new ArrayList<String>();
public String getName() { public String getName() {
@ -33,15 +30,7 @@ public class NameAndVisibilityInformation {
this.name = name; this.name = name;
} }
public VisibilityEnum getVisibility() { public List<String> getUsedNames() {
return visibility;
}
public void setVisibility(VisibilityEnum visibility) {
this.visibility = visibility;
}
public List<String> getUsedNames(){
return usedNames; return usedNames;
} }
@ -49,7 +38,7 @@ public class NameAndVisibilityInformation {
usedNames.add(name); usedNames.add(name);
} }
public void addNamesToUsedNames(ArrayList<String> names) { public void addNamesToUsedNames(List<String> names) {
usedNames.addAll(names); usedNames.addAll(names);
} }
} }

View file

@ -1,100 +0,0 @@
/*******************************************************************************
* Copyright (c) 2008 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.dialogs;
import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.cdt.internal.ui.refactoring.NameAndVisibilityInformation;
import org.eclipse.cdt.internal.ui.refactoring.utils.IdentifierHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.IdentifierResult;
import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
/**
* Holds a NameAndVisibilityComposite and deals with the extract refactoring
* specific implementation and propagates the inputs made in the wizard ui back
* to the refactoring via the NameNVisibilityInformation object.
*
* @author Emanuel Graf
*/
public abstract class ExtractInputPage extends UserInputWizardPage {
protected NameAndVisibilityComposite control;
protected NameAndVisibilityInformation info;
protected String label = Messages.ExtractInputPage_ReplaceInSubclass;
protected String errorLabel = Messages.ExtractInputPage_EnterName;
public ExtractInputPage(String name, NameAndVisibilityInformation info) {
super(name);
this.info = info;
}
@Override
public void createControl(Composite parent) {
control = new NameAndVisibilityComposite(parent, label, info.getName());
setTitle(getName());
setPageComplete(false);
control.getConstantNameText().addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
info.setName(control.getConstantNameText().getText());
checkName();
}
});
for (Control buttons : control.getVisibiltyGroup().getChildren()) {
buttons.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
String text = ((Button)e.getSource()).getText();
visibilityChange(text);
}
});
}
checkName();
setControl(control);
}
protected void checkName() {
String methodName = control.getConstantNameText().getText();
IdentifierResult result = IdentifierHelper.checkIdentifierName(methodName);
if(result.isCorrect()){
setErrorMessage(null);
setPageComplete(true);
verifyName(methodName);
}
else{
setErrorMessage(NLS.bind(Messages.ExtractInputPage_CheckName, result.getMessage()));
setPageComplete(false);
}
}
abstract protected void verifyName(String name);
protected void visibilityChange(String visibilityText) {
info.setVisibility(VisibilityEnum.getEnumForStringRepresentation(visibilityText));
}
}

View file

@ -22,10 +22,8 @@ import org.eclipse.swt.widgets.Text;
* A text field with an associated label, displayed side-by-side. * A text field with an associated label, displayed side-by-side.
* *
* @author Mirko Stocker * @author Mirko Stocker
*
*/ */
public class LabeledTextField extends Composite { public class LabeledTextField extends Composite {
private final Text textField; private final Text textField;
public LabeledTextField(Composite parent, String labelName, String textContent) { public LabeledTextField(Composite parent, String labelName, String textContent) {
@ -40,7 +38,7 @@ public class LabeledTextField extends Composite {
label.setText(labelName); label.setText(labelName);
label.setLayoutData(new GridData()); label.setLayoutData(new GridData());
textField = new Text(this, SWT.BORDER |SWT.SINGLE); textField = new Text(this, SWT.BORDER | SWT.SINGLE);
textField.setText(textContent); textField.setText(textContent);
textField.selectAll(); textField.selectAll();
GridData textData = new GridData(GridData.FILL_HORIZONTAL); GridData textData = new GridData(GridData.FILL_HORIZONTAL);

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2008 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others. * Rapperswil, University of applied sciences and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -7,28 +7,34 @@
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* Contributors: * Contributors:
* Institute for Software (IFS)- initial API and implementation * Institute for Software (IFS) - initial API and implementation
* Sergey Prigogin (Google)
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.extractconstant; package org.eclipse.cdt.internal.ui.refactoring.extractconstant;
import org.eclipse.cdt.internal.ui.refactoring.MethodContext; import org.eclipse.cdt.internal.ui.refactoring.MethodContext;
import org.eclipse.cdt.internal.ui.refactoring.NameAndVisibilityInformation; import org.eclipse.cdt.internal.ui.refactoring.VariableNameInformation;
import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
/** /**
* @author Emanuel Graf IFS * @author Emanuel Graf IFS
*
*/ */
public class ExtractConstantInfo extends NameAndVisibilityInformation{ public class ExtractConstantInfo extends VariableNameInformation {
private VisibilityEnum visibility = VisibilityEnum.v_private;
private MethodContext methodContext;
private MethodContext mContext; public VisibilityEnum getVisibility() {
return visibility;
public MethodContext getMContext() {
return mContext;
}
public void setMContext(MethodContext context) {
mContext = context;
} }
public void setVisibility(VisibilityEnum visibility) {
this.visibility = visibility;
}
public MethodContext getMethodContext() {
return methodContext;
}
public void setMethodContext(MethodContext context) {
methodContext = context;
}
} }

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others * Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -17,13 +17,9 @@ import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.preferences.IPreferencesService; import org.eclipse.core.runtime.preferences.IPreferencesService;
@ -31,6 +27,7 @@ import org.eclipse.jface.text.Region;
import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.text.edits.TextEditGroup; import org.eclipse.text.edits.TextEditGroup;
import org.eclipse.cdt.core.dom.ast.ASTNodeFactoryFactory; import org.eclipse.cdt.core.dom.ast.ASTNodeFactoryFactory;
@ -40,11 +37,13 @@ import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTDeclarator; import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTEqualsInitializer; import org.eclipse.cdt.core.dom.ast.IASTEqualsInitializer;
import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTExpression;
import org.eclipse.cdt.core.dom.ast.IASTFileLocation;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition; import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition;
import org.eclipse.cdt.core.dom.ast.IASTLiteralExpression; import org.eclipse.cdt.core.dom.ast.IASTLiteralExpression;
import org.eclipse.cdt.core.dom.ast.IASTMacroExpansionLocation; import org.eclipse.cdt.core.dom.ast.IASTMacroExpansionLocation;
import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.IASTUnaryExpression; import org.eclipse.cdt.core.dom.ast.IASTUnaryExpression;
import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.INodeFactory; import org.eclipse.cdt.core.dom.ast.INodeFactory;
@ -54,7 +53,9 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceDefinition;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPNodeFactory; import org.eclipse.cdt.core.dom.ast.cpp.ICPPNodeFactory;
import org.eclipse.cdt.core.dom.rewrite.ASTRewrite; import org.eclipse.cdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.cdt.core.dom.rewrite.DeclarationGenerator; import org.eclipse.cdt.core.dom.rewrite.DeclarationGenerator;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.PreferenceConstants; import org.eclipse.cdt.ui.PreferenceConstants;
@ -65,87 +66,78 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTName;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclaration; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclaration;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPMethod; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPMethod;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
import org.eclipse.cdt.internal.ui.refactoring.ClassMemberInserter; import org.eclipse.cdt.internal.ui.refactoring.ClassMemberInserter;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescription;
import org.eclipse.cdt.internal.ui.refactoring.MethodContext; import org.eclipse.cdt.internal.ui.refactoring.MethodContext;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.utils.NodeHelper; import org.eclipse.cdt.internal.ui.refactoring.utils.NodeHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.TranslationUnitHelper; import org.eclipse.cdt.internal.ui.refactoring.utils.TranslationUnitHelper;
import org.eclipse.cdt.internal.ui.util.NameComposer; import org.eclipse.cdt.internal.ui.util.NameComposer;
/** /**
* The central class of the Extract Constant Refactoring. Does all the work like checking pre- and * The main class of the Extract Constant refactoring.
* postconditions and collecting/creating the modifications to the AST.
* *
* @author Mirko Stocker * @author Mirko Stocker
*/ */
public class ExtractConstantRefactoring extends CRefactoring { public class ExtractConstantRefactoring extends CRefactoring2 {
public static final String ID = "org.eclipse.cdt.ui.refactoring.extractconstant.ExtractConstantRefactoring"; //$NON-NLS-1$ public static final String ID =
"org.eclipse.cdt.ui.refactoring.extractconstant.ExtractConstantRefactoring"; //$NON-NLS-1$
private IASTLiteralExpression target = null; private IASTLiteralExpression target;
private final ArrayList<IASTExpression> literalsToReplace = new ArrayList<IASTExpression>();
private final ExtractConstantInfo info; private final ExtractConstantInfo info;
private final ArrayList<IASTExpression> literalsToReplace = new ArrayList<IASTExpression>();
public ExtractConstantRefactoring(ICElement element, ISelection selection, ICProject project) {
public ExtractConstantRefactoring(IFile file, ISelection selection, ExtractConstantInfo info, ICProject proj) { super(element, selection, project);
super(file,selection, null, proj); this.info = new ExtractConstantInfo();
this.info = info;
this.project = proj;
name = Messages.ExtractConstantRefactoring_ExtractConst; name = Messages.ExtractConstantRefactoring_ExtractConst;
} }
@Override @Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
SubMonitor sm = SubMonitor.convert(pm, 9); SubMonitor sm = SubMonitor.convert(pm, 10);
try {
lockIndex(); RefactoringStatus status = super.checkInitialConditions(sm.newChild(7));
try {
RefactoringStatus status = super.checkInitialConditions(sm.newChild(6));
if (status.hasError()) { if (status.hasError()) {
return status; return status;
} }
Collection<IASTLiteralExpression> literalExpressionCollection = findAllLiterals(); Collection<IASTLiteralExpression> literalExpressionCollection = findAllLiterals(sm.newChild(1));
if (literalExpressionCollection.isEmpty()) { if (literalExpressionCollection.isEmpty()) {
initStatus.addFatalError(Messages.ExtractConstantRefactoring_LiteralMustBeSelected); initStatus.addFatalError(Messages.ExtractConstantRefactoring_LiteralMustBeSelected);
return initStatus; return initStatus;
} }
sm.worked(1);
if (isProgressMonitorCanceld(sm, initStatus)) return initStatus;
boolean oneMarked = region != null && isOneMarked(literalExpressionCollection, region); if (isProgressMonitorCanceld(sm, initStatus))
return initStatus;
boolean oneMarked =
selectedRegion != null && isOneMarked(literalExpressionCollection, selectedRegion);
if (!oneMarked) { if (!oneMarked) {
//No or more than one marked // None or more than one literal selected
if (target == null) { if (target == null) {
//No Selection found; // No l found;
initStatus.addFatalError(Messages.ExtractConstantRefactoring_NoLiteralSelected); initStatus.addFatalError(Messages.ExtractConstantRefactoring_NoLiteralSelected);
} else { } else {
//To many selection found // To many selection found
initStatus.addFatalError(Messages.ExtractConstantRefactoring_TooManyLiteralSelected); initStatus.addFatalError(Messages.ExtractConstantRefactoring_TooManyLiteralSelected);
} }
return initStatus; return initStatus;
} }
sm.worked(1); sm.worked(1);
if (isProgressMonitorCanceld(sm, initStatus)) return initStatus; if (isProgressMonitorCanceld(sm, initStatus))
return initStatus;
findAllNodesForReplacement(literalExpressionCollection); findAllNodesForReplacement(literalExpressionCollection);
info.addNamesToUsedNames(findAllDeclaredNames()); info.addNamesToUsedNames(findAllDeclaredNames());
if (info.getName().length() == 0) { if (info.getName().isEmpty()) {
info.setName(getDefaultName(target)); info.setName(getDefaultName(target));
} }
info.setMContext(NodeHelper.findMethodContext(target, getIndex())); info.setMethodContext(NodeHelper.findMethodContext(target, refactoringContext, sm.newChild(1)));
sm.done(); sm.done();
}
finally {
unlockIndex();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return initStatus; return initStatus;
} }
@ -244,15 +236,16 @@ public class ExtractConstantRefactoring extends CRefactoring {
} }
} }
private boolean isOneMarked(Collection<IASTLiteralExpression> literalExpressionCollection, Region textSelection) { private boolean isOneMarked(Collection<IASTLiteralExpression> selectedNodes,
Region textSelection) {
boolean oneMarked = false; boolean oneMarked = false;
for (IASTLiteralExpression expression : literalExpressionCollection) { for (IASTLiteralExpression expression : selectedNodes) {
boolean isInSameFileSelection = SelectionHelper.isInSameFileSelection(textSelection, expression, file); if (expression.isPartOfTranslationUnitFile() &&
if (isInSameFileSelection) { isExpressionInSelection(expression, textSelection)) {
if (target == null) { if (target == null) {
target = expression; target = expression;
oneMarked = true; oneMarked = true;
} else { } else if (!isTargetChild(expression)) {
oneMarked = false; oneMarked = false;
} }
} }
@ -260,18 +253,43 @@ public class ExtractConstantRefactoring extends CRefactoring {
return oneMarked; return oneMarked;
} }
private Collection<IASTLiteralExpression> findAllLiterals() { private static boolean isExpressionInSelection(IASTExpression expression, Region selection) {
IASTFileLocation location = expression.getFileLocation();
int expressionStart = location.getNodeOffset();
int expressionEnd = expressionStart + location.getNodeLength();
int selectionStart = selection.getOffset();
int selectionEnd = selectionStart + selection.getLength();
return expressionStart >= selectionStart && expressionEnd <= selectionEnd;
}
private boolean isTargetChild(IASTExpression child) {
if (target == null) {
return false;
}
IASTNode node = child;
while (node != null) {
if (node.getParent() == target)
return true;
node = node.getParent();
}
return false;
}
private Collection<IASTLiteralExpression> findAllLiterals(IProgressMonitor pm)
throws OperationCanceledException, CoreException {
final Collection<IASTLiteralExpression> result = new ArrayList<IASTLiteralExpression>(); final Collection<IASTLiteralExpression> result = new ArrayList<IASTLiteralExpression>();
IASTTranslationUnit ast = getAST(tu, pm);
ast.accept(new ASTVisitor() { ast.accept(new ASTVisitor() {
{ {
shouldVisitExpressions = true; shouldVisitExpressions = true;
} }
@Override @Override
public int visit(IASTExpression expression) { public int visit(IASTExpression expression) {
if (expression instanceof IASTLiteralExpression) { if (expression instanceof IASTLiteralExpression) {
if (!(expression.getNodeLocations().length == 1 if (!(expression.getNodeLocations().length == 1 &&
&& expression.getNodeLocations()[0] instanceof IASTMacroExpansionLocation)) { expression.getNodeLocations()[0] instanceof IASTMacroExpansionLocation)) {
IASTLiteralExpression literal = (IASTLiteralExpression) expression; IASTLiteralExpression literal = (IASTLiteralExpression) expression;
result.add(literal); result.add(literal);
} }
@ -283,25 +301,33 @@ public class ExtractConstantRefactoring extends CRefactoring {
return result; return result;
} }
@Override
protected RefactoringStatus checkFinalConditions(IProgressMonitor subProgressMonitor,
CheckConditionsContext checkContext) throws CoreException, OperationCanceledException {
return new RefactoringStatus();
}
@Override @Override
protected void collectModifications(IProgressMonitor pm, ModificationCollector collector) protected void collectModifications(IProgressMonitor pm, ModificationCollector collector)
throws CoreException, OperationCanceledException{ throws CoreException, OperationCanceledException{
try { SubMonitor progress = SubMonitor.convert(pm, 10);
lockIndex(); MethodContext context = info.getMethodContext();
try {
MethodContext context = info.getMContext();
Collection<IASTExpression> locLiteralsToReplace = new ArrayList<IASTExpression>(); Collection<IASTExpression> locLiteralsToReplace = new ArrayList<IASTExpression>();
IASTTranslationUnit ast = getAST(tu, progress.newChild(9));
if (context.getType() == MethodContext.ContextType.METHOD) { if (context.getType() == MethodContext.ContextType.METHOD) {
SubMonitor loopProgress = progress.newChild(1).setWorkRemaining(literalsToReplace.size());
for (IASTExpression expression : literalsToReplace) { for (IASTExpression expression : literalsToReplace) {
MethodContext exprContext = NodeHelper.findMethodContext(expression, getIndex()); MethodContext exprContext =
NodeHelper.findMethodContext(expression, refactoringContext, loopProgress.newChild(1));
if (exprContext.getType() == MethodContext.ContextType.METHOD) { if (exprContext.getType() == MethodContext.ContextType.METHOD) {
if (context.getMethodQName() != null) { if (context.getMethodQName() != null) {
if (MethodContext.isSameClass(exprContext.getMethodQName(), context.getMethodQName())) { if (MethodContext.isSameClass(exprContext.getMethodQName(), context.getMethodQName())) {
locLiteralsToReplace.add(expression); locLiteralsToReplace.add(expression);
} }
} else { } else {
if (MethodContext.isSameClass(exprContext.getMethodDeclarationName(), context.getMethodDeclarationName())) { if (MethodContext.isSameClass(exprContext.getMethodDeclarationName(),
context.getMethodDeclarationName())) {
locLiteralsToReplace.add(expression); locLiteralsToReplace.add(expression);
} }
} }
@ -309,49 +335,45 @@ public class ExtractConstantRefactoring extends CRefactoring {
} }
} else { } else {
for (IASTExpression expression : literalsToReplace) { for (IASTExpression expression : literalsToReplace) {
IPath path = new Path(expression.getContainingFilename()); ITranslationUnit expressionTu = expression.getTranslationUnit().getOriginatingTranslationUnit();
IFile expressionFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path); if (expressionTu.getResource() != null) {
//expressionFile may be null if the file is NOT in the workspace
if (expressionFile != null && expressionFile.equals(file)) {
locLiteralsToReplace.add(expression); locLiteralsToReplace.add(expression);
} }
} }
} }
// Create all Changes for literals // Create all changes for literals
String constName = info.getName(); String constName = info.getName();
createLiteralToConstantChanges(constName, locLiteralsToReplace, collector); createLiteralToConstantChanges(constName, locLiteralsToReplace, collector);
if (context.getType() == MethodContext.ContextType.METHOD) { if (context.getType() == MethodContext.ContextType.METHOD) {
ICPPASTCompositeTypeSpecifier classDefinition = (ICPPASTCompositeTypeSpecifier) context.getMethodDeclaration().getParent(); ICPPASTCompositeTypeSpecifier classDefinition =
ClassMemberInserter.createChange(classDefinition, info.getVisibility(), getConstNodesClass(constName), true, collector); (ICPPASTCompositeTypeSpecifier) context.getMethodDeclaration().getParent();
ClassMemberInserter.createChange(classDefinition, info.getVisibility(),
getConstNodesClass(constName), true, collector);
} else { } else {
IASTDeclaration nodes = getConstNodesGlobal(constName); IASTDeclaration nodes = getConstNodesGlobal(constName, ast.getASTNodeFactory());
ASTRewrite rewriter = collector.rewriterForTranslationUnit(ast); ASTRewrite rewriter = collector.rewriterForTranslationUnit(ast);
rewriter.insertBefore(ast, TranslationUnitHelper.getFirstNode(ast), nodes, new TextEditGroup(Messages.ExtractConstantRefactoring_CreateConstant)); rewriter.insertBefore(ast, TranslationUnitHelper.getFirstNode(ast), nodes,
} new TextEditGroup(Messages.ExtractConstantRefactoring_CreateConstant));
} finally {
unlockIndex();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} }
} }
@Override @Override
protected RefactoringDescriptor getRefactoringDescriptor() { protected RefactoringDescriptor getRefactoringDescriptor() {
Map<String, String> arguments = getArgumentMap(); Map<String, String> arguments = getArgumentMap();
RefactoringDescriptor desc = new ExtractConstantRefactoringDescription(project.getProject().getName(), RefactoringDescriptor desc = new ExtractConstantRefactoringDescriptor(project.getProject().getName(),
"Extract Constant Refactoring", "Create constant for " + target.getRawSignature(), arguments); //$NON-NLS-1$//$NON-NLS-2$ "Extract Constant Refactoring", "Create constant for " + target.getRawSignature(), //$NON-NLS-1$ //$NON-NLS-2$
arguments);
return desc; return desc;
} }
private Map<String, String> getArgumentMap() { private Map<String, String> getArgumentMap() {
Map<String, String> arguments = new HashMap<String, String>(); Map<String, String> arguments = new HashMap<String, String>();
arguments.put(CRefactoringDescription.FILE_NAME, file.getLocationURI().toString()); arguments.put(CRefactoringDescriptor.FILE_NAME, tu.getLocationURI().toString());
arguments.put(CRefactoringDescription.SELECTION, region.getOffset() + "," + region.getLength()); //$NON-NLS-1$ arguments.put(CRefactoringDescriptor.SELECTION, selectedRegion.getOffset() + "," + selectedRegion.getLength()); //$NON-NLS-1$
arguments.put(ExtractConstantRefactoringDescription.NAME, info.getName()); arguments.put(ExtractConstantRefactoringDescriptor.NAME, info.getName());
arguments.put(ExtractConstantRefactoringDescription.VISIBILITY, info.getVisibility().toString()); arguments.put(ExtractConstantRefactoringDescriptor.VISIBILITY, info.getVisibility().toString());
return arguments; return arguments;
} }
@ -359,8 +381,10 @@ public class ExtractConstantRefactoring extends CRefactoring {
Iterable<? extends IASTExpression> literals, ModificationCollector collector) { Iterable<? extends IASTExpression> literals, ModificationCollector collector) {
for (IASTExpression each : literals) { for (IASTExpression each : literals) {
ASTRewrite rewrite = collector.rewriterForTranslationUnit(each.getTranslationUnit()); ASTRewrite rewrite = collector.rewriterForTranslationUnit(each.getTranslationUnit());
CPPASTIdExpression idExpression = new CPPASTIdExpression(new CPPASTName(constName.toCharArray())); CPPASTIdExpression idExpression =
rewrite.replace(each, idExpression, new TextEditGroup(Messages.ExtractConstantRefactoring_ReplaceLiteral)); new CPPASTIdExpression(new CPPASTName(constName.toCharArray()));
rewrite.replace(each, idExpression,
new TextEditGroup(Messages.ExtractConstantRefactoring_ReplaceLiteral));
} }
} }
@ -383,7 +407,8 @@ public class ExtractConstantRefactoring extends CRefactoring {
IASTUnaryExpression unary = (IASTUnaryExpression) target.getParent(); IASTUnaryExpression unary = (IASTUnaryExpression) target.getParent();
init.setInitializerClause(unary); init.setInitializerClause(unary);
} else { } else {
CPPASTLiteralExpression expression = new CPPASTLiteralExpression(target.getKind(), target.getValue()); CPPASTLiteralExpression expression =
new CPPASTLiteralExpression(target.getKind(), target.getValue());
init.setInitializerClause(expression); init.setInitializerClause(expression);
} }
declarator.setInitializer(init); declarator.setInitializer(init);
@ -392,12 +417,12 @@ public class ExtractConstantRefactoring extends CRefactoring {
return simple; return simple;
} }
private IASTDeclaration getConstNodesGlobal(String newName) { private IASTDeclaration getConstNodesGlobal(String newName, INodeFactory nodeFactory) {
IASTSimpleDeclaration simple = getConstNodes(newName); IASTSimpleDeclaration simple = getConstNodes(newName);
INodeFactory factory= ast.getASTNodeFactory(); if (nodeFactory instanceof ICPPNodeFactory) {
if (factory instanceof ICPPNodeFactory) { ICPPASTNamespaceDefinition namespace =
ICPPASTNamespaceDefinition namespace = ((ICPPNodeFactory) factory).newNamespaceDefinition(new CPPASTName()); ((ICPPNodeFactory) nodeFactory).newNamespaceDefinition(new CPPASTName());
namespace.addDeclaration(simple); namespace.addDeclaration(simple);
return namespace; return namespace;
} }
@ -411,4 +436,8 @@ public class ExtractConstantRefactoring extends CRefactoring {
simple.getDeclSpecifier().setStorageClass(IASTDeclSpecifier.sc_static); simple.getDeclSpecifier().setStorageClass(IASTDeclSpecifier.sc_static);
return simple; return simple;
} }
public ExtractConstantInfo getRefactoringInfo() {
return info;
}
} }

View file

@ -28,7 +28,7 @@ public class ExtractConstantRefactoringContribution extends CRefactoringContribu
String description, String comment, Map arguments, int flags) String description, String comment, Map arguments, int flags)
throws IllegalArgumentException { throws IllegalArgumentException {
if (id.equals(ExtractConstantRefactoring.ID)) { if (id.equals(ExtractConstantRefactoring.ID)) {
return new ExtractConstantRefactoringDescription(project, description, comment, arguments); return new ExtractConstantRefactoringDescriptor(project, description, comment, arguments);
} else { } else {
return null; return null;
} }

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2009 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2009, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others. * Rapperswil, University of applied sciences and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -8,53 +8,46 @@
* *
* Contributors: * Contributors:
* Institute for Software (IFS)- initial API and implementation * Institute for Software (IFS)- initial API and implementation
* Sergey Prigogin (Google)
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.extractconstant; package org.eclipse.cdt.internal.ui.refactoring.extractconstant;
import java.util.Map; import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescription; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum; import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
/** /**
* @author Emanuel Graf IFS * @author Emanuel Graf IFS
*
*/ */
public class ExtractConstantRefactoringDescription extends public class ExtractConstantRefactoringDescriptor extends CRefactoringDescriptor {
CRefactoringDescription {
protected static final String NAME = "name"; //$NON-NLS-1$ protected static final String NAME = "name"; //$NON-NLS-1$
protected static final String VISIBILITY = "visibility"; //$NON-NLS-1$ protected static final String VISIBILITY = "visibility"; //$NON-NLS-1$
protected ExtractConstantRefactoringDescription(String project, protected ExtractConstantRefactoringDescriptor(String project,
String description, String comment, Map<String, String> arguments) { String description, String comment, Map<String, String> arguments) {
super(ExtractConstantRefactoring.ID, project, description, comment, RefactoringDescriptor.MULTI_CHANGE, arguments); super(ExtractConstantRefactoring.ID, project, description, comment,
RefactoringDescriptor.MULTI_CHANGE, arguments);
} }
@Override @Override
public Refactoring createRefactoring(RefactoringStatus status) public CRefactoring2 createRefactoring(RefactoringStatus status)
throws CoreException { throws CoreException {
IFile file; ISelection selection = getSelection();
ExtractConstantInfo info = new ExtractConstantInfo(); ICProject project = getCProject();
ICProject proj; ExtractConstantRefactoring refactoring =
new ExtractConstantRefactoring(getTranslationUnit(), selection, project);
ExtractConstantInfo info = refactoring.getRefactoringInfo();
info.setName(arguments.get(NAME)); info.setName(arguments.get(NAME));
info.setVisibility(VisibilityEnum.getEnumForStringRepresentation(arguments.get(VISIBILITY))); info.setVisibility(VisibilityEnum.getEnumForStringRepresentation(arguments.get(VISIBILITY)));
return refactoring;
proj = getCProject();
file = getFile();
ISelection selection = getSelection();
return new ExtractConstantRefactoring(file, selection, info, proj);
} }
} }

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2008, 2009 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others * Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -8,40 +8,34 @@
* *
* Contributors: * Contributors:
* Institute for Software - initial API and implementation * Institute for Software - initial API and implementation
* Sergey Prigogin (Google)
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.extractconstant; package org.eclipse.cdt.internal.ui.refactoring.extractconstant;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.window.IShellProvider; import org.eclipse.jface.window.IShellProvider;
import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring; import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner2;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner; import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper;
/** /**
* @author Emanuel Graf * @author Emanuel Graf
*/ */
public class ExtractConstantRefactoringRunner extends RefactoringRunner { public class ExtractConstantRefactoringRunner extends RefactoringRunner2 {
public ExtractConstantRefactoringRunner(IFile file, ISelection selection, public ExtractConstantRefactoringRunner(ICElement element, ISelection selection,
IShellProvider shellProvider, ICProject cProject) { IShellProvider shellProvider, ICProject cProject) {
super(file, selection, null, shellProvider, cProject); super(element, selection, shellProvider, cProject);
} }
@Override @Override
public void run() { public void run() {
ExtractConstantInfo info = new ExtractConstantInfo(); ExtractConstantRefactoring refactoring =
CRefactoring refactoring = new ExtractConstantRefactoring(file,selection,info, project); new ExtractConstantRefactoring(element, selection, project);
ExtractConstantRefactoringWizard wizard = new ExtractConstantRefactoringWizard(refactoring, info); ExtractConstantWizard wizard = new ExtractConstantWizard(refactoring);
RefactoringWizardOpenOperation operator = new RefactoringWizardOpenOperation(wizard); run(wizard, refactoring, RefactoringSaveHelper.SAVE_REFACTORING);
try {
operator.run(shellProvider.getShell(), refactoring.getName());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} }
} }

View file

@ -1,39 +0,0 @@
/*******************************************************************************
* Copyright (c) 2008 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.extractconstant;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
import org.eclipse.cdt.internal.ui.refactoring.MethodContext.ContextType;
import org.eclipse.cdt.internal.ui.refactoring.dialogs.ExtractInputPage;
/**
* The wizard page for Extract Constant Refactoring, creates the UI page.
*/
public class ExtractConstantRefactoringWizard extends RefactoringWizard {
private ExtractInputPage page;
private final ExtractConstantInfo info;
public ExtractConstantRefactoringWizard(Refactoring refactoring, ExtractConstantInfo info) {
super(refactoring, WIZARD_BASED_USER_INTERFACE);
this.info = info;
}
@Override
protected void addUserInputPages() {
page = new InputPage(Messages.ExtractConstantRefactoring_ExtractConst, info, info.getMContext().getType() == ContextType.METHOD);
addPage(page);
}
}

View file

@ -0,0 +1,33 @@
/*******************************************************************************
* Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Sergey Prigogin (Google)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.extractconstant;
import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
import org.eclipse.cdt.ui.CUIPlugin;
/**
* The wizard page for Extract Constant refactoring, creates the UI page.
*/
public class ExtractConstantWizard extends RefactoringWizard {
public ExtractConstantWizard(ExtractConstantRefactoring refactoring) {
super(refactoring, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
setDefaultPageTitle(Messages.ExtractConstantRefactoring_ExtractConst);
setDialogSettings(CUIPlugin.getDefault().getDialogSettings());
}
@Override
protected void addUserInputPages() {
addPage(new InputPage());
}
}

View file

@ -12,41 +12,84 @@
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.extractconstant; package org.eclipse.cdt.internal.ui.refactoring.extractconstant;
import java.util.List; import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
import org.eclipse.osgi.util.NLS; import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.cdt.internal.ui.refactoring.NameAndVisibilityInformation; import org.eclipse.cdt.internal.ui.refactoring.MethodContext.ContextType;
import org.eclipse.cdt.internal.ui.refactoring.dialogs.ExtractInputPage; import org.eclipse.cdt.internal.ui.refactoring.dialogs.NameAndVisibilityComposite;
import org.eclipse.cdt.internal.ui.refactoring.utils.IdentifierHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.IdentifierResult;
import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
public class InputPage extends ExtractInputPage { public class InputPage extends UserInputWizardPage {
private final List<String> usedNames; private static final String PAGE_NAME = "InputPage"; //$NON-NLS-1$
protected ExtractConstantInfo info;
protected NameAndVisibilityComposite control;
private boolean showVisibilityPane; private boolean showVisibilityPane;
public InputPage(String name, NameAndVisibilityInformation info) { public InputPage() {
this(name, info, true); super(PAGE_NAME);
}
public InputPage(String name, NameAndVisibilityInformation info, boolean showVisibilityPane) {
super(name, info);
label = Messages.InputPage_ConstName;
errorLabel = Messages.InputPage_EnterContName;
usedNames = info.getUsedNames();
this.showVisibilityPane = showVisibilityPane;
} }
@Override @Override
public void createControl(Composite parent) { public void createControl(Composite parent) {
super.createControl(parent); this.info = ((ExtractConstantRefactoring) getRefactoring()).getRefactoringInfo();
control.getVisibiltyGroup().setVisible(showVisibilityPane); this.showVisibilityPane = info.getMethodContext().getType() == ContextType.METHOD;
control = new NameAndVisibilityComposite(parent, Messages.InputPage_ConstName, info.getName());
setTitle(getName());
setPageComplete(false);
control.getConstantNameText().addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
info.setName(control.getConstantNameText().getText());
checkName();
}
});
for (Control buttons : control.getVisibiltyGroup().getChildren()) {
buttons.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
String text = ((Button)e.getSource()).getText();
visibilityChange(text);
}
});
} }
@Override checkName();
protected void verifyName(String name) { control.getVisibiltyGroup().setVisible(showVisibilityPane);
if(usedNames.contains(name)) { setControl(control);
}
private void checkName() {
String methodName = control.getConstantNameText().getText();
IdentifierResult result = IdentifierHelper.checkIdentifierName(methodName);
if (result.isCorrect()) {
setErrorMessage(null);
setPageComplete(true);
verifyName(methodName);
} else {
setErrorMessage(result.getMessage());
setPageComplete(false);
}
}
private void verifyName(String name) {
if (info.getUsedNames().contains(name)) {
setErrorMessage(NLS.bind(Messages.InputPage_NameAlreadyDefined, name)); setErrorMessage(NLS.bind(Messages.InputPage_NameAlreadyDefined, name));
setPageComplete(false); setPageComplete(false);
} }
} }
private void visibilityChange(String visibilityText) {
info.setVisibility(VisibilityEnum.getEnumForStringRepresentation(visibilityText));
}
} }

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2008 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others * Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -15,7 +15,7 @@ import org.eclipse.osgi.util.NLS;
public final class Messages extends NLS { public final class Messages extends NLS {
public static String InputPage_ConstName; public static String InputPage_ConstName;
public static String InputPage_EnterContName; public static String InputPage_EnterConstName;
public static String InputPage_NameAlreadyDefined; public static String InputPage_NameAlreadyDefined;
public static String ExtractConstantRefactoring_ExtractConst; public static String ExtractConstantRefactoring_ExtractConst;
public static String ExtractConstantRefactoring_LiteralMustBeSelected; public static String ExtractConstantRefactoring_LiteralMustBeSelected;

View file

@ -1,5 +1,5 @@
############################################################################### ###############################################################################
# Copyright (c) 2008 Institute for Software, HSR Hochschule fuer Technik # Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
# Rapperswil, University of applied sciences and others # Rapperswil, University of applied sciences and others
# All rights reserved. This program and the accompanying materials # All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0 # are made available under the terms of the Eclipse Public License v1.0
@ -11,7 +11,7 @@
# IBM Corporation # IBM Corporation
############################################################################### ###############################################################################
InputPage_ConstName=Constant &name: InputPage_ConstName=Constant &name:
InputPage_EnterContName=Enter a name for the new constant InputPage_EnterConstName=Enter a name for the new constant
InputPage_NameAlreadyDefined=An element named ''{0}'' is already defined in this scope. InputPage_NameAlreadyDefined=An element named ''{0}'' is already defined in this scope.
ExtractConstantRefactoring_ExtractConst=Extract Constant ExtractConstantRefactoring_ExtractConst=Extract Constant
ExtractConstantRefactoring_LiteralMustBeSelected=An literal expression must be selected to activate this refactoring. ExtractConstantRefactoring_LiteralMustBeSelected=An literal expression must be selected to activate this refactoring.

View file

@ -54,7 +54,7 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
import org.eclipse.cdt.internal.ui.util.RowLayouter; import org.eclipse.cdt.internal.ui.util.RowLayouter;
public class ExtractFunctionInputPage extends UserInputWizardPage { public class ExtractFunctionInputPage extends UserInputWizardPage {
public static final String PAGE_NAME = "ExtractFunctionInputPage";//$NON-NLS-1$ public static final String PAGE_NAME = "ExtractFunctionInputPage"; //$NON-NLS-1$
static final String DIALOG_SETTING_SECTION = "ExtractFunctionWizard"; //$NON-NLS-1$ static final String DIALOG_SETTING_SECTION = "ExtractFunctionWizard"; //$NON-NLS-1$
private ExtractFunctionRefactoring refactoring; private ExtractFunctionRefactoring refactoring;

View file

@ -70,7 +70,7 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPFunction;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor; import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.NameAndVisibilityInformation; import org.eclipse.cdt.internal.ui.refactoring.VariableNameInformation;
import org.eclipse.cdt.internal.ui.refactoring.NodeContainer; import org.eclipse.cdt.internal.ui.refactoring.NodeContainer;
import org.eclipse.cdt.internal.ui.refactoring.utils.NodeHelper; import org.eclipse.cdt.internal.ui.refactoring.utils.NodeHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper; import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper;
@ -88,12 +88,12 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
"org.eclipse.cdt.internal.ui.refactoring.extractlocalvariable.ExtractLocalVariableRefactoring"; //$NON-NLS-1$ "org.eclipse.cdt.internal.ui.refactoring.extractlocalvariable.ExtractLocalVariableRefactoring"; //$NON-NLS-1$
private IASTExpression target; private IASTExpression target;
private final NameAndVisibilityInformation info; private final VariableNameInformation info;
private NodeContainer container; private NodeContainer container;
public ExtractLocalVariableRefactoring(ICElement element, ISelection selection, ICProject project) { public ExtractLocalVariableRefactoring(ICElement element, ISelection selection, ICProject project) {
super(element, selection, project); super(element, selection, project);
info = new NameAndVisibilityInformation(); info = new VariableNameInformation();
name = Messages.ExtractLocalVariable; name = Messages.ExtractLocalVariable;
} }
@ -204,7 +204,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
return oneMarked; return oneMarked;
} }
private boolean isExpressionInSelection(IASTExpression expression, Region selection) { private static boolean isExpressionInSelection(IASTExpression expression, Region selection) {
IASTFileLocation location = expression.getFileLocation(); IASTFileLocation location = expression.getFileLocation();
int expressionStart = location.getNodeOffset(); int expressionStart = location.getNodeOffset();
int expressionEnd = expressionStart + location.getNodeLength(); int expressionEnd = expressionStart + location.getNodeLength();
@ -516,7 +516,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
return arguments; return arguments;
} }
public NameAndVisibilityInformation getRefactoringInfo() { public VariableNameInformation getRefactoringInfo() {
return info; return info;
} }
} }

View file

@ -37,8 +37,8 @@ public class ExtractLocalVariableRefactoringRunner extends RefactoringRunner2 {
public void run() { public void run() {
ExtractLocalVariableRefactoring refactoring = ExtractLocalVariableRefactoring refactoring =
new ExtractLocalVariableRefactoring(element, selection, project); new ExtractLocalVariableRefactoring(element, selection, project);
ExtractLocalVariableRefactoringWizard wizard = ExtractLocalVariableWizard wizard =
new ExtractLocalVariableRefactoringWizard(refactoring); new ExtractLocalVariableWizard(refactoring);
run(wizard, refactoring, RefactoringSaveHelper.SAVE_NOTHING); run(wizard, refactoring, RefactoringSaveHelper.SAVE_NOTHING);
} }
} }

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others * Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -14,22 +14,23 @@ package org.eclipse.cdt.internal.ui.refactoring.extractlocalvariable;
import org.eclipse.ltk.ui.refactoring.RefactoringWizard; import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
import org.eclipse.cdt.ui.CUIPlugin;
/** /**
* The wizard page for Extract Local Variable Refactoring, creates the UI page. * The wizard page for Extract Local Variable refactoring, creates the UI page.
* *
* @author Tom Ball * @author Tom Ball
*/ */
public class ExtractLocalVariableRefactoringWizard extends RefactoringWizard { public class ExtractLocalVariableWizard extends RefactoringWizard {
private InputPage page;
public ExtractLocalVariableRefactoringWizard(ExtractLocalVariableRefactoring refactoring) { public ExtractLocalVariableWizard(ExtractLocalVariableRefactoring refactoring) {
super(refactoring, WIZARD_BASED_USER_INTERFACE); super(refactoring, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
setDefaultPageTitle(Messages.ExtractLocalVariable);
setDialogSettings(CUIPlugin.getDefault().getDialogSettings());
} }
@Override @Override
protected void addUserInputPages() { protected void addUserInputPages() {
ExtractLocalVariableRefactoring refactoring = (ExtractLocalVariableRefactoring) getRefactoring(); addPage(new InputPage());
page = new InputPage(Messages.ExtractLocalVariable, refactoring.getRefactoringInfo());
addPage(page);
} }
} }

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2008 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others * Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -8,7 +8,8 @@
* *
* Contributors: * Contributors:
* Institute for Software - initial API and implementation * Institute for Software - initial API and implementation
* Google * Tom Ball (Google)
* Sergey Prigogin (Google)
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.extractlocalvariable; package org.eclipse.cdt.internal.ui.refactoring.extractlocalvariable;
@ -22,7 +23,7 @@ import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Text;
import org.eclipse.cdt.internal.ui.refactoring.NameAndVisibilityInformation; import org.eclipse.cdt.internal.ui.refactoring.VariableNameInformation;
import org.eclipse.cdt.internal.ui.refactoring.dialogs.LabeledTextField; import org.eclipse.cdt.internal.ui.refactoring.dialogs.LabeledTextField;
import org.eclipse.cdt.internal.ui.refactoring.utils.IdentifierHelper; import org.eclipse.cdt.internal.ui.refactoring.utils.IdentifierHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.IdentifierResult; import org.eclipse.cdt.internal.ui.refactoring.utils.IdentifierResult;
@ -34,22 +35,19 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.IdentifierResult;
* @author Tom Ball * @author Tom Ball
*/ */
public class InputPage extends UserInputWizardPage { public class InputPage extends UserInputWizardPage {
private String label = Messages.VariableName; private static final String PAGE_NAME = "InputPage"; //$NON-NLS-1$
private final NameAndVisibilityInformation info;
private VariableNameInformation info;
private InputForm control; private InputForm control;
public InputPage(String name, NameAndVisibilityInformation info) { public InputPage() {
super(name); super(PAGE_NAME);
this.info = info;
}
public String getVariableName() {
return info.getName();
} }
@Override @Override
public void createControl(Composite parent) { public void createControl(Composite parent) {
control = new InputForm(parent, label); this.info = ((ExtractLocalVariableRefactoring) getRefactoring()).getRefactoringInfo();
control = new InputForm(parent, Messages.VariableName);
setTitle(getName()); setTitle(getName());
setMessage(Messages.EnterVariableName); setMessage(Messages.EnterVariableName);
@ -78,14 +76,13 @@ public class InputPage extends UserInputWizardPage {
private void checkName() { private void checkName() {
String methodName = control.getVariableNameText().getText(); String methodName = control.getVariableNameText().getText();
IdentifierResult result = IdentifierHelper IdentifierResult result = IdentifierHelper.checkIdentifierName(methodName);
.checkIdentifierName(methodName);
if (result.isCorrect()) { if (result.isCorrect()) {
setErrorMessage(null); setErrorMessage(null);
setPageComplete(true); setPageComplete(true);
verifyName(methodName); verifyName(methodName);
} else { } else {
setErrorMessage(NLS.bind(Messages.CheckName, result.getMessage())); setErrorMessage(result.getMessage());
setPageComplete(false); setPageComplete(false);
} }
} }
@ -96,8 +93,7 @@ public class InputPage extends UserInputWizardPage {
InputForm(Composite parent, String label) { InputForm(Composite parent, String label) {
super(parent, SWT.NONE); super(parent, SWT.NONE);
FillLayout layout = new FillLayout(SWT.HORIZONTAL); FillLayout layout = new FillLayout(SWT.HORIZONTAL);
GridData gridData = new GridData(SWT.FILL, SWT.BEGINNING, true, GridData gridData = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
false);
gridData.horizontalAlignment = GridData.FILL; gridData.horizontalAlignment = GridData.FILL;
setLayoutData(gridData); setLayoutData(gridData);
setLayout(layout); setLayout(layout);

View file

@ -15,7 +15,6 @@ package org.eclipse.cdt.internal.ui.refactoring.extractlocalvariable;
import org.eclipse.osgi.util.NLS; import org.eclipse.osgi.util.NLS;
public final class Messages extends NLS { public final class Messages extends NLS {
public static String CheckName;
public static String CreateLocalVariable; public static String CreateLocalVariable;
public static String EnterVariableName; public static String EnterVariableName;
public static String ExpressionMustBeSelected; public static String ExpressionMustBeSelected;

View file

@ -9,11 +9,10 @@
# Contributors: # Contributors:
# Institute for Software - initial API and implementation # Institute for Software - initial API and implementation
# IBM Corporation # IBM Corporation
# Google # Tom Ball (Google)
############################################################################### ###############################################################################
VariableName=Variable &name: VariableName=Variable &name:
EnterVariableName=Enter a name for the new variable EnterVariableName=Enter a name for the new variable
CheckName=Check Name: {0}
NameAlreadyDefined=An element named ''{0}'' is already defined in this scope. NameAlreadyDefined=An element named ''{0}'' is already defined in this scope.
ExtractLocalVariable=Extract Local Variable ExtractLocalVariable=Extract Local Variable
ExpressionMustBeSelected=An expression must be selected to activate this refactoring. ExpressionMustBeSelected=An expression must be selected to activate this refactoring.

View file

@ -29,7 +29,6 @@ import org.eclipse.cdt.internal.core.parser.token.KeywordSets;
* @author Thomas Corbat * @author Thomas Corbat
*/ */
public class IdentifierHelper { public class IdentifierHelper {
/** /**
* @param identifier to check * @param identifier to check
* @return an instance of IdentifierResult that holds the outcome of the validation * @return an instance of IdentifierResult that holds the outcome of the validation

View file

@ -44,8 +44,8 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTNamespaceDefinition;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTranslationUnit; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTranslationUnit;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor; import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.ui.refactoring.MethodContext;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringContext; import org.eclipse.cdt.internal.ui.refactoring.CRefactoringContext;
import org.eclipse.cdt.internal.ui.refactoring.MethodContext;
/** /**
* General class for common Node operations. * General class for common Node operations.
@ -107,12 +107,11 @@ public class NodeHelper {
return null; return null;
} }
public static MethodContext findMethodContext(IASTNode node, CRefactoringContext astCache, public static MethodContext findMethodContext(IASTNode node, CRefactoringContext refactoringContext,
IProgressMonitor pm) throws CoreException { IProgressMonitor pm) throws CoreException {
IASTTranslationUnit translationUnit = node.getTranslationUnit(); IASTTranslationUnit translationUnit = node.getTranslationUnit();
boolean found = false; boolean found = false;
MethodContext context = new MethodContext(); MethodContext context = new MethodContext();
context.setType(MethodContext.ContextType.NONE);
IASTName name = null; IASTName name = null;
while (node != null && !found) { while (node != null && !found) {
node = node.getParent(); node = node.getParent();
@ -126,11 +125,11 @@ public class NodeHelper {
context.setType(MethodContext.ContextType.FUNCTION); context.setType(MethodContext.ContextType.FUNCTION);
} }
} }
getMethodContexWithIndex(astCache, translationUnit, name, context, pm); getMethodContexWithIndex(refactoringContext, translationUnit, name, context, pm);
return context; return context;
} }
private static void getMethodContexWithIndex(CRefactoringContext astCache, private static void getMethodContexWithIndex(CRefactoringContext refactoringContext,
IASTTranslationUnit ast, IASTName name, MethodContext context, IProgressMonitor pm) IASTTranslationUnit ast, IASTName name, MethodContext context, IProgressMonitor pm)
throws CoreException { throws CoreException {
if (name instanceof ICPPASTQualifiedName) { if (name instanceof ICPPASTQualifiedName) {
@ -140,7 +139,7 @@ public class NodeHelper {
IBinding binding = name.resolveBinding(); IBinding binding = name.resolveBinding();
if (binding instanceof ICPPMethod) { if (binding instanceof ICPPMethod) {
context.setType(MethodContext.ContextType.METHOD); context.setType(MethodContext.ContextType.METHOD);
IIndex index = astCache.getIndex(); IIndex index = refactoringContext.getIndex();
IIndexName[] declarations = index.findDeclarations(binding); IIndexName[] declarations = index.findDeclarations(binding);
if (declarations.length == 0) { if (declarations.length == 0) {
context.setMethodDeclarationName(name); context.setMethodDeclarationName(name);
@ -153,7 +152,7 @@ public class NodeHelper {
IIndexFileLocation fileLocation = decl.getFile().getLocation(); IIndexFileLocation fileLocation = decl.getFile().getLocation();
ITranslationUnit locTu = ITranslationUnit locTu =
CoreModelUtil.findTranslationUnitForLocation(fileLocation, cProject); CoreModelUtil.findTranslationUnitForLocation(fileLocation, cProject);
astCache.getAST(locTu, pm); ast2 = refactoringContext.getAST(locTu, pm);
} }
IASTName declName = DeclarationFinder.findDeclarationInTranslationUnit(ast2, decl); IASTName declName = DeclarationFinder.findDeclarationInTranslationUnit(ast2, decl);
if (declName != null) { if (declName != null) {
@ -169,14 +168,13 @@ public class NodeHelper {
} }
/** /**
* @deprecated Use #findMethodContext(IASTNode, RefactoringASTCache, IProgressMonitor pm) * @deprecated Use #findMethodContext(IASTNode, CRefactoringContext, IProgressMonitor)
*/ */
@Deprecated @Deprecated
public static MethodContext findMethodContext(IASTNode node, IIndex index) throws CoreException { public static MethodContext findMethodContext(IASTNode node, IIndex index) throws CoreException {
IASTTranslationUnit translationUnit = node.getTranslationUnit(); IASTTranslationUnit translationUnit = node.getTranslationUnit();
boolean found = false; boolean found = false;
MethodContext context = new MethodContext(); MethodContext context = new MethodContext();
context.setType(MethodContext.ContextType.NONE);
IASTName name = null; IASTName name = null;
while (node != null && !found) { while (node != null && !found) {
node = node.getParent(); node = node.getParent();
@ -191,15 +189,15 @@ public class NodeHelper {
} }
} }
if (index != null) { if (index != null) {
getMethodContexWithIndex(index, translationUnit, context, name); getMethodContextWithIndex(index, translationUnit, context, name);
} else { } else {
getMethodContex(translationUnit, context, name); getMethodContext(translationUnit, context, name);
} }
return context; return context;
} }
@Deprecated @Deprecated
private static void getMethodContexWithIndex(IIndex index, IASTTranslationUnit translationUnit, private static void getMethodContextWithIndex(IIndex index, IASTTranslationUnit translationUnit,
MethodContext context, IASTName name) throws CoreException { MethodContext context, IASTName name) throws CoreException {
IBinding bind = name.resolveBinding(); IBinding bind = name.resolveBinding();
if (bind instanceof ICPPMethod) { if (bind instanceof ICPPMethod) {
@ -231,7 +229,7 @@ public class NodeHelper {
} }
} }
private static void getMethodContex(IASTTranslationUnit translationUnit, MethodContext context, private static void getMethodContext(IASTTranslationUnit translationUnit, MethodContext context,
IASTName name) { IASTName name) {
if (name instanceof ICPPASTQualifiedName) { if (name instanceof ICPPASTQualifiedName) {
ICPPASTQualifiedName qname = (ICPPASTQualifiedName) name; ICPPASTQualifiedName qname = (ICPPASTQualifiedName) name;

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2005, 2009 Wind River Systems, Inc. * Copyright (c) 2005, 2012 Wind River Systems, Inc.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at * which accompanies this distribution, and is available at
@ -7,13 +7,10 @@
* *
* Contributors: * Contributors:
* Markus Schorn - initial API and implementation * Markus Schorn - initial API and implementation
* Sergey Prigogin (Google)
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.ui.refactoring.actions; package org.eclipse.cdt.ui.refactoring.actions;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.window.IShellProvider; import org.eclipse.jface.window.IShellProvider;
@ -23,7 +20,7 @@ import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.internal.ui.refactoring.extractconstant.ExtractConstantRefactoringRunner; import org.eclipse.cdt.internal.ui.refactoring.extractconstant.ExtractConstantRefactoringRunner;
/** /**
* Launches a extract constant refactoring. * Launches an Extract Constant refactoring.
* *
* @noextend This class is not intended to be subclassed by clients. * @noextend This class is not intended to be subclassed by clients.
*/ */
@ -39,9 +36,8 @@ public class ExtractConstantAction extends RefactoringAction {
@Override @Override
public void run(IShellProvider shellProvider, IWorkingCopy wc, ITextSelection selection) { public void run(IShellProvider shellProvider, IWorkingCopy wc, ITextSelection selection) {
IResource res= wc.getResource(); if (wc.getResource() != null) {
if (res instanceof IFile) { new ExtractConstantRefactoringRunner(wc, selection, shellProvider, wc.getCProject()).run();
new ExtractConstantRefactoringRunner((IFile) res, selection, shellProvider, wc.getCProject()).run();
} }
} }