1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-06-06 17:26:01 +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.
*/
public class ExtractConstantRefactoringTest extends RefactoringTestBase {
private ExtractConstantInfo refactoringInfo;
private String extractedConstantName = "EXTRACTED";
private VisibilityEnum visibility = VisibilityEnum.v_private;
private ExtractConstantRefactoring refactoring;
public ExtractConstantRefactoringTest() {
super();
@ -44,15 +44,16 @@ public class ExtractConstantRefactoringTest extends RefactoringTestBase {
@Override
protected Refactoring createRefactoring() {
refactoringInfo = new ExtractConstantInfo();
return new ExtractConstantRefactoring(getSelectedFile(), getSelection(), refactoringInfo,
refactoring = new ExtractConstantRefactoring(getSelectedTranslationUnit(), getSelection(),
getCProject());
return refactoring;
}
@Override
protected void simulateUserInput() {
refactoringInfo.setName(extractedConstantName);
refactoringInfo.setVisibility(visibility);
ExtractConstantInfo info = refactoring.getRefactoringInfo();
info.setName(extractedConstantName);
info.setVisibility(visibility);
}
//A.h

View file

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

View file

@ -15,14 +15,11 @@ package org.eclipse.cdt.internal.ui.refactoring;
import java.util.ArrayList;
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 VisibilityEnum visibility = VisibilityEnum.v_public;
private final ArrayList<String> usedNames = new ArrayList<String>();
public String getName() {
@ -33,15 +30,7 @@ public class NameAndVisibilityInformation {
this.name = name;
}
public VisibilityEnum getVisibility() {
return visibility;
}
public void setVisibility(VisibilityEnum visibility) {
this.visibility = visibility;
}
public List<String> getUsedNames(){
public List<String> getUsedNames() {
return usedNames;
}
@ -49,7 +38,7 @@ public class NameAndVisibilityInformation {
usedNames.add(name);
}
public void addNamesToUsedNames(ArrayList<String> names) {
public void addNamesToUsedNames(List<String> 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

@ -7,7 +7,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Institute for Software - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.dialogs;
@ -22,10 +22,8 @@ import org.eclipse.swt.widgets.Text;
* A text field with an associated label, displayed side-by-side.
*
* @author Mirko Stocker
*
*/
public class LabeledTextField extends Composite {
private final Text textField;
public LabeledTextField(Composite parent, String labelName, String textContent) {
@ -40,7 +38,7 @@ public class LabeledTextField extends Composite {
label.setText(labelName);
label.setLayoutData(new GridData());
textField = new Text(this, SWT.BORDER |SWT.SINGLE);
textField = new Text(this, SWT.BORDER | SWT.SINGLE);
textField.setText(textContent);
textField.selectAll();
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.
* All rights reserved. This program and the accompanying materials
* 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
*
* 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;
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
*
*/
public class ExtractConstantInfo extends NameAndVisibilityInformation{
private MethodContext mContext;
public class ExtractConstantInfo extends VariableNameInformation {
private VisibilityEnum visibility = VisibilityEnum.v_private;
private MethodContext methodContext;
public MethodContext getMContext() {
return mContext;
public VisibilityEnum getVisibility() {
return visibility;
}
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
* All rights reserved. This program and the accompanying materials
* 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.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubMonitor;
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.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.text.edits.TextEditGroup;
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.IASTEqualsInitializer;
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.IASTLiteralExpression;
import org.eclipse.cdt.core.dom.ast.IASTMacroExpansionLocation;
import org.eclipse.cdt.core.dom.ast.IASTNode;
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.IBinding;
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.rewrite.ASTRewrite;
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.ITranslationUnit;
import org.eclipse.cdt.ui.CUIPlugin;
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.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.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescription;
import org.eclipse.cdt.internal.ui.refactoring.MethodContext;
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.SelectionHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.TranslationUnitHelper;
import org.eclipse.cdt.internal.ui.util.NameComposer;
/**
* The central class of the Extract Constant Refactoring. Does all the work like checking pre- and
* postconditions and collecting/creating the modifications to the AST.
* The main class of the Extract Constant refactoring.
*
* @author Mirko Stocker
*/
public class ExtractConstantRefactoring extends CRefactoring {
public static final String ID = "org.eclipse.cdt.ui.refactoring.extractconstant.ExtractConstantRefactoring"; //$NON-NLS-1$
private IASTLiteralExpression target = null;
private final ArrayList<IASTExpression> literalsToReplace = new ArrayList<IASTExpression>();
public class ExtractConstantRefactoring extends CRefactoring2 {
public static final String ID =
"org.eclipse.cdt.ui.refactoring.extractconstant.ExtractConstantRefactoring"; //$NON-NLS-1$
private IASTLiteralExpression target;
private final ExtractConstantInfo info;
public ExtractConstantRefactoring(IFile file, ISelection selection, ExtractConstantInfo info, ICProject proj) {
super(file,selection, null, proj);
this.info = info;
this.project = proj;
private final ArrayList<IASTExpression> literalsToReplace = new ArrayList<IASTExpression>();
public ExtractConstantRefactoring(ICElement element, ISelection selection, ICProject project) {
super(element, selection, project);
this.info = new ExtractConstantInfo();
name = Messages.ExtractConstantRefactoring_ExtractConst;
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
SubMonitor sm = SubMonitor.convert(pm, 9);
try {
lockIndex();
try {
RefactoringStatus status = super.checkInitialConditions(sm.newChild(6));
if (status.hasError()) {
return status;
}
SubMonitor sm = SubMonitor.convert(pm, 10);
Collection<IASTLiteralExpression> literalExpressionCollection = findAllLiterals();
if (literalExpressionCollection.isEmpty()) {
initStatus.addFatalError(Messages.ExtractConstantRefactoring_LiteralMustBeSelected);
return initStatus;
}
sm.worked(1);
if (isProgressMonitorCanceld(sm, initStatus)) return initStatus;
boolean oneMarked = region != null && isOneMarked(literalExpressionCollection, region);
if (!oneMarked) {
//No or more than one marked
if (target == null) {
//No Selection found;
initStatus.addFatalError(Messages.ExtractConstantRefactoring_NoLiteralSelected);
} else {
//To many selection found
initStatus.addFatalError(Messages.ExtractConstantRefactoring_TooManyLiteralSelected);
}
return initStatus;
}
sm.worked(1);
if (isProgressMonitorCanceld(sm, initStatus)) return initStatus;
findAllNodesForReplacement(literalExpressionCollection);
info.addNamesToUsedNames(findAllDeclaredNames());
if (info.getName().length() == 0) {
info.setName(getDefaultName(target));
}
info.setMContext(NodeHelper.findMethodContext(target, getIndex()));
sm.done();
}
finally {
unlockIndex();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
RefactoringStatus status = super.checkInitialConditions(sm.newChild(7));
if (status.hasError()) {
return status;
}
Collection<IASTLiteralExpression> literalExpressionCollection = findAllLiterals(sm.newChild(1));
if (literalExpressionCollection.isEmpty()) {
initStatus.addFatalError(Messages.ExtractConstantRefactoring_LiteralMustBeSelected);
return initStatus;
}
if (isProgressMonitorCanceld(sm, initStatus))
return initStatus;
boolean oneMarked =
selectedRegion != null && isOneMarked(literalExpressionCollection, selectedRegion);
if (!oneMarked) {
// None or more than one literal selected
if (target == null) {
// No l found;
initStatus.addFatalError(Messages.ExtractConstantRefactoring_NoLiteralSelected);
} else {
// To many selection found
initStatus.addFatalError(Messages.ExtractConstantRefactoring_TooManyLiteralSelected);
}
return initStatus;
}
sm.worked(1);
if (isProgressMonitorCanceld(sm, initStatus))
return initStatus;
findAllNodesForReplacement(literalExpressionCollection);
info.addNamesToUsedNames(findAllDeclaredNames());
if (info.getName().isEmpty()) {
info.setName(getDefaultName(target));
}
info.setMethodContext(NodeHelper.findMethodContext(target, refactoringContext, sm.newChild(1)));
sm.done();
return initStatus;
}
@ -205,14 +197,14 @@ public class ExtractConstantRefactoring extends CRefactoring {
if (binding instanceof CPPMethod) {
CPPMethod methode = (CPPMethod) binding;
IASTNode[] declarations = methode.getDeclarations();
IASTNode decl;
if (declarations != null) {
decl = declarations[0];
} else {
decl = methode.getDefinition();
}
IASTNode spec = decl.getParent().getParent();
if (spec instanceof ICPPASTCompositeTypeSpecifier) {
ICPPASTCompositeTypeSpecifier compTypeSpec = (ICPPASTCompositeTypeSpecifier) spec;
@ -232,27 +224,28 @@ public class ExtractConstantRefactoring extends CRefactoring {
&& expression.getParent() instanceof IASTUnaryExpression
&& unary.getOperator() == ((IASTUnaryExpression)expression.getParent()).getOperator()) {
literalsToReplace.add(((IASTUnaryExpression)expression.getParent()));
}
}
}
} else {
for (IASTLiteralExpression expression : literalExpressionCollection) {
if (target.getKind() == expression.getKind()
&& target.toString().equals(expression.toString())) {
literalsToReplace.add(expression);
}
}
}
}
}
private boolean isOneMarked(Collection<IASTLiteralExpression> literalExpressionCollection, Region textSelection) {
private boolean isOneMarked(Collection<IASTLiteralExpression> selectedNodes,
Region textSelection) {
boolean oneMarked = false;
for (IASTLiteralExpression expression : literalExpressionCollection) {
boolean isInSameFileSelection = SelectionHelper.isInSameFileSelection(textSelection, expression, file);
if (isInSameFileSelection) {
for (IASTLiteralExpression expression : selectedNodes) {
if (expression.isPartOfTranslationUnitFile() &&
isExpressionInSelection(expression, textSelection)) {
if (target == null) {
target = expression;
oneMarked = true;
} else {
} else if (!isTargetChild(expression)) {
oneMarked = false;
}
}
@ -260,18 +253,43 @@ public class ExtractConstantRefactoring extends CRefactoring {
return oneMarked;
}
private Collection<IASTLiteralExpression> findAllLiterals() {
final Collection<IASTLiteralExpression> result = new ArrayList<IASTLiteralExpression>();
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>();
IASTTranslationUnit ast = getAST(tu, pm);
ast.accept(new ASTVisitor() {
{
shouldVisitExpressions = true;
}
@Override
public int visit(IASTExpression expression) {
if (expression instanceof IASTLiteralExpression) {
if (!(expression.getNodeLocations().length == 1
&& expression.getNodeLocations()[0] instanceof IASTMacroExpansionLocation)) {
if (!(expression.getNodeLocations().length == 1 &&
expression.getNodeLocations()[0] instanceof IASTMacroExpansionLocation)) {
IASTLiteralExpression literal = (IASTLiteralExpression) expression;
result.add(literal);
}
@ -279,79 +297,83 @@ public class ExtractConstantRefactoring extends CRefactoring {
return super.visit(expression);
}
});
return result;
}
@Override
protected RefactoringStatus checkFinalConditions(IProgressMonitor subProgressMonitor,
CheckConditionsContext checkContext) throws CoreException, OperationCanceledException {
return new RefactoringStatus();
}
@Override
protected void collectModifications(IProgressMonitor pm, ModificationCollector collector)
throws CoreException, OperationCanceledException{
try {
lockIndex();
try {
MethodContext context = info.getMContext();
Collection<IASTExpression> locLiteralsToReplace = new ArrayList<IASTExpression>();
SubMonitor progress = SubMonitor.convert(pm, 10);
MethodContext context = info.getMethodContext();
Collection<IASTExpression> locLiteralsToReplace = new ArrayList<IASTExpression>();
if (context.getType() == MethodContext.ContextType.METHOD) {
for (IASTExpression expression : literalsToReplace) {
MethodContext exprContext = NodeHelper.findMethodContext(expression, getIndex());
if (exprContext.getType() == MethodContext.ContextType.METHOD) {
if (context.getMethodQName() != null) {
if (MethodContext.isSameClass(exprContext.getMethodQName(), context.getMethodQName())) {
locLiteralsToReplace.add(expression);
}
} else {
if (MethodContext.isSameClass(exprContext.getMethodDeclarationName(), context.getMethodDeclarationName())) {
locLiteralsToReplace.add(expression);
}
}
IASTTranslationUnit ast = getAST(tu, progress.newChild(9));
if (context.getType() == MethodContext.ContextType.METHOD) {
SubMonitor loopProgress = progress.newChild(1).setWorkRemaining(literalsToReplace.size());
for (IASTExpression expression : literalsToReplace) {
MethodContext exprContext =
NodeHelper.findMethodContext(expression, refactoringContext, loopProgress.newChild(1));
if (exprContext.getType() == MethodContext.ContextType.METHOD) {
if (context.getMethodQName() != null) {
if (MethodContext.isSameClass(exprContext.getMethodQName(), context.getMethodQName())) {
locLiteralsToReplace.add(expression);
}
}
} else {
for (IASTExpression expression : literalsToReplace) {
IPath path = new Path(expression.getContainingFilename());
IFile expressionFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
//expressionFile may be null if the file is NOT in the workspace
if (expressionFile != null && expressionFile.equals(file)) {
} else {
if (MethodContext.isSameClass(exprContext.getMethodDeclarationName(),
context.getMethodDeclarationName())) {
locLiteralsToReplace.add(expression);
}
}
}
// Create all Changes for literals
String constName = info.getName();
createLiteralToConstantChanges(constName, locLiteralsToReplace, collector);
if (context.getType() == MethodContext.ContextType.METHOD) {
ICPPASTCompositeTypeSpecifier classDefinition = (ICPPASTCompositeTypeSpecifier) context.getMethodDeclaration().getParent();
ClassMemberInserter.createChange(classDefinition, info.getVisibility(), getConstNodesClass(constName), true, collector);
} else {
IASTDeclaration nodes = getConstNodesGlobal(constName);
ASTRewrite rewriter = collector.rewriterForTranslationUnit(ast);
rewriter.insertBefore(ast, TranslationUnitHelper.getFirstNode(ast), nodes, new TextEditGroup(Messages.ExtractConstantRefactoring_CreateConstant));
}
} finally {
unlockIndex();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} else {
for (IASTExpression expression : literalsToReplace) {
ITranslationUnit expressionTu = expression.getTranslationUnit().getOriginatingTranslationUnit();
if (expressionTu.getResource() != null) {
locLiteralsToReplace.add(expression);
}
}
}
// Create all changes for literals
String constName = info.getName();
createLiteralToConstantChanges(constName, locLiteralsToReplace, collector);
if (context.getType() == MethodContext.ContextType.METHOD) {
ICPPASTCompositeTypeSpecifier classDefinition =
(ICPPASTCompositeTypeSpecifier) context.getMethodDeclaration().getParent();
ClassMemberInserter.createChange(classDefinition, info.getVisibility(),
getConstNodesClass(constName), true, collector);
} else {
IASTDeclaration nodes = getConstNodesGlobal(constName, ast.getASTNodeFactory());
ASTRewrite rewriter = collector.rewriterForTranslationUnit(ast);
rewriter.insertBefore(ast, TranslationUnitHelper.getFirstNode(ast), nodes,
new TextEditGroup(Messages.ExtractConstantRefactoring_CreateConstant));
}
}
@Override
protected RefactoringDescriptor getRefactoringDescriptor() {
Map<String, String> arguments = getArgumentMap();
RefactoringDescriptor desc = new ExtractConstantRefactoringDescription(project.getProject().getName(),
"Extract Constant Refactoring", "Create constant for " + target.getRawSignature(), arguments); //$NON-NLS-1$//$NON-NLS-2$
RefactoringDescriptor desc = new ExtractConstantRefactoringDescriptor(project.getProject().getName(),
"Extract Constant Refactoring", "Create constant for " + target.getRawSignature(), //$NON-NLS-1$ //$NON-NLS-2$
arguments);
return desc;
}
private Map<String, String> getArgumentMap() {
Map<String, String> arguments = new HashMap<String, String>();
arguments.put(CRefactoringDescription.FILE_NAME, file.getLocationURI().toString());
arguments.put(CRefactoringDescription.SELECTION, region.getOffset() + "," + region.getLength()); //$NON-NLS-1$
arguments.put(ExtractConstantRefactoringDescription.NAME, info.getName());
arguments.put(ExtractConstantRefactoringDescription.VISIBILITY, info.getVisibility().toString());
arguments.put(CRefactoringDescriptor.FILE_NAME, tu.getLocationURI().toString());
arguments.put(CRefactoringDescriptor.SELECTION, selectedRegion.getOffset() + "," + selectedRegion.getLength()); //$NON-NLS-1$
arguments.put(ExtractConstantRefactoringDescriptor.NAME, info.getName());
arguments.put(ExtractConstantRefactoringDescriptor.VISIBILITY, info.getVisibility().toString());
return arguments;
}
@ -359,56 +381,63 @@ public class ExtractConstantRefactoring extends CRefactoring {
Iterable<? extends IASTExpression> literals, ModificationCollector collector) {
for (IASTExpression each : literals) {
ASTRewrite rewrite = collector.rewriterForTranslationUnit(each.getTranslationUnit());
CPPASTIdExpression idExpression = new CPPASTIdExpression(new CPPASTName(constName.toCharArray()));
rewrite.replace(each, idExpression, new TextEditGroup(Messages.ExtractConstantRefactoring_ReplaceLiteral));
CPPASTIdExpression idExpression =
new CPPASTIdExpression(new CPPASTName(constName.toCharArray()));
rewrite.replace(each, idExpression,
new TextEditGroup(Messages.ExtractConstantRefactoring_ReplaceLiteral));
}
}
private IASTSimpleDeclaration getConstNodes(String newName) {
ICPPNodeFactory factory = ASTNodeFactoryFactory.getDefaultCPPNodeFactory();
DeclarationGenerator generator = DeclarationGenerator.create(factory);
IType type = target.getExpressionType();
IASTDeclSpecifier declSpec = generator.createDeclSpecFromType(type);
declSpec.setConst(true);
IASTDeclarator declarator = generator.createDeclaratorFromType(type, newName.toCharArray());
IASTSimpleDeclaration simple = new CPPASTSimpleDeclaration();
simple.setDeclSpecifier(declSpec);
IASTEqualsInitializer init = new CPPASTEqualsInitializer();
if (target.getParent() instanceof IASTUnaryExpression) {
IASTUnaryExpression unary = (IASTUnaryExpression) target.getParent();
init.setInitializerClause(unary);
} else {
CPPASTLiteralExpression expression = new CPPASTLiteralExpression(target.getKind(), target.getValue());
CPPASTLiteralExpression expression =
new CPPASTLiteralExpression(target.getKind(), target.getValue());
init.setInitializerClause(expression);
}
declarator.setInitializer(init);
simple.addDeclarator(declarator);
return simple;
}
private IASTDeclaration getConstNodesGlobal(String newName) {
private IASTDeclaration getConstNodesGlobal(String newName, INodeFactory nodeFactory) {
IASTSimpleDeclaration simple = getConstNodes(newName);
INodeFactory factory= ast.getASTNodeFactory();
if (factory instanceof ICPPNodeFactory) {
ICPPASTNamespaceDefinition namespace = ((ICPPNodeFactory) factory).newNamespaceDefinition(new CPPASTName());
if (nodeFactory instanceof ICPPNodeFactory) {
ICPPASTNamespaceDefinition namespace =
((ICPPNodeFactory) nodeFactory).newNamespaceDefinition(new CPPASTName());
namespace.addDeclaration(simple);
return namespace;
}
simple.getDeclSpecifier().setStorageClass(IASTDeclSpecifier.sc_static);
return simple;
}
private IASTDeclaration getConstNodesClass(String newName) {
IASTSimpleDeclaration simple = getConstNodes(newName);
simple.getDeclSpecifier().setStorageClass(IASTDeclSpecifier.sc_static);
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)
throws IllegalArgumentException {
if (id.equals(ExtractConstantRefactoring.ID)) {
return new ExtractConstantRefactoringDescription(project, description, comment, arguments);
return new ExtractConstantRefactoringDescriptor(project, description, comment, arguments);
} else {
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.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
@ -7,54 +7,47 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* 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;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
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.RefactoringStatus;
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;
/**
* @author Emanuel Graf IFS
*
*/
public class ExtractConstantRefactoringDescription extends
CRefactoringDescription {
public class ExtractConstantRefactoringDescriptor extends CRefactoringDescriptor {
protected static final String NAME = "name"; //$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) {
super(ExtractConstantRefactoring.ID, project, description, comment, RefactoringDescriptor.MULTI_CHANGE, arguments);
super(ExtractConstantRefactoring.ID, project, description, comment,
RefactoringDescriptor.MULTI_CHANGE, arguments);
}
@Override
public Refactoring createRefactoring(RefactoringStatus status)
public CRefactoring2 createRefactoring(RefactoringStatus status)
throws CoreException {
IFile file;
ExtractConstantInfo info = new ExtractConstantInfo();
ICProject proj;
ISelection selection = getSelection();
ICProject project = getCProject();
ExtractConstantRefactoring refactoring =
new ExtractConstantRefactoring(getTranslationUnit(), selection, project);
ExtractConstantInfo info = refactoring.getRefactoringInfo();
info.setName(arguments.get(NAME));
info.setVisibility(VisibilityEnum.getEnumForStringRepresentation(arguments.get(VISIBILITY)));
proj = getCProject();
file = getFile();
ISelection selection = getSelection();
return new ExtractConstantRefactoring(file, selection, info, proj);
return refactoring;
}
}

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
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
@ -7,41 +7,35 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* 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;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.viewers.ISelection;
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.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringRunner2;
import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper;
/**
* @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) {
super(file, selection, null, shellProvider, cProject);
super(element, selection, shellProvider, cProject);
}
@Override
public void run() {
ExtractConstantInfo info = new ExtractConstantInfo();
CRefactoring refactoring = new ExtractConstantRefactoring(file,selection,info, project);
ExtractConstantRefactoringWizard wizard = new ExtractConstantRefactoringWizard(refactoring, info);
RefactoringWizardOpenOperation operator = new RefactoringWizardOpenOperation(wizard);
try {
operator.run(shellProvider.getShell(), refactoring.getName());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
ExtractConstantRefactoring refactoring =
new ExtractConstantRefactoring(element, selection, project);
ExtractConstantWizard wizard = new ExtractConstantWizard(refactoring);
run(wizard, refactoring, RefactoringSaveHelper.SAVE_REFACTORING);
}
}

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;
import java.util.List;
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.dialogs.ExtractInputPage;
import org.eclipse.cdt.internal.ui.refactoring.MethodContext.ContextType;
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 {
private final List<String> usedNames;
public class InputPage extends UserInputWizardPage {
private static final String PAGE_NAME = "InputPage"; //$NON-NLS-1$
protected ExtractConstantInfo info;
protected NameAndVisibilityComposite control;
private boolean showVisibilityPane;
public InputPage(String name, NameAndVisibilityInformation info) {
this(name, info, true);
}
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;
public InputPage() {
super(PAGE_NAME);
}
@Override
public void createControl(Composite parent) {
super.createControl(parent);
this.info = ((ExtractConstantRefactoring) getRefactoring()).getRefactoringInfo();
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);
}
});
}
checkName();
control.getVisibiltyGroup().setVisible(showVisibilityPane);
setControl(control);
}
@Override
protected void verifyName(String name) {
if(usedNames.contains(name)) {
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));
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
* All rights reserved. This program and the accompanying materials
* 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 static String InputPage_ConstName;
public static String InputPage_EnterContName;
public static String InputPage_EnterConstName;
public static String InputPage_NameAlreadyDefined;
public static String ExtractConstantRefactoring_ExtractConst;
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
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
@ -11,7 +11,7 @@
# IBM Corporation
###############################################################################
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.
ExtractConstantRefactoring_ExtractConst=Extract Constant
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;
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$
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.CRefactoringDescriptor;
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.utils.NodeHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper;
@ -86,14 +86,14 @@ import org.eclipse.cdt.internal.ui.util.NameComposer;
public class ExtractLocalVariableRefactoring extends CRefactoring2 {
public static final String ID =
"org.eclipse.cdt.internal.ui.refactoring.extractlocalvariable.ExtractLocalVariableRefactoring"; //$NON-NLS-1$
private IASTExpression target;
private final NameAndVisibilityInformation info;
private final VariableNameInformation info;
private NodeContainer container;
public ExtractLocalVariableRefactoring(ICElement element, ISelection selection, ICProject project) {
super(element, selection, project);
info = new NameAndVisibilityInformation();
info = new VariableNameInformation();
name = Messages.ExtractLocalVariable;
}
@ -132,7 +132,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
container.getNames(); //XXX Is this needed?
sm.worked(1);
info.addNamesToUsedNames(findAllDeclaredNames());
sm.worked(1);
@ -204,7 +204,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
return oneMarked;
}
private boolean isExpressionInSelection(IASTExpression expression, Region selection) {
private static boolean isExpressionInSelection(IASTExpression expression, Region selection) {
IASTFileLocation location = expression.getFileLocation();
int expressionStart = location.getNodeOffset();
int expressionEnd = expressionStart + location.getNodeLength();
@ -236,7 +236,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
{
shouldVisitExpressions = true;
}
@Override
public int visit(IASTExpression expression) {
if (expression.isPartOfTranslationUnitFile() &&
@ -283,11 +283,11 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
private IASTDeclarationStatement getVariableNodes(IASTTranslationUnit ast, String newName) {
INodeFactory factory = ast.getASTNodeFactory();
IASTSimpleDeclaration simple = factory.newSimpleDeclaration(null);
DeclarationGenerator generator = DeclarationGenerator.create(factory);
IASTDeclSpecifier declSpec = generator.createDeclSpecFromType(target.getExpressionType());
declSpec.setStorageClass(IASTDeclSpecifier.sc_unspecified);
simple.setDeclSpecifier(declSpec);
@ -379,7 +379,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
}
}
}
if (expression instanceof CPPASTLiteralExpression) {
CPPASTLiteralExpression literal = (CPPASTLiteralExpression) expression;
String name = null;
@ -423,7 +423,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
PreferenceConstants.NAME_STYLE_VARIABLE_SUFFIX, "", null); //$NON-NLS-1$
NameComposer composer = new NameComposer(capitalization, wordDelimiter, prefix, suffix);
name = composer.compose(name);
if (name.length() > 0) {
if (nameAvailable(name, guessedTempNames, scope)) {
guessedTempNames.add(name);
@ -516,7 +516,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
return arguments;
}
public NameAndVisibilityInformation getRefactoringInfo() {
public VariableNameInformation getRefactoringInfo() {
return info;
}
}

View file

@ -37,8 +37,8 @@ public class ExtractLocalVariableRefactoringRunner extends RefactoringRunner2 {
public void run() {
ExtractLocalVariableRefactoring refactoring =
new ExtractLocalVariableRefactoring(element, selection, project);
ExtractLocalVariableRefactoringWizard wizard =
new ExtractLocalVariableRefactoringWizard(refactoring);
ExtractLocalVariableWizard wizard =
new ExtractLocalVariableWizard(refactoring);
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
* All rights reserved. This program and the accompanying materials
* 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.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
*/
public class ExtractLocalVariableRefactoringWizard extends RefactoringWizard {
private InputPage page;
public class ExtractLocalVariableWizard extends RefactoringWizard {
public ExtractLocalVariableRefactoringWizard(ExtractLocalVariableRefactoring refactoring) {
super(refactoring, WIZARD_BASED_USER_INTERFACE);
public ExtractLocalVariableWizard(ExtractLocalVariableRefactoring refactoring) {
super(refactoring, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
setDefaultPageTitle(Messages.ExtractLocalVariable);
setDialogSettings(CUIPlugin.getDefault().getDialogSettings());
}
@Override
protected void addUserInputPages() {
ExtractLocalVariableRefactoring refactoring = (ExtractLocalVariableRefactoring) getRefactoring();
page = new InputPage(Messages.ExtractLocalVariable, refactoring.getRefactoringInfo());
addPage(page);
addPage(new InputPage());
}
}

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
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
@ -8,7 +8,8 @@
*
* Contributors:
* Institute for Software - initial API and implementation
* Google
* Tom Ball (Google)
* Sergey Prigogin (Google)
*******************************************************************************/
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.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.utils.IdentifierHelper;
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
*/
public class InputPage extends UserInputWizardPage {
private String label = Messages.VariableName;
private final NameAndVisibilityInformation info;
private static final String PAGE_NAME = "InputPage"; //$NON-NLS-1$
private VariableNameInformation info;
private InputForm control;
public InputPage(String name, NameAndVisibilityInformation info) {
super(name);
this.info = info;
}
public String getVariableName() {
return info.getName();
public InputPage() {
super(PAGE_NAME);
}
@Override
public void createControl(Composite parent) {
control = new InputForm(parent, label);
this.info = ((ExtractLocalVariableRefactoring) getRefactoring()).getRefactoringInfo();
control = new InputForm(parent, Messages.VariableName);
setTitle(getName());
setMessage(Messages.EnterVariableName);
@ -78,14 +76,13 @@ public class InputPage extends UserInputWizardPage {
private void checkName() {
String methodName = control.getVariableNameText().getText();
IdentifierResult result = IdentifierHelper
.checkIdentifierName(methodName);
IdentifierResult result = IdentifierHelper.checkIdentifierName(methodName);
if (result.isCorrect()) {
setErrorMessage(null);
setPageComplete(true);
verifyName(methodName);
} else {
setErrorMessage(NLS.bind(Messages.CheckName, result.getMessage()));
setErrorMessage(result.getMessage());
setPageComplete(false);
}
}
@ -96,8 +93,7 @@ public class InputPage extends UserInputWizardPage {
InputForm(Composite parent, String label) {
super(parent, SWT.NONE);
FillLayout layout = new FillLayout(SWT.HORIZONTAL);
GridData gridData = new GridData(SWT.FILL, SWT.BEGINNING, true,
false);
GridData gridData = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
gridData.horizontalAlignment = GridData.FILL;
setLayoutData(gridData);
setLayout(layout);

View file

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

View file

@ -9,11 +9,10 @@
# Contributors:
# Institute for Software - initial API and implementation
# IBM Corporation
# Google
# Tom Ball (Google)
###############################################################################
VariableName=Variable &name:
EnterVariableName=Enter a name for the new variable
CheckName=Check Name: {0}
NameAlreadyDefined=An element named ''{0}'' is already defined in this scope.
ExtractLocalVariable=Extract Local Variable
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
*/
public class IdentifierHelper {
/**
* @param identifier to check
* @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.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.MethodContext;
/**
* General class for common Node operations.
@ -107,12 +107,11 @@ public class NodeHelper {
return null;
}
public static MethodContext findMethodContext(IASTNode node, CRefactoringContext astCache,
public static MethodContext findMethodContext(IASTNode node, CRefactoringContext refactoringContext,
IProgressMonitor pm) throws CoreException {
IASTTranslationUnit translationUnit = node.getTranslationUnit();
boolean found = false;
MethodContext context = new MethodContext();
context.setType(MethodContext.ContextType.NONE);
IASTName name = null;
while (node != null && !found) {
node = node.getParent();
@ -124,13 +123,13 @@ public class NodeHelper {
name = CPPVisitor.findInnermostDeclarator(((IASTFunctionDefinition) node).getDeclarator()).getName();
found = true;
context.setType(MethodContext.ContextType.FUNCTION);
}
}
}
getMethodContexWithIndex(astCache, translationUnit, name, context, pm);
getMethodContexWithIndex(refactoringContext, translationUnit, name, context, pm);
return context;
}
private static void getMethodContexWithIndex(CRefactoringContext astCache,
private static void getMethodContexWithIndex(CRefactoringContext refactoringContext,
IASTTranslationUnit ast, IASTName name, MethodContext context, IProgressMonitor pm)
throws CoreException {
if (name instanceof ICPPASTQualifiedName) {
@ -140,7 +139,7 @@ public class NodeHelper {
IBinding binding = name.resolveBinding();
if (binding instanceof ICPPMethod) {
context.setType(MethodContext.ContextType.METHOD);
IIndex index = astCache.getIndex();
IIndex index = refactoringContext.getIndex();
IIndexName[] declarations = index.findDeclarations(binding);
if (declarations.length == 0) {
context.setMethodDeclarationName(name);
@ -153,7 +152,7 @@ public class NodeHelper {
IIndexFileLocation fileLocation = decl.getFile().getLocation();
ITranslationUnit locTu =
CoreModelUtil.findTranslationUnitForLocation(fileLocation, cProject);
astCache.getAST(locTu, pm);
ast2 = refactoringContext.getAST(locTu, pm);
}
IASTName declName = DeclarationFinder.findDeclarationInTranslationUnit(ast2, decl);
if (declName != null) {
@ -169,14 +168,13 @@ public class NodeHelper {
}
/**
* @deprecated Use #findMethodContext(IASTNode, RefactoringASTCache, IProgressMonitor pm)
* @deprecated Use #findMethodContext(IASTNode, CRefactoringContext, IProgressMonitor)
*/
@Deprecated
public static MethodContext findMethodContext(IASTNode node, IIndex index) throws CoreException {
IASTTranslationUnit translationUnit = node.getTranslationUnit();
boolean found = false;
MethodContext context = new MethodContext();
context.setType(MethodContext.ContextType.NONE);
IASTName name = null;
while (node != null && !found) {
node = node.getParent();
@ -191,15 +189,15 @@ public class NodeHelper {
}
}
if (index != null) {
getMethodContexWithIndex(index, translationUnit, context, name);
getMethodContextWithIndex(index, translationUnit, context, name);
} else {
getMethodContex(translationUnit, context, name);
getMethodContext(translationUnit, context, name);
}
return context;
}
@Deprecated
private static void getMethodContexWithIndex(IIndex index, IASTTranslationUnit translationUnit,
private static void getMethodContextWithIndex(IIndex index, IASTTranslationUnit translationUnit,
MethodContext context, IASTName name) throws CoreException {
IBinding bind = name.resolveBinding();
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) {
if (name instanceof ICPPASTQualifiedName) {
ICPPASTQualifiedName qname = (ICPPASTQualifiedName) name;

View file

@ -1,19 +1,16 @@
/*******************************************************************************
* 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
* 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:
* Markus Schorn - initial API and implementation
* Markus Schorn - initial API and implementation
* Sergey Prigogin (Google)
*******************************************************************************/
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.window.IShellProvider;
@ -23,7 +20,7 @@ import org.eclipse.cdt.core.model.IWorkingCopy;
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.
*/
@ -39,9 +36,8 @@ public class ExtractConstantAction extends RefactoringAction {
@Override
public void run(IShellProvider shellProvider, IWorkingCopy wc, ITextSelection selection) {
IResource res= wc.getResource();
if (res instanceof IFile) {
new ExtractConstantRefactoringRunner((IFile) res, selection, shellProvider, wc.getCProject()).run();
if (wc.getResource() != null) {
new ExtractConstantRefactoringRunner(wc, selection, shellProvider, wc.getCProject()).run();
}
}