1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-07-30 04:15:35 +02:00

Cosmetics.

This commit is contained in:
Sergey Prigogin 2010-11-17 01:40:04 +00:00
parent f32b1fefd0
commit 6a4bd1e7c1
7 changed files with 192 additions and 271 deletions

View file

@ -66,7 +66,7 @@ public abstract class CRefactoring extends Refactoring {
protected IFile file; protected IFile file;
protected Region region; protected Region region;
protected RefactoringStatus initStatus; protected RefactoringStatus initStatus;
protected IASTTranslationUnit unit; protected IASTTranslationUnit ast;
protected ICProject project; protected ICProject project;
private IIndex fIndex; private IIndex fIndex;
@ -227,8 +227,8 @@ public abstract class CRefactoring extends Refactoring {
if (file != null) { if (file != null) {
try { try {
subMonitor.subTask(Messages.Refactoring_PM_ParseTU); subMonitor.subTask(Messages.Refactoring_PM_ParseTU);
unit = loadTranslationUnit(file); ast = loadTranslationUnit(file);
if (unit == null) { if (ast == null) {
subMonitor.done(); subMonitor.done();
return false; return false;
} }
@ -264,7 +264,7 @@ public abstract class CRefactoring extends Refactoring {
protected boolean translationUnitHasProblem() { protected boolean translationUnitHasProblem() {
ProblemFinder pf = new ProblemFinder(initStatus); ProblemFinder pf = new ProblemFinder(initStatus);
unit.accept(pf); ast.accept(pf);
return pf.hasProblem(); return pf.hasProblem();
} }
@ -293,13 +293,13 @@ public abstract class CRefactoring extends Refactoring {
} }
public IASTTranslationUnit getUnit() { public IASTTranslationUnit getUnit() {
return unit; return ast;
} }
protected ArrayList<IASTName> findAllMarkedNames() { protected ArrayList<IASTName> findAllMarkedNames() {
final ArrayList<IASTName> namesVector = new ArrayList<IASTName>(); final ArrayList<IASTName> namesVector = new ArrayList<IASTName>();
unit.accept(new ASTVisitor() { ast.accept(new ASTVisitor() {
{ {
shouldVisitNames = true; shouldVisitNames = true;
} }

View file

@ -31,6 +31,7 @@ import org.eclipse.ltk.core.refactoring.RefactoringStatus;
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;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration; import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTDeclarator; import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
@ -45,7 +46,6 @@ 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;
import org.eclipse.cdt.core.dom.ast.IType; import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.dom.ast.cpp.CPPASTVisitor;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceDefinition; 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;
@ -74,10 +74,8 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.TranslationUnitHelper;
* postconditions and collecting/creating the modifications to the AST. * postconditions and collecting/creating the modifications to the AST.
* *
* @author Mirko Stocker * @author Mirko Stocker
*
*/ */
public class ExtractConstantRefactoring extends CRefactoring { public class ExtractConstantRefactoring extends CRefactoring {
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 = null;
@ -85,7 +83,7 @@ public class ExtractConstantRefactoring extends CRefactoring {
private final ExtractConstantInfo info; private final ExtractConstantInfo info;
public ExtractConstantRefactoring(IFile file, ISelection selection, ExtractConstantInfo info, ICProject proj){ public ExtractConstantRefactoring(IFile file, ISelection selection, ExtractConstantInfo info, ICProject proj) {
super(file,selection, null, proj); super(file,selection, null, proj);
this.info = info; this.info = info;
this.project = proj; this.project = proj;
@ -99,22 +97,22 @@ public class ExtractConstantRefactoring extends CRefactoring {
lockIndex(); lockIndex();
try { try {
RefactoringStatus status = super.checkInitialConditions(sm.newChild(6)); 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();
if(literalExpressionCollection.isEmpty()){ if (literalExpressionCollection.isEmpty()) {
initStatus.addFatalError(Messages.ExtractConstantRefactoring_LiteralMustBeSelected); initStatus.addFatalError(Messages.ExtractConstantRefactoring_LiteralMustBeSelected);
return initStatus; return initStatus;
} }
sm.worked(1); sm.worked(1);
if(isProgressMonitorCanceld(sm, initStatus)) return initStatus; if (isProgressMonitorCanceld(sm, initStatus)) return initStatus;
boolean oneMarked = region != null && isOneMarked(literalExpressionCollection, region); boolean oneMarked = region != null && isOneMarked(literalExpressionCollection, region);
if(!oneMarked){ if (!oneMarked) {
//No or more than one marked //No or more than one marked
if(target == null){ if (target == null) {
//No Selection found; //No Selection found;
initStatus.addFatalError(Messages.ExtractConstantRefactoring_NoLiteralSelected); initStatus.addFatalError(Messages.ExtractConstantRefactoring_NoLiteralSelected);
} else { } else {
@ -125,12 +123,12 @@ public class ExtractConstantRefactoring extends CRefactoring {
} }
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().length() == 0) {
info.setName(getDefaultName(target)); info.setName(getDefaultName(target));
} }
info.setMContext(NodeHelper.findMethodContext(target, getIndex())); info.setMContext(NodeHelper.findMethodContext(target, getIndex()));
@ -151,7 +149,7 @@ public class ExtractConstantRefactoring extends CRefactoring {
case IASTLiteralExpression.lk_char_constant: case IASTLiteralExpression.lk_char_constant:
case IASTLiteralExpression.lk_string_literal: case IASTLiteralExpression.lk_string_literal:
int beginIndex = 1; int beginIndex = 1;
if(nameString.startsWith("L")) { //$NON-NLS-1$ if (nameString.startsWith("L")) { //$NON-NLS-1$
beginIndex = 2; beginIndex = 2;
} }
final int len= nameString.length(); final int len= nameString.length();
@ -172,7 +170,7 @@ public class ExtractConstantRefactoring extends CRefactoring {
ArrayList<String>names = new ArrayList<String>(); ArrayList<String>names = new ArrayList<String>();
IASTFunctionDefinition funcDef = NodeHelper.findFunctionDefinitionInAncestors(target); IASTFunctionDefinition funcDef = NodeHelper.findFunctionDefinitionInAncestors(target);
ICPPASTCompositeTypeSpecifier comTypeSpec = getCompositeTypeSpecifier(funcDef); ICPPASTCompositeTypeSpecifier comTypeSpec = getCompositeTypeSpecifier(funcDef);
if(comTypeSpec != null) { if (comTypeSpec != null) {
for(IASTDeclaration dec : comTypeSpec.getMembers()) { for(IASTDeclaration dec : comTypeSpec.getMembers()) {
if (dec instanceof IASTSimpleDeclaration) { if (dec instanceof IASTSimpleDeclaration) {
IASTSimpleDeclaration simpDec = (IASTSimpleDeclaration) dec; IASTSimpleDeclaration simpDec = (IASTSimpleDeclaration) dec;
@ -186,17 +184,16 @@ public class ExtractConstantRefactoring extends CRefactoring {
} }
private ICPPASTCompositeTypeSpecifier getCompositeTypeSpecifier(IASTFunctionDefinition funcDef) { private ICPPASTCompositeTypeSpecifier getCompositeTypeSpecifier(IASTFunctionDefinition funcDef) {
if(funcDef != null) { if (funcDef != null) {
IBinding binding = funcDef.getDeclarator().getName().resolveBinding(); IBinding binding = funcDef.getDeclarator().getName().resolveBinding();
if (binding instanceof CPPMethod) { if (binding instanceof CPPMethod) {
CPPMethod methode = (CPPMethod) binding; CPPMethod methode = (CPPMethod) binding;
IASTNode[] declarations = methode.getDeclarations(); IASTNode[] declarations = methode.getDeclarations();
IASTNode decl; IASTNode decl;
if(declarations != null) { if (declarations != null) {
decl = declarations[0]; decl = declarations[0];
}else { } else {
decl = methode.getDefinition(); decl = methode.getDefinition();
} }
@ -214,18 +211,18 @@ public class ExtractConstantRefactoring extends CRefactoring {
if (target.getParent() instanceof IASTUnaryExpression) { if (target.getParent() instanceof IASTUnaryExpression) {
IASTUnaryExpression unary = (IASTUnaryExpression) target.getParent(); IASTUnaryExpression unary = (IASTUnaryExpression) target.getParent();
for (IASTLiteralExpression expression : literalExpressionCollection) { for (IASTLiteralExpression expression : literalExpressionCollection) {
if( target.getKind() == expression.getKind() if (target.getKind() == expression.getKind()
&& target.toString().equals( expression.toString() ) && target.toString().equals(expression.toString())
&& expression.getParent() instanceof IASTUnaryExpression && expression.getParent() instanceof IASTUnaryExpression
&& unary.getOperator() == ((IASTUnaryExpression)expression.getParent()).getOperator()) { && unary.getOperator() == ((IASTUnaryExpression)expression.getParent()).getOperator()) {
literalsToReplace.add( ((IASTUnaryExpression)expression.getParent()) ); literalsToReplace.add(((IASTUnaryExpression)expression.getParent()));
} }
} }
} else { } else {
for (IASTLiteralExpression expression : literalExpressionCollection) { for (IASTLiteralExpression expression : literalExpressionCollection) {
if( target.getKind() == expression.getKind() if (target.getKind() == expression.getKind()
&& target.toString().equals( expression.toString() ) ) { && target.toString().equals(expression.toString())) {
literalsToReplace.add( expression ); literalsToReplace.add(expression);
} }
} }
} }
@ -235,8 +232,8 @@ public class ExtractConstantRefactoring extends CRefactoring {
boolean oneMarked = false; boolean oneMarked = false;
for (IASTLiteralExpression expression : literalExpressionCollection) { for (IASTLiteralExpression expression : literalExpressionCollection) {
boolean isInSameFileSelection = SelectionHelper.isInSameFileSelection(textSelection, expression, file); boolean isInSameFileSelection = SelectionHelper.isInSameFileSelection(textSelection, expression, file);
if(isInSameFileSelection){ if (isInSameFileSelection) {
if(target == null) { if (target == null) {
target = expression; target = expression;
oneMarked = true; oneMarked = true;
} else { } else {
@ -250,22 +247,21 @@ public class ExtractConstantRefactoring extends CRefactoring {
private Collection<IASTLiteralExpression> findAllLiterals() { private Collection<IASTLiteralExpression> findAllLiterals() {
final Collection<IASTLiteralExpression> result = new ArrayList<IASTLiteralExpression>(); final Collection<IASTLiteralExpression> result = new ArrayList<IASTLiteralExpression>();
unit.accept(new CPPASTVisitor(){ 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);
} }
} }
return super.visit(expression); return super.visit(expression);
} }
}); });
return result; return result;
@ -273,57 +269,52 @@ public class ExtractConstantRefactoring extends CRefactoring {
@Override @Override
protected void collectModifications(IProgressMonitor pm, ModificationCollector collector) protected void collectModifications(IProgressMonitor pm, ModificationCollector collector)
throws CoreException, OperationCanceledException{ throws CoreException, OperationCanceledException{
try { try {
lockIndex(); lockIndex();
try { try {
MethodContext context = info.getMContext(); MethodContext context = info.getMContext();
Collection<IASTExpression> locLiteralsToReplace = new ArrayList<IASTExpression>(); Collection<IASTExpression> locLiteralsToReplace = new ArrayList<IASTExpression>();
if(context.getType() == MethodContext.ContextType.METHOD){ if (context.getType() == MethodContext.ContextType.METHOD) {
for (IASTExpression expression : literalsToReplace) { for (IASTExpression expression : literalsToReplace) {
MethodContext exprContext = NodeHelper.findMethodContext(expression, getIndex()); MethodContext exprContext = NodeHelper.findMethodContext(expression, getIndex());
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);
} }
} }
} }
} }
} else { } else {
for (IASTExpression expression : literalsToReplace) { for (IASTExpression expression : literalsToReplace) {
IPath path = new Path(expression.getContainingFilename()); IPath path = new Path(expression.getContainingFilename());
IFile expressionFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path); IFile expressionFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
//expressionFile may be null if the file is NOT in the workspace //expressionFile may be null if the file is NOT in the workspace
if( expressionFile != null && expressionFile.equals(file) ){ 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 = (ICPPASTCompositeTypeSpecifier) context.getMethodDeclaration().getParent();
AddDeclarationNodeToClassChange.createChange(classDefinition, info.getVisibility(), getConstNodesClass(constName), true, collector); AddDeclarationNodeToClassChange.createChange(classDefinition, info.getVisibility(), getConstNodesClass(constName), true, collector);
} else { } else {
IASTDeclaration nodes = getConstNodesGlobal(constName); IASTDeclaration nodes = getConstNodesGlobal(constName);
ASTRewrite rewriter = collector.rewriterForTranslationUnit(unit); ASTRewrite rewriter = collector.rewriterForTranslationUnit(ast);
rewriter.insertBefore(unit, TranslationUnitHelper.getFirstNode(unit), nodes, new TextEditGroup(Messages.ExtractConstantRefactoring_CreateConstant)); rewriter.insertBefore(ast, TranslationUnitHelper.getFirstNode(ast), nodes, new TextEditGroup(Messages.ExtractConstantRefactoring_CreateConstant));
} }
} } finally {
finally {
unlockIndex(); unlockIndex();
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -334,7 +325,8 @@ public class ExtractConstantRefactoring extends CRefactoring {
@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(), "Extract Constant Refactoring", "Create constant for " + target.getRawSignature(), arguments); //$NON-NLS-1$//$NON-NLS-2$ RefactoringDescriptor desc = new ExtractConstantRefactoringDescription(project.getProject().getName(),
"Extract Constant Refactoring", "Create constant for " + target.getRawSignature(), arguments); //$NON-NLS-1$//$NON-NLS-2$
return desc; return desc;
} }
@ -347,8 +339,8 @@ public class ExtractConstantRefactoring extends CRefactoring {
return arguments; return arguments;
} }
private void createLiteralToConstantChanges(String constName, Iterable<? extends IASTExpression> literals, ModificationCollector collector) { private void createLiteralToConstantChanges(String constName,
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 = new CPPASTIdExpression(new CPPASTName(constName.toCharArray()));
@ -356,12 +348,10 @@ public class ExtractConstantRefactoring extends CRefactoring {
} }
} }
private IASTSimpleDeclaration getConstNodes(String newName){ private IASTSimpleDeclaration getConstNodes(String newName) {
ICPPNodeFactory factory = ASTNodeFactoryFactory.getDefaultCPPNodeFactory(); ICPPNodeFactory factory = ASTNodeFactoryFactory.getDefaultCPPNodeFactory();
DeclarationGenerator generator = DeclarationGenerator.create(factory); DeclarationGenerator generator = DeclarationGenerator.create(factory);
IType type = target.getExpressionType(); IType type = target.getExpressionType();
IASTDeclSpecifier declSpec = generator.createDeclSpecFromType(type); IASTDeclSpecifier declSpec = generator.createDeclSpecFromType(type);
@ -386,10 +376,10 @@ public class ExtractConstantRefactoring extends CRefactoring {
return simple; return simple;
} }
private IASTDeclaration getConstNodesGlobal(String newName){ private IASTDeclaration getConstNodesGlobal(String newName) {
IASTSimpleDeclaration simple = getConstNodes(newName); IASTSimpleDeclaration simple = getConstNodes(newName);
INodeFactory factory= unit.getASTNodeFactory(); INodeFactory factory= ast.getASTNodeFactory();
if (factory instanceof ICPPNodeFactory) { if (factory instanceof ICPPNodeFactory) {
ICPPASTNamespaceDefinition namespace = ((ICPPNodeFactory) factory).newNamespaceDefinition(new CPPASTName()); ICPPASTNamespaceDefinition namespace = ((ICPPNodeFactory) factory).newNamespaceDefinition(new CPPASTName());
namespace.addDeclaration(simple); namespace.addDeclaration(simple);
@ -400,10 +390,9 @@ public class ExtractConstantRefactoring extends CRefactoring {
return simple; return simple;
} }
private IASTDeclaration getConstNodesClass(String newName){ private IASTDeclaration getConstNodesClass(String newName) {
IASTSimpleDeclaration simple = getConstNodes(newName); IASTSimpleDeclaration simple = getConstNodes(newName);
simple.getDeclSpecifier().setStorageClass(IASTDeclSpecifier.sc_static); simple.getDeclSpecifier().setStorageClass(IASTDeclSpecifier.sc_static);
return simple; return simple;
} }
} }

View file

@ -109,13 +109,11 @@ 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;
public class ExtractFunctionRefactoring extends CRefactoring { public class ExtractFunctionRefactoring extends CRefactoring {
public static final String ID = "org.eclipse.cdt.internal.ui.refactoring.extractfunction.ExtractFunctionRefactoring"; //$NON-NLS-1$ public static final String ID = "org.eclipse.cdt.internal.ui.refactoring.extractfunction.ExtractFunctionRefactoring"; //$NON-NLS-1$
static final Integer NULL_INTEGER = Integer.valueOf(0); static final Integer NULL_INTEGER = Integer.valueOf(0);
static final char[] ZERO= "0".toCharArray(); //$NON-NLS-1$ static final char[] ZERO= "0".toCharArray(); //$NON-NLS-1$
NodeContainer container; NodeContainer container;
final ExtractFunctionInformation info; final ExtractFunctionInformation info;
@ -151,7 +149,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
try { try {
RefactoringStatus status = super.checkInitialConditions(sm.newChild(6)); RefactoringStatus status = super.checkInitialConditions(sm.newChild(6));
if(status.hasError()) { if (status.hasError()) {
return status; return status;
} }
@ -189,8 +187,8 @@ public class ExtractFunctionRefactoring extends CRefactoring {
info.setInScopeDeclaredVariable(container.getAllDeclaredInScope().get(0)); info.setInScopeDeclaredVariable(container.getAllDeclaredInScope().get(0));
} }
extractedFunctionConstructionHelper = ExtractedFunctionConstructionHelper extractedFunctionConstructionHelper =
.createFor(container.getNodesToWrite()); ExtractedFunctionConstructionHelper.createFor(container.getNodesToWrite());
boolean isExtractExpression = container.getNodesToWrite().get(0) instanceof IASTExpression; boolean isExtractExpression = container.getNodesToWrite().get(0) instanceof IASTExpression;
info.setExtractExpression(isExtractExpression); info.setExtractExpression(isExtractExpression);
@ -205,14 +203,13 @@ public class ExtractFunctionRefactoring extends CRefactoring {
for (int i = 0; i < info.getAllUsedNames().size(); i++) { for (int i = 0; i < info.getAllUsedNames().size(); i++) {
if (!info.getAllUsedNames().get(i).isDeclarationInScope()) { if (!info.getAllUsedNames().get(i).isDeclarationInScope()) {
NameInformation name = info.getAllUsedNames().get(i); NameInformation name = info.getAllUsedNames().get(i);
if(!name.isReturnValue()) { if (!name.isReturnValue()) {
name.setUserSetIsReference(name.isReference()); name.setUserSetIsReference(name.isReference());
} }
} }
} }
sm.done(); sm.done();
} } finally {
finally {
unlockIndex(); unlockIndex();
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -225,18 +222,14 @@ public class ExtractFunctionRefactoring extends CRefactoring {
ArrayList<NameInformation> paras = container.getNames(); ArrayList<NameInformation> paras = container.getNames();
for (NameInformation name : paras) { for (NameInformation name : paras) {
int flag = CPPVariableReadWriteFlags.getReadWriteFlags(name int flag = CPPVariableReadWriteFlags.getReadWriteFlags(name.getName());
.getName());
if ((flag & PDOMName.WRITE_ACCESS) != 0) { if ((flag & PDOMName.WRITE_ACCESS) != 0) {
name.setWriteAccess(true); name.setWriteAccess(true);
} }
} }
} }
private void checkForNonExtractableStatements(NodeContainer cont, private void checkForNonExtractableStatements(NodeContainer cont, RefactoringStatus status) {
RefactoringStatus status) {
NonExtractableStmtFinder vis = new NonExtractableStmtFinder(); NonExtractableStmtFinder vis = new NonExtractableStmtFinder();
for (IASTNode node : cont.getNodesToWrite()) { for (IASTNode node : cont.getNodesToWrite()) {
node.accept(vis); node.accept(vis);
@ -257,17 +250,14 @@ public class ExtractFunctionRefactoring extends CRefactoring {
break; break;
} }
} }
} }
private ICPPASTFunctionDeclarator getDeclaration(IASTNode node) { private ICPPASTFunctionDeclarator getDeclaration(IASTNode node) {
while (node != null && !(node instanceof IASTFunctionDefinition)) { while (node != null && !(node instanceof IASTFunctionDefinition)) {
node = node.getParent(); node = node.getParent();
} }
if (node != null) { if (node != null) {
IASTFunctionDeclarator declarator = ((IASTFunctionDefinition) node) IASTFunctionDeclarator declarator = ((IASTFunctionDefinition) node).getDeclarator();
.getDeclarator();
if (declarator instanceof ICPPASTFunctionDeclarator) { if (declarator instanceof ICPPASTFunctionDeclarator) {
return (ICPPASTFunctionDeclarator) declarator; return (ICPPASTFunctionDeclarator) declarator;
} }
@ -318,8 +308,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
try { try {
lockIndex(); lockIndex();
try { try {
final IASTName astMethodName = new CPPASTName(info.getMethodName() final IASTName astMethodName = new CPPASTName(info.getMethodName().toCharArray());
.toCharArray());
MethodContext context = NodeHelper.findMethodContext(container.getNodesToWrite().get(0), getIndex()); MethodContext context = NodeHelper.findMethodContext(container.getNodesToWrite().get(0), getIndex());
@ -330,27 +319,24 @@ public class ExtractFunctionRefactoring extends CRefactoring {
// Create Method Definition // Create Method Definition
IASTNode firstNode = container.getNodesToWrite().get(0); IASTNode firstNode = container.getNodesToWrite().get(0);
IPath implPath = new Path(firstNode.getContainingFilename()); IPath implPath = new Path(firstNode.getContainingFilename());
final IFile implementationFile = ResourcesPlugin.getWorkspace() final IFile implementationFile =
.getRoot().getFileForLocation(implPath); ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(implPath);
createMethodDefinition(astMethodName, context, firstNode, createMethodDefinition(astMethodName, context, firstNode, implementationFile,
implementationFile, collector); collector);
createMethodCalls(astMethodName, implementationFile, context, collector); createMethodCalls(astMethodName, implementationFile, context, collector);
} } finally {
finally {
unlockIndex(); unlockIndex();
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} }
private void createMethodCalls(final IASTName astMethodName, private void createMethodCalls(final IASTName astMethodName,
final IFile implementationFile, MethodContext context, final IFile implementationFile, MethodContext context,
ModificationCollector collector) throws CoreException { ModificationCollector collector) throws CoreException {
String title; String title;
if (context.getType() == MethodContext.ContextType.METHOD) { if (context.getType() == MethodContext.ContextType.METHOD) {
title = Messages.ExtractFunctionRefactoring_CreateMethodCall; title = Messages.ExtractFunctionRefactoring_CreateMethodCall;
@ -361,11 +347,10 @@ public class ExtractFunctionRefactoring extends CRefactoring {
IASTNode methodCall = getMethodCall(astMethodName); IASTNode methodCall = getMethodCall(astMethodName);
IASTNode firstNodeToWrite = container.getNodesToWrite().get(0); IASTNode firstNodeToWrite = container.getNodesToWrite().get(0);
ASTRewrite rewriter = collector ASTRewrite rewriter = collector.rewriterForTranslationUnit(
.rewriterForTranslationUnit(firstNodeToWrite firstNodeToWrite.getTranslationUnit());
.getTranslationUnit());
TextEditGroup editGroup = new TextEditGroup(title); TextEditGroup editGroup = new TextEditGroup(title);
if(methodCall instanceof IASTDeclaration){ if (methodCall instanceof IASTDeclaration){
CPPASTDeclarationStatement declarationStatement = new CPPASTDeclarationStatement((IASTDeclaration) methodCall); CPPASTDeclarationStatement declarationStatement = new CPPASTDeclarationStatement((IASTDeclaration) methodCall);
methodCall = declarationStatement; methodCall = declarationStatement;
} }
@ -385,7 +370,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
private void insertCallintoTree(IASTNode methodCall, List<IASTNode> list, private void insertCallintoTree(IASTNode methodCall, List<IASTNode> list,
ASTRewrite rewriter, TextEditGroup editGroup) { ASTRewrite rewriter, TextEditGroup editGroup) {
IASTNode firstNode = list.get(0); IASTNode firstNode = list.get(0);
if(list.size() > 1 && firstNode.getParent() instanceof IASTBinaryExpression && if (list.size() > 1 && firstNode.getParent() instanceof IASTBinaryExpression &&
firstNode.getParent().getParent() instanceof IASTBinaryExpression) { firstNode.getParent().getParent() instanceof IASTBinaryExpression) {
IASTBinaryExpression parent = (IASTBinaryExpression) firstNode.getParent(); IASTBinaryExpression parent = (IASTBinaryExpression) firstNode.getParent();
IASTExpression leftSubTree = parent.getOperand1(); IASTExpression leftSubTree = parent.getOperand1();
@ -397,7 +382,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
newParentNode.setOperator(op); newParentNode.setOperator(op);
newParentNode.setOperand2((IASTExpression) methodCall); newParentNode.setOperand2((IASTExpression) methodCall);
rewriter.replace(rootBinExp, newParentNode, editGroup); rewriter.replace(rootBinExp, newParentNode, editGroup);
}else { } else {
rewriter.replace(firstNode, methodCall, editGroup); rewriter.replace(firstNode, methodCall, editGroup);
} }
} }
@ -412,7 +397,6 @@ public class ExtractFunctionRefactoring extends CRefactoring {
private void createMethodDefinition(final IASTName astMethodName, private void createMethodDefinition(final IASTName astMethodName,
MethodContext context, IASTNode firstNode, MethodContext context, IASTNode firstNode,
final IFile implementationFile, ModificationCollector collector) { final IFile implementationFile, ModificationCollector collector) {
IASTFunctionDefinition node = NodeHelper.findFunctionDefinitionInAncestors(firstNode); IASTFunctionDefinition node = NodeHelper.findFunctionDefinitionInAncestors(firstNode);
if (node != null) { if (node != null) {
String title; String title;
@ -434,14 +418,12 @@ public class ExtractFunctionRefactoring extends CRefactoring {
IASTSimpleDeclaration methodDeclaration = getDeclaration(collector, astMethodName); IASTSimpleDeclaration methodDeclaration = getDeclaration(collector, astMethodName);
AddDeclarationNodeToClassChange.createChange(classDeclaration, info AddDeclarationNodeToClassChange.createChange(classDeclaration, info.getVisibility(),
.getVisibility(), methodDeclaration, false, collector); methodDeclaration, false, collector);
} }
private void replaceSimilar(ModificationCollector collector, final IASTName astMethodName, private void replaceSimilar(ModificationCollector collector, final IASTName astMethodName,
final IFile implementationFile, final IFile implementationFile, final ContextType contextType) {
final ContextType contextType) {
// Find similar code // Find similar code
final List<IASTNode> nodesToRewriteWithoutComments = new LinkedList<IASTNode>(); final List<IASTNode> nodesToRewriteWithoutComments = new LinkedList<IASTNode>();
@ -460,14 +442,13 @@ public class ExtractFunctionRefactoring extends CRefactoring {
} }
if (!hasNameResolvingForSimilarError) { if (!hasNameResolvingForSimilarError) {
unit.accept(new SimilarFinderVisitor(this, collector, initTrail, implementationFile, ast.accept(new SimilarFinderVisitor(this, collector, initTrail, implementationFile,
astMethodName, nodesToRewriteWithoutComments, title)); astMethodName, nodesToRewriteWithoutComments, title));
} }
} }
protected Vector<IASTNode> getTrail(List<IASTNode> stmts) { protected Vector<IASTNode> getTrail(List<IASTNode> stmts) {
final Vector<IASTNode> trail = new Vector<IASTNode>(); final Vector<IASTNode> trail = new Vector<IASTNode>();
nameTrail = new HashMap<String, Integer>(); nameTrail = new HashMap<String, Integer>();
final Container<Integer> trailCounter = new Container<Integer>(NULL_INTEGER); final Container<Integer> trailCounter = new Container<Integer>(NULL_INTEGER);
@ -475,7 +456,6 @@ public class ExtractFunctionRefactoring extends CRefactoring {
node.accept(new CPPASTAllVisitor() { node.accept(new CPPASTAllVisitor() {
@Override @Override
public int visitAll(IASTNode node) { public int visitAll(IASTNode node) {
if (node instanceof IASTComment) { if (node instanceof IASTComment) {
// Visit Comment, but don't add them to the trail // Visit Comment, but don't add them to the trail
return super.visitAll(node); return super.visitAll(node);
@ -489,7 +469,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
trail.add(node); trail.add(node);
return super.visitAll(node); return super.visitAll(node);
} else { } else {
// Save Name Sequenz Number // Save Name Sequence Number
IASTName name = (IASTName) node; IASTName name = (IASTName) node;
TrailName trailName = new TrailName(name); TrailName trailName = new TrailName(name);
int actCount = trailCounter.getObject().intValue(); int actCount = trailCounter.getObject().intValue();
@ -530,7 +510,6 @@ public class ExtractFunctionRefactoring extends CRefactoring {
stmt.accept(new CPPASTAllVisitor() { stmt.accept(new CPPASTAllVisitor() {
@Override @Override
public int visitAll(IASTNode node) { public int visitAll(IASTNode node) {
int pos = trailPos.getObject().intValue(); int pos = trailPos.getObject().intValue();
if (trail.size() <= 0 || pos >= trail.size()) { if (trail.size() <= 0 || pos >= trail.size()) {
@ -552,7 +531,6 @@ public class ExtractFunctionRefactoring extends CRefactoring {
} else { } else {
return super.visitAll(node); return super.visitAll(node);
} }
} else { } else {
same.setObject(new Boolean(false)); same.setObject(new Boolean(false));
return PROCESS_ABORT; return PROCESS_ABORT;
@ -563,15 +541,14 @@ public class ExtractFunctionRefactoring extends CRefactoring {
return same.getObject().booleanValue(); return same.getObject().booleanValue();
} }
private boolean isMethodAllreadyDefined( private boolean isMethodAllreadyDefined(IASTSimpleDeclaration methodDeclaration,
IASTSimpleDeclaration methodDeclaration,
ICPPASTCompositeTypeSpecifier classDeclaration, IIndex index) { ICPPASTCompositeTypeSpecifier classDeclaration, IIndex index) {
TrailNodeEqualityChecker equalityChecker = new TrailNodeEqualityChecker( TrailNodeEqualityChecker equalityChecker = new TrailNodeEqualityChecker(
names, namesCounter, index); names, namesCounter, index);
IBinding bind = classDeclaration.getName().resolveBinding(); IBinding bind = classDeclaration.getName().resolveBinding();
IASTStandardFunctionDeclarator declarator = (IASTStandardFunctionDeclarator) methodDeclaration IASTStandardFunctionDeclarator declarator =
.getDeclarators()[0]; (IASTStandardFunctionDeclarator) methodDeclaration.getDeclarators()[0];
String name = new String(declarator.getName().toCharArray()); String name = new String(declarator.getName().toCharArray());
if (bind instanceof ICPPClassType) { if (bind instanceof ICPPClassType) {
ICPPClassType classBind = (ICPPClassType) bind; ICPPClassType classBind = (ICPPClassType) bind;
@ -587,23 +564,16 @@ public class ExtractFunctionRefactoring extends CRefactoring {
IParameter[] parameters = method.getParameters(); IParameter[] parameters = method.getParameters();
if (parameters.length == declarator.getParameters().length) { if (parameters.length == declarator.getParameters().length) {
for (int i = 0; i < parameters.length; i++) { for (int i = 0; i < parameters.length; i++) {
IASTName[] origParameterName = unit IASTName[] origParameterName = ast.getDeclarationsInAST(parameters[i]);
.getDeclarationsInAST(parameters[i]); IASTParameterDeclaration origParameter =
(IASTParameterDeclaration) origParameterName[0].getParent().getParent();
IASTParameterDeclaration origParameter = (IASTParameterDeclaration) origParameterName[0] IASTParameterDeclaration newParameter = declarator.getParameters()[i];
.getParent().getParent();
IASTParameterDeclaration newParameter = declarator
.getParameters()[i];
// if not the same break; // if not the same break;
if (!(equalityChecker.isEquals(origParameter if (!(equalityChecker.isEquals(origParameter.getDeclSpecifier(),
.getDeclSpecifier(), newParameter newParameter.getDeclSpecifier()) &&
.getDeclSpecifier()) && ASTHelper ASTHelper.samePointers(origParameter.getDeclarator().getPointerOperators(),
.samePointers(origParameter newParameter.getDeclarator().getPointerOperators(),
.getDeclarator()
.getPointerOperators(),
newParameter.getDeclarator()
.getPointerOperators(),
equalityChecker))) { equalityChecker))) {
break; break;
} }
@ -613,7 +583,6 @@ public class ExtractFunctionRefactoring extends CRefactoring {
} }
} }
} }
} }
} }
return false; return false;
@ -623,10 +592,9 @@ public class ExtractFunctionRefactoring extends CRefactoring {
private void addMethod(IASTName astMethodName, MethodContext context, private void addMethod(IASTName astMethodName, MethodContext context,
ASTRewrite rewriter, IASTNode insertpoint, TextEditGroup group) { ASTRewrite rewriter, IASTNode insertpoint, TextEditGroup group) {
ICPPASTQualifiedName qname = new CPPASTQualifiedName(); ICPPASTQualifiedName qname = new CPPASTQualifiedName();
if (context.getType() == ContextType.METHOD) { if (context.getType() == ContextType.METHOD) {
if(context.getMethodQName() != null) { if (context.getMethodQName() != null) {
for (int i = 0; i < (context.getMethodQName().getNames().length - 1); i++) { for (int i = 0; i < (context.getMethodQName().getNames().length - 1); i++) {
qname.addName(new CPPASTName(context.getMethodQName().getNames()[i].toCharArray())); qname.addName(new CPPASTName(context.getMethodQName().getNames()[i].toCharArray()));
} }
@ -635,7 +603,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
qname.addName(astMethodName); qname.addName(astMethodName);
IASTFunctionDefinition func = new CPPASTFunctionDefinition(); IASTFunctionDefinition func = new CPPASTFunctionDefinition();
func.setParent(unit); func.setParent(ast);
IASTDeclSpecifier returnType = getReturnType(); IASTDeclSpecifier returnType = getReturnType();
func.setDeclSpecifier(returnType); func.setDeclSpecifier(returnType);
@ -643,26 +611,24 @@ public class ExtractFunctionRefactoring extends CRefactoring {
IASTStandardFunctionDeclarator createdFunctionDeclarator = extractedFunctionConstructionHelper IASTStandardFunctionDeclarator createdFunctionDeclarator = extractedFunctionConstructionHelper
.createFunctionDeclarator(qname, info.getDeclarator(), info .createFunctionDeclarator(qname, info.getDeclarator(), info
.getReturnVariable(), container.getNodesToWrite(), info .getReturnVariable(), container.getNodesToWrite(), info
.getAllUsedNames(), unit.getASTNodeFactory()); .getAllUsedNames(), ast.getASTNodeFactory());
func.setDeclarator(createdFunctionDeclarator); func.setDeclarator(createdFunctionDeclarator);
IASTCompoundStatement compound = new CPPASTCompoundStatement(); IASTCompoundStatement compound = new CPPASTCompoundStatement();
func.setBody(compound); func.setBody(compound);
ASTRewrite subRW; ASTRewrite subRW;
if(insertpoint.getParent() instanceof ICPPASTTemplateDeclaration) { if (insertpoint.getParent() instanceof ICPPASTTemplateDeclaration) {
CPPASTTemplateDeclaration templateDeclaration = new CPPASTTemplateDeclaration(); CPPASTTemplateDeclaration templateDeclaration = new CPPASTTemplateDeclaration();
templateDeclaration.setParent(unit); templateDeclaration.setParent(ast);
for(ICPPASTTemplateParameter templateParameter : ((ICPPASTTemplateDeclaration) insertpoint.getParent()).getTemplateParameters()) { for (ICPPASTTemplateParameter templateParameter : ((ICPPASTTemplateDeclaration) insertpoint.getParent()).getTemplateParameters()) {
templateDeclaration.addTemplateParameter(templateParameter.copy()); templateDeclaration.addTemplateParameter(templateParameter.copy());
} }
templateDeclaration.setDeclaration(func); templateDeclaration.setDeclaration(func);
subRW = rewriter.insertBefore(insertpoint.getParent().getParent(), insertpoint.getParent(),
subRW = rewriter.insertBefore(insertpoint.getParent().getParent(), insertpoint.getParent(), templateDeclaration, group); templateDeclaration, group);
} else { } else {
subRW = rewriter.insertBefore(insertpoint.getParent(), insertpoint, func, group); subRW = rewriter.insertBefore(insertpoint.getParent(), insertpoint, func, group);
@ -690,7 +656,6 @@ public class ExtractFunctionRefactoring extends CRefactoring {
} }
subRW.insertBefore(compound, null, returnStmt, group); subRW.insertBefore(compound, null, returnStmt, group);
} }
} }
private IASTName newName(IASTName declaration) { private IASTName newName(IASTName declaration) {
@ -698,12 +663,10 @@ public class ExtractFunctionRefactoring extends CRefactoring {
} }
private IASTDeclSpecifier getReturnType() { private IASTDeclSpecifier getReturnType() {
IASTNode firstNodeToWrite = container.getNodesToWrite().get(0); IASTNode firstNodeToWrite = container.getNodesToWrite().get(0);
NameInformation returnVariable = info.getReturnVariable(); NameInformation returnVariable = info.getReturnVariable();
return extractedFunctionConstructionHelper.determineReturnType( return extractedFunctionConstructionHelper.determineReturnType(firstNodeToWrite, returnVariable);
firstNodeToWrite, returnVariable);
} }
protected IASTNode getMethodCall(IASTName astMethodName, protected IASTNode getMethodCall(IASTName astMethodName,
@ -721,8 +684,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
boolean theRetName = false; boolean theRetName = false;
for (NameInformation nameInfo : myContainer.getNames()) { for (NameInformation nameInfo : myContainer.getNames()) {
Integer trailSeqNumber = trailNameTable.get(nameInfo Integer trailSeqNumber = trailNameTable.get(nameInfo.getDeclaration().getRawSignature());
.getDeclaration().getRawSignature());
String orgName = null; String orgName = null;
for (Entry<String, Integer> entry : similarNameTable.entrySet()) { for (Entry<String, Integer> entry : similarNameTable.entrySet()) {
if (entry.getValue().equals(trailSeqNumber)) { if (entry.getValue().equals(trailSeqNumber)) {
@ -736,8 +698,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
if (orgName != null) { if (orgName != null) {
boolean found = false; boolean found = false;
for (NameInformation simNameInfo : mySimilarContainer for (NameInformation simNameInfo : mySimilarContainer.getNames()) {
.getNames()) {
if (orgName.equals(simNameInfo.getDeclaration() if (orgName.equals(simNameInfo.getDeclaration()
.getRawSignature())) { .getRawSignature())) {
addAParameterIfPossible(args, declarations, addAParameterIfPossible(args, declarations,
@ -746,9 +707,8 @@ public class ExtractFunctionRefactoring extends CRefactoring {
if (theRetName) { if (theRetName) {
theRetName = false; theRetName = false;
retName = new CPPASTName(simNameInfo retName = new CPPASTName(
.getDeclaration().getRawSignature() simNameInfo.getDeclaration().getRawSignature().toCharArray());
.toCharArray());
} }
} }
} }
@ -792,7 +752,6 @@ public class ExtractFunctionRefactoring extends CRefactoring {
} }
IASTName retname = newName(info.getReturnVariable().getName()); IASTName retname = newName(info.getReturnVariable().getName());
return getReturnAssignment(stmt, callExpression, retname); return getReturnAssignment(stmt, callExpression, retname);
} }
private IASTNode getReturnAssignment(IASTExpressionStatement stmt, private IASTNode getReturnAssignment(IASTExpressionStatement stmt,
@ -808,8 +767,7 @@ public class ExtractFunctionRefactoring extends CRefactoring {
declarator.setName(retname); declarator.setName(retname);
for (IASTPointerOperator pointer : orgDecl.getDeclarators()[0] for (IASTPointerOperator pointer : orgDecl.getDeclarators()[0].getPointerOperators()) {
.getPointerOperators()) {
declarator.addPointerOperator(pointer.copy()); declarator.addPointerOperator(pointer.copy());
} }
@ -834,19 +792,17 @@ public class ExtractFunctionRefactoring extends CRefactoring {
private IASTNode getReturnAssignment(IASTExpressionStatement stmt, private IASTNode getReturnAssignment(IASTExpressionStatement stmt,
IASTExpression callExpression) { IASTExpression callExpression) {
IASTNode node = container.getNodesToWrite().get(0); IASTNode node = container.getNodesToWrite().get(0);
return extractedFunctionConstructionHelper.createReturnAssignment(node, return extractedFunctionConstructionHelper.createReturnAssignment(node,
stmt, callExpression); stmt, callExpression);
} }
private IASTSimpleDeclaration getDeclaration(IASTName name) { private IASTSimpleDeclaration getDeclaration(IASTName name) {
IASTSimpleDeclaration simpleDecl = new CPPASTSimpleDeclaration(); IASTSimpleDeclaration simpleDecl = new CPPASTSimpleDeclaration();
IASTStandardFunctionDeclarator declarator = extractedFunctionConstructionHelper IASTStandardFunctionDeclarator declarator =
.createFunctionDeclarator(name, info.getDeclarator(), info extractedFunctionConstructionHelper.createFunctionDeclarator(name,
.getReturnVariable(), container.getNodesToWrite(), info info.getDeclarator(), info.getReturnVariable(),
.getAllUsedNames(), unit.getASTNodeFactory()); container.getNodesToWrite(), info.getAllUsedNames(), ast.getASTNodeFactory());
simpleDecl.addDeclarator(declarator); simpleDecl.addDeclarator(declarator);
return simpleDecl; return simpleDecl;
} }
@ -854,21 +810,21 @@ public class ExtractFunctionRefactoring extends CRefactoring {
private IASTSimpleDeclaration getDeclaration(ModificationCollector collector,IASTName name) { private IASTSimpleDeclaration getDeclaration(ModificationCollector collector,IASTName name) {
IASTDeclSpecifier declSpec = getReturnType(); IASTDeclSpecifier declSpec = getReturnType();
IASTSimpleDeclaration simpleDecl = factory.newSimpleDeclaration(declSpec); IASTSimpleDeclaration simpleDecl = factory.newSimpleDeclaration(declSpec);
if(info.isVirtual() && declSpec instanceof ICPPASTDeclSpecifier) { if (info.isVirtual() && declSpec instanceof ICPPASTDeclSpecifier) {
((ICPPASTDeclSpecifier)declSpec).setVirtual(true); ((ICPPASTDeclSpecifier)declSpec).setVirtual(true);
} }
simpleDecl.setParent(unit); simpleDecl.setParent(ast);
IASTStandardFunctionDeclarator declarator = extractedFunctionConstructionHelper IASTStandardFunctionDeclarator declarator = extractedFunctionConstructionHelper
.createFunctionDeclarator(name, info.getDeclarator(), info .createFunctionDeclarator(name, info.getDeclarator(), info
.getReturnVariable(), container.getNodesToWrite(), info .getReturnVariable(), container.getNodesToWrite(), info
.getAllUsedNames(), unit.getASTNodeFactory()); .getAllUsedNames(), ast.getASTNodeFactory());
simpleDecl.addDeclarator(declarator); simpleDecl.addDeclarator(declarator);
return simpleDecl; return simpleDecl;
} }
private NodeContainer findExtractableNodes() { private NodeContainer findExtractableNodes() {
final NodeContainer container = new NodeContainer(); final NodeContainer container = new NodeContainer();
unit.accept(new ASTVisitor() { ast.accept(new ASTVisitor() {
{ {
shouldVisitStatements = true; shouldVisitStatements = true;
shouldVisitExpressions = true; shouldVisitExpressions = true;
@ -933,5 +889,4 @@ public class ExtractFunctionRefactoring extends CRefactoring {
arguments.put(ExtractFunctionRefactoringDescription.REPLACE_DUBLICATES, Boolean.toString(info.isReplaceDuplicates())); arguments.put(ExtractFunctionRefactoringDescription.REPLACE_DUBLICATES, Boolean.toString(info.isReplaceDuplicates()));
return arguments; return arguments;
} }
} }

View file

@ -224,7 +224,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring {
private NodeContainer findAllExpressions() { private NodeContainer findAllExpressions() {
final NodeContainer container = new NodeContainer(); final NodeContainer container = new NodeContainer();
unit.accept(new ASTVisitor() { ast.accept(new ASTVisitor() {
{ {
shouldVisitExpressions = true; shouldVisitExpressions = true;
} }
@ -255,7 +255,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring {
IASTStatement declInsertPoint = getParentStatement(target); IASTStatement declInsertPoint = getParentStatement(target);
IASTDeclarationStatement declaration = getVariableNodes(variableName); IASTDeclarationStatement declaration = getVariableNodes(variableName);
declaration.setParent(declInsertPoint.getParent()); declaration.setParent(declInsertPoint.getParent());
ASTRewrite rewriter = collector.rewriterForTranslationUnit(unit); ASTRewrite rewriter = collector.rewriterForTranslationUnit(ast);
rewriter.insertBefore(declInsertPoint.getParent(), declInsertPoint, declaration, editGroup); rewriter.insertBefore(declInsertPoint.getParent(), declInsertPoint, declaration, editGroup);
// Replace target with reference to temporary variable // Replace target with reference to temporary variable
@ -280,7 +280,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring {
} }
private IASTDeclarationStatement getVariableNodes(String newName) { private IASTDeclarationStatement getVariableNodes(String newName) {
INodeFactory factory = this.unit.getASTNodeFactory(); INodeFactory factory = this.ast.getASTNodeFactory();
IASTSimpleDeclaration simple = factory.newSimpleDeclaration(null); IASTSimpleDeclaration simple = factory.newSimpleDeclaration(null);

View file

@ -55,7 +55,6 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
/** /**
* @author Thomas Corbat * @author Thomas Corbat
*
*/ */
public class GenerateGettersAndSettersRefactoring extends CRefactoring { public class GenerateGettersAndSettersRefactoring extends CRefactoring {
@ -73,10 +72,9 @@ public class GenerateGettersAndSettersRefactoring extends CRefactoring {
@Override @Override
public int visit(IASTDeclSpecifier declSpec) { public int visit(IASTDeclSpecifier declSpec) {
if (declSpec instanceof IASTCompositeTypeSpecifier) { if (declSpec instanceof IASTCompositeTypeSpecifier) {
IASTFileLocation loc = declSpec.getFileLocation(); IASTFileLocation loc = declSpec.getFileLocation();
if(start > loc.getNodeOffset() && start < loc.getNodeOffset()+ loc.getNodeLength()) { if (start > loc.getNodeOffset() && start < loc.getNodeOffset()+ loc.getNodeLength()) {
container.setObject((IASTCompositeTypeSpecifier) declSpec); container.setObject((IASTCompositeTypeSpecifier) declSpec);
return ASTVisitor.PROCESS_ABORT; return ASTVisitor.PROCESS_ABORT;
} }
@ -99,22 +97,18 @@ public class GenerateGettersAndSettersRefactoring extends CRefactoring {
SubMonitor sm = SubMonitor.convert(pm, 10); SubMonitor sm = SubMonitor.convert(pm, 10);
RefactoringStatus status = super.checkInitialConditions(sm.newChild(6)); RefactoringStatus status = super.checkInitialConditions(sm.newChild(6));
if(status.hasError()) { if (status.hasError()) {
return status; return status;
} }
if(!initStatus.hasFatalError()) { if (!initStatus.hasFatalError()) {
initRefactoring(pm); initRefactoring(pm);
if (context.existingFields.size() == 0) {
if(context.existingFields.size() == 0) {
initStatus.addFatalError(Messages.GenerateGettersAndSettersRefactoring_NoFields); initStatus.addFatalError(Messages.GenerateGettersAndSettersRefactoring_NoFields);
} }
} }
return initStatus; return initStatus;
} }
@Override @Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException,
@ -123,14 +117,14 @@ public class GenerateGettersAndSettersRefactoring extends CRefactoring {
try { try {
lockIndex(); lockIndex();
finalStatus = super.checkFinalConditions(pm); finalStatus = super.checkFinalConditions(pm);
if(!context.isImplementationInHeader()) { if (!context.isImplementationInHeader()) {
definitionInsertLocation = findInsertLocation(); definitionInsertLocation = findInsertLocation();
if(file.equals(definitionInsertLocation.getInsertFile())) { if (file.equals(definitionInsertLocation.getInsertFile())) {
finalStatus.addInfo(Messages.GenerateGettersAndSettersRefactoring_NoImplFile); finalStatus.addInfo(Messages.GenerateGettersAndSettersRefactoring_NoImplFile);
} }
} }
} catch (InterruptedException e) {} } catch (InterruptedException e) {
finally { } finally {
unlockIndex(); unlockIndex();
} }
return finalStatus; return finalStatus;
@ -140,14 +134,14 @@ public class GenerateGettersAndSettersRefactoring extends CRefactoring {
loadTranslationUnit(initStatus, pm); loadTranslationUnit(initStatus, pm);
context.selectedName = getSelectedName(); context.selectedName = getSelectedName();
IASTCompositeTypeSpecifier compositeTypeSpecifier = null; IASTCompositeTypeSpecifier compositeTypeSpecifier = null;
if(context.selectedName != null) { if (context.selectedName != null) {
compositeTypeSpecifier = getCompositeTypeSpecifier(context.selectedName); compositeTypeSpecifier = getCompositeTypeSpecifier(context.selectedName);
}else { } else {
compositeTypeSpecifier = findCurrentCompositeTypeSpecifier(); compositeTypeSpecifier = findCurrentCompositeTypeSpecifier();
} }
if(compositeTypeSpecifier != null) { if (compositeTypeSpecifier != null) {
findDeclarations(compositeTypeSpecifier); findDeclarations(compositeTypeSpecifier);
}else { } else {
initStatus.addFatalError(Messages.GenerateGettersAndSettersRefactoring_NoCassDefFound); initStatus.addFatalError(Messages.GenerateGettersAndSettersRefactoring_NoCassDefFound);
} }
} }
@ -155,7 +149,7 @@ public class GenerateGettersAndSettersRefactoring extends CRefactoring {
private IASTCompositeTypeSpecifier findCurrentCompositeTypeSpecifier() { private IASTCompositeTypeSpecifier findCurrentCompositeTypeSpecifier() {
final int start = region.getOffset(); final int start = region.getOffset();
Container<IASTCompositeTypeSpecifier> container = new Container<IASTCompositeTypeSpecifier>(); Container<IASTCompositeTypeSpecifier> container = new Container<IASTCompositeTypeSpecifier>();
unit.accept(new CompositeTypeSpecFinder(start, container)); ast.accept(new CompositeTypeSpecFinder(start, container));
return container.getObject(); return container.getObject();
} }
@ -176,9 +170,7 @@ public class GenerateGettersAndSettersRefactoring extends CRefactoring {
} }
protected void findDeclarations(IASTCompositeTypeSpecifier compositeTypeSpecifier) { protected void findDeclarations(IASTCompositeTypeSpecifier compositeTypeSpecifier) {
compositeTypeSpecifier.accept(new ASTVisitor() { compositeTypeSpecifier.accept(new ASTVisitor() {
{ {
shouldVisitDeclarations = true; shouldVisitDeclarations = true;
} }
@ -198,7 +190,7 @@ public class GenerateGettersAndSettersRefactoring extends CRefactoring {
if ((innermostDeclarator instanceof IASTFunctionDeclarator)) { if ((innermostDeclarator instanceof IASTFunctionDeclarator)) {
context.existingFunctionDeclarations.add(fieldDeclaration); context.existingFunctionDeclarations.add(fieldDeclaration);
} else { } else {
if(SelectionHelper.isInSameFile(fieldDeclaration, file)){ if (SelectionHelper.isInSameFile(fieldDeclaration, file)) {
context.existingFields.add(fieldDeclaration); context.existingFields.add(fieldDeclaration);
} }
} }
@ -218,31 +210,32 @@ public class GenerateGettersAndSettersRefactoring extends CRefactoring {
} }
@Override @Override
protected void collectModifications(IProgressMonitor pm,ModificationCollector collector) throws CoreException, OperationCanceledException { protected void collectModifications(IProgressMonitor pm,ModificationCollector collector)
throws CoreException, OperationCanceledException {
try { try {
lockIndex(); lockIndex();
ArrayList<IASTNode> getterAndSetters = new ArrayList<IASTNode>(); ArrayList<IASTNode> getterAndSetters = new ArrayList<IASTNode>();
ArrayList<IASTFunctionDefinition> definitions = new ArrayList<IASTFunctionDefinition>(); ArrayList<IASTFunctionDefinition> definitions = new ArrayList<IASTFunctionDefinition>();
for(GetterSetterInsertEditProvider currentProvider : context.selectedFunctions){ for (GetterSetterInsertEditProvider currentProvider : context.selectedFunctions) {
if(context.isImplementationInHeader()) { if (context.isImplementationInHeader()) {
getterAndSetters.add(currentProvider.getFunctionDefinition(false)); getterAndSetters.add(currentProvider.getFunctionDefinition(false));
}else { } else {
getterAndSetters.add(currentProvider.getFunctionDeclaration()); getterAndSetters.add(currentProvider.getFunctionDeclaration());
definitions.add(currentProvider.getFunctionDefinition(true)); definitions.add(currentProvider.getFunctionDefinition(true));
} }
} }
if(!context.isImplementationInHeader()) { if (!context.isImplementationInHeader()) {
addDefinition(collector, definitions); addDefinition(collector, definitions);
} }
ICPPASTCompositeTypeSpecifier classDefinition = (ICPPASTCompositeTypeSpecifier) context.existingFields.get(context.existingFields.size()-1).getParent(); ICPPASTCompositeTypeSpecifier classDefinition =
(ICPPASTCompositeTypeSpecifier) context.existingFields.get(context.existingFields.size() - 1).getParent();
AddDeclarationNodeToClassChange.createChange(classDefinition, VisibilityEnum.v_public, getterAndSetters, false, collector); AddDeclarationNodeToClassChange.createChange(classDefinition, VisibilityEnum.v_public,
} catch (InterruptedException e) {} getterAndSetters, false, collector);
finally { } catch (InterruptedException e) {
} finally {
unlockIndex(); unlockIndex();
} }
} }
private void addDefinition(ModificationCollector collector, ArrayList<IASTFunctionDefinition> definitions) private void addDefinition(ModificationCollector collector, ArrayList<IASTFunctionDefinition> definitions)
@ -269,8 +262,8 @@ public class GenerateGettersAndSettersRefactoring extends CRefactoring {
private InsertLocation findInsertLocation() throws CoreException { private InsertLocation findInsertLocation() throws CoreException {
IASTSimpleDeclaration decl = context.existingFields.get(0); IASTSimpleDeclaration decl = context.existingFields.get(0);
InsertLocation insertLocation = MethodDefinitionInsertLocationFinder.find(decl.getFileLocation(),
InsertLocation insertLocation = MethodDefinitionInsertLocationFinder.find(decl.getFileLocation(), decl.getParent(), file); decl.getParent(), file);
if (!insertLocation.hasFile() || NodeHelper.isContainedInTemplateDeclaration(decl)) { if (!insertLocation.hasFile() || NodeHelper.isContainedInTemplateDeclaration(decl)) {
insertLocation.setInsertFile(file); insertLocation.setInsertFile(file);
@ -278,7 +271,6 @@ public class GenerateGettersAndSettersRefactoring extends CRefactoring {
} }
return insertLocation; return insertLocation;
} }
@Override @Override

View file

@ -59,10 +59,8 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
/** /**
* @author Guido Zgraggen IFS * @author Guido Zgraggen IFS
*
*/ */
public class HideMethodRefactoring extends CRefactoring { public class HideMethodRefactoring extends CRefactoring {
public static final String ID = "org.eclipse.cdt.internal.ui.refactoring.hidemethod.HideMethodRefactoring"; //$NON-NLS-1$ public static final String ID = "org.eclipse.cdt.internal.ui.refactoring.hidemethod.HideMethodRefactoring"; //$NON-NLS-1$
private IASTName methodToHide; private IASTName methodToHide;
@ -82,11 +80,11 @@ public class HideMethodRefactoring extends CRefactoring {
try { try {
super.checkInitialConditions(sm.newChild(6)); super.checkInitialConditions(sm.newChild(6));
if(initStatus.hasFatalError()){ if (initStatus.hasFatalError()) {
return initStatus; return initStatus;
} }
if(isProgressMonitorCanceld(sm, initStatus)) return initStatus; if (isProgressMonitorCanceld(sm, initStatus)) return initStatus;
IASTName name; IASTName name;
ArrayList<IASTName> names = findAllMarkedNames(); ArrayList<IASTName> names = findAllMarkedNames();
@ -96,11 +94,11 @@ public class HideMethodRefactoring extends CRefactoring {
} }
name = names.get(names.size()-1); name = names.get(names.size()-1);
sm.worked(1); sm.worked(1);
if(isProgressMonitorCanceld(sm, initStatus)) return initStatus; if (isProgressMonitorCanceld(sm, initStatus)) return initStatus;
declData = DeclarationFinder.getDeclaration(name, getIndex()); declData = DeclarationFinder.getDeclaration(name, getIndex());
if(declData == null || declData.name == null) { if (declData == null || declData.name == null) {
initStatus.addFatalError(Messages.HideMethodRefactoring_NoMethodNameSelected); initStatus.addFatalError(Messages.HideMethodRefactoring_NoMethodNameSelected);
return initStatus; return initStatus;
} }
@ -108,34 +106,34 @@ public class HideMethodRefactoring extends CRefactoring {
methodToHide = declData.name; methodToHide = declData.name;
sm.worked(1); sm.worked(1);
methodToHideDecl = NodeHelper.findSimpleDeclarationInParents(methodToHide); methodToHideDecl = NodeHelper.findSimpleDeclarationInParents(methodToHide);
if(methodToHideDecl == null) { if (methodToHideDecl == null) {
initStatus.addFatalError(Messages.HideMethodRefactoring_CanOnlyHideMethods); initStatus.addFatalError(Messages.HideMethodRefactoring_CanOnlyHideMethods);
return initStatus; return initStatus;
} }
if(!(methodToHideDecl.getParent() instanceof ICPPASTCompositeTypeSpecifier)) { if (!(methodToHideDecl.getParent() instanceof ICPPASTCompositeTypeSpecifier)) {
methodToHideDecl = NodeHelper.findFunctionDefinitionInAncestors(methodToHide); methodToHideDecl = NodeHelper.findFunctionDefinitionInAncestors(methodToHide);
} }
if(isProgressMonitorCanceld(sm, initStatus)) return initStatus; if (isProgressMonitorCanceld(sm, initStatus)) return initStatus;
sm.worked(1); sm.worked(1);
if(methodToHideDecl instanceof IASTFunctionDefinition) { if (methodToHideDecl instanceof IASTFunctionDefinition) {
IASTDeclarator declarator = ((IASTFunctionDefinition)methodToHideDecl).getDeclarator(); IASTDeclarator declarator = ((IASTFunctionDefinition)methodToHideDecl).getDeclarator();
if(CPPVisitor.findInnermostDeclarator(declarator).getName().getRawSignature().equals(name.getRawSignature())) { if (CPPVisitor.findInnermostDeclarator(declarator).getName().getRawSignature().equals(name.getRawSignature())) {
if (!(declarator instanceof IASTFunctionDeclarator)) { if (!(declarator instanceof IASTFunctionDeclarator)) {
initStatus.addFatalError(Messages.HideMethodRefactoring_CanOnlyHideMethods); initStatus.addFatalError(Messages.HideMethodRefactoring_CanOnlyHideMethods);
return initStatus; return initStatus;
} }
} }
}else if (methodToHideDecl instanceof IASTSimpleDeclaration) { } else if (methodToHideDecl instanceof IASTSimpleDeclaration) {
for(IASTDeclarator declarator : ((IASTSimpleDeclaration) methodToHideDecl).getDeclarators()) { for(IASTDeclarator declarator : ((IASTSimpleDeclaration) methodToHideDecl).getDeclarators()) {
if(declarator.getName().getRawSignature().equals(name.getRawSignature())) { if (declarator.getName().getRawSignature().equals(name.getRawSignature())) {
if (!(declarator instanceof IASTFunctionDeclarator)) { if (!(declarator instanceof IASTFunctionDeclarator)) {
initStatus.addFatalError(Messages.HideMethodRefactoring_CanOnlyHideMethods); initStatus.addFatalError(Messages.HideMethodRefactoring_CanOnlyHideMethods);
return initStatus; return initStatus;
} }
} }
} }
}else { } else {
initStatus.addFatalError(Messages.HideMethodRefactoring_CanOnlyHideMethods); initStatus.addFatalError(Messages.HideMethodRefactoring_CanOnlyHideMethods);
return initStatus; return initStatus;
} }
@ -143,16 +141,15 @@ public class HideMethodRefactoring extends CRefactoring {
sm.worked(1); sm.worked(1);
IASTCompositeTypeSpecifier classNode = NodeHelper.findClassInAncestors(methodToHide); IASTCompositeTypeSpecifier classNode = NodeHelper.findClassInAncestors(methodToHide);
if(classNode == null) { if (classNode == null) {
initStatus.addError(Messages.HideMethodRefactoring_EnclosingClassNotFound); initStatus.addError(Messages.HideMethodRefactoring_EnclosingClassNotFound);
} }
if(checkIfPrivate(classNode, methodToHideDecl)) { if (checkIfPrivate(classNode, methodToHideDecl)) {
initStatus.addError(Messages.HideMethodRefactoring_IsAlreadyPrivate); initStatus.addError(Messages.HideMethodRefactoring_IsAlreadyPrivate);
} }
sm.done(); sm.done();
} } finally {
finally {
unlockIndex(); unlockIndex();
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -163,23 +160,22 @@ public class HideMethodRefactoring extends CRefactoring {
private boolean checkIfPrivate(IASTCompositeTypeSpecifier classNode, IASTDeclaration decl) { private boolean checkIfPrivate(IASTCompositeTypeSpecifier classNode, IASTDeclaration decl) {
IASTDeclaration[] members = classNode.getMembers(); IASTDeclaration[] members = classNode.getMembers();
int currentVisibility = ICPPASTVisibilityLabel.v_private; int currentVisibility = ICPPASTVisibilityLabel.v_private;
if(IASTCompositeTypeSpecifier.k_struct == classNode.getKey()) { if (IASTCompositeTypeSpecifier.k_struct == classNode.getKey()) {
currentVisibility = ICPPASTVisibilityLabel.v_public; currentVisibility = ICPPASTVisibilityLabel.v_public;
} }
for (IASTDeclaration declaration : members) { for (IASTDeclaration declaration : members) {
if(declaration instanceof ICPPASTVisibilityLabel){ if (declaration instanceof ICPPASTVisibilityLabel) {
currentVisibility =((ICPPASTVisibilityLabel) declaration).getVisibility(); currentVisibility =((ICPPASTVisibilityLabel) declaration).getVisibility();
} }
if (declaration != null) { if (declaration != null) {
if(decl == declaration) { if (decl == declaration) {
break; break;
} }
} }
} }
if(ICPPASTVisibilityLabel.v_private == currentVisibility) { if (ICPPASTVisibilityLabel.v_private == currentVisibility) {
return true; return true;
} }
return false; return false;
@ -196,12 +192,12 @@ public class HideMethodRefactoring extends CRefactoring {
for(IIndexName pdomref : declData.allNamesPDom) { for(IIndexName pdomref : declData.allNamesPDom) {
declData.filename = pdomref.getFileLocation().getFileName(); declData.filename = pdomref.getFileLocation().getFileName();
if(pdomref instanceof PDOMName) { if (pdomref instanceof PDOMName) {
PDOMName pdomName = (PDOMName)pdomref; PDOMName pdomName = (PDOMName)pdomref;
if(pdomName.isDeclaration()) { if (pdomName.isDeclaration()) {
continue; continue;
} }
if(pdomName.isDefinition()) { if (pdomName.isDefinition()) {
continue; continue;
} }
} }
@ -211,7 +207,7 @@ public class HideMethodRefactoring extends CRefactoring {
IASTFunctionDeclarator funcDec = findEnclosingFunction(expName); IASTFunctionDeclarator funcDec = findEnclosingFunction(expName);
IASTCompositeTypeSpecifier encClass2; IASTCompositeTypeSpecifier encClass2;
if(funcDec == null) { if (funcDec == null) {
encClass2 = NodeHelper.findClassInAncestors(expName); encClass2 = NodeHelper.findClassInAncestors(expName);
} }
else { else {
@ -220,15 +216,14 @@ public class HideMethodRefactoring extends CRefactoring {
IASTCompositeTypeSpecifier encClass = NodeHelper.findClassInAncestors(methodToHide); IASTCompositeTypeSpecifier encClass = NodeHelper.findClassInAncestors(methodToHide);
if(!NodeHelper.isSameNode(encClass, encClass2)) { if (!NodeHelper.isSameNode(encClass, encClass2)) {
finalConditions.addWarning(Messages.HideMethodRefactoring_HasExternalReferences); finalConditions.addWarning(Messages.HideMethodRefactoring_HasExternalReferences);
break; break;
} }
} }
return finalConditions; return finalConditions;
} } finally {
finally {
unlockIndex(); unlockIndex();
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -239,26 +234,26 @@ public class HideMethodRefactoring extends CRefactoring {
private IASTFunctionDeclarator findEnclosingFunction(IASTNode node) throws CoreException { private IASTFunctionDeclarator findEnclosingFunction(IASTNode node) throws CoreException {
IASTCompoundStatement compStat = NodeHelper.findCompoundStatementInAncestors(node); IASTCompoundStatement compStat = NodeHelper.findCompoundStatementInAncestors(node);
if(compStat == null) { if (compStat == null) {
return null; return null;
} }
IASTNode parent = compStat.getParent(); IASTNode parent = compStat.getParent();
if(parent instanceof IASTFunctionDefinition) { if (parent instanceof IASTFunctionDefinition) {
IASTDeclarator declarator = ((IASTFunctionDefinition)parent).getDeclarator(); IASTDeclarator declarator = ((IASTFunctionDefinition)parent).getDeclarator();
IASTName declaratorName = getLastName(CPPVisitor.findInnermostDeclarator(declarator)); IASTName declaratorName = getLastName(CPPVisitor.findInnermostDeclarator(declarator));
DeclarationFinderDO data = DeclarationFinder.getDeclaration(declaratorName, getIndex()); DeclarationFinderDO data = DeclarationFinder.getDeclaration(declaratorName, getIndex());
if(data == null || data.name == null) { if (data == null || data.name == null) {
return null; return null;
} }
if(data.name.getParent() instanceof IASTFunctionDeclarator) { if (data.name.getParent() instanceof IASTFunctionDeclarator) {
return (IASTFunctionDeclarator) data.name.getParent(); return (IASTFunctionDeclarator) data.name.getParent();
} }
return null; return null;
}else if(parent instanceof IASTTranslationUnit) { } else if (parent instanceof IASTTranslationUnit) {
return null; return null;
} }
return findEnclosingFunction(parent); return findEnclosingFunction(parent);
@ -266,8 +261,8 @@ public class HideMethodRefactoring extends CRefactoring {
private IASTName getLastName(IASTDeclarator declarator) { private IASTName getLastName(IASTDeclarator declarator) {
IASTName declaratorName = declarator.getName(); IASTName declaratorName = declarator.getName();
if(declaratorName instanceof ICPPASTQualifiedName) { if (declaratorName instanceof ICPPASTQualifiedName) {
IASTName[] declaratorNames = ((ICPPASTQualifiedName)declaratorName).getNames(); IASTName[] declaratorNames = ((ICPPASTQualifiedName) declaratorName).getNames();
declaratorName = declaratorNames[declaratorNames.length-1]; declaratorName = declaratorNames[declaratorNames.length-1];
} }
return declaratorName; return declaratorName;
@ -285,8 +280,7 @@ public class HideMethodRefactoring extends CRefactoring {
AddDeclarationNodeToClassChange.createChange(classDefinition, VisibilityEnum.v_private, methodToHideDecl, false, collector); AddDeclarationNodeToClassChange.createChange(classDefinition, VisibilityEnum.v_private, methodToHideDecl, false, collector);
rewriter.remove(methodToHideDecl, editGroup); rewriter.remove(methodToHideDecl, editGroup);
} } finally {
finally {
unlockIndex(); unlockIndex();
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {

View file

@ -60,10 +60,8 @@ import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper;
* Checks conditions, finds insert location and generates the ImplementationNode. * Checks conditions, finds insert location and generates the ImplementationNode.
* *
* @author Mirko Stocker, Lukas Felber, Emanuel Graf * @author Mirko Stocker, Lukas Felber, Emanuel Graf
*
*/ */
public class ImplementMethodRefactoring extends CRefactoring { public class ImplementMethodRefactoring extends CRefactoring {
private InsertLocation insertLocation; private InsertLocation insertLocation;
private CPPASTFunctionDeclarator createdMethodDeclarator; private CPPASTFunctionDeclarator createdMethodDeclarator;
private ImplementMethodData data; private ImplementMethodData data;
@ -78,15 +76,14 @@ public class ImplementMethodRefactoring extends CRefactoring {
SubMonitor sm = SubMonitor.convert(pm, 10); SubMonitor sm = SubMonitor.convert(pm, 10);
super.checkInitialConditions(sm.newChild(6)); super.checkInitialConditions(sm.newChild(6));
if(!initStatus.hasFatalError()) { if (!initStatus.hasFatalError()) {
data.setMethodDeclarations(findUnimplementedMethodDeclarations(ast));
data.setMethodDeclarations(findUnimplementedMethodDeclarations(unit)); if (region.getLength() > 0) {
IASTSimpleDeclaration methodDeclaration = SelectionHelper.findFirstSelectedDeclaration(region, ast);
if(region.getLength()>0) {
IASTSimpleDeclaration methodDeclaration = SelectionHelper.findFirstSelectedDeclaration(region, unit);
if (NodeHelper.isMethodDeclaration(methodDeclaration)) { if (NodeHelper.isMethodDeclaration(methodDeclaration)) {
for (MethodToImplementConfig config : data.getMethodDeclarations()) { for (MethodToImplementConfig config : data.getMethodDeclarations()) {
if(config.getDeclaration() == methodDeclaration) { if (config.getDeclaration() == methodDeclaration) {
config.setChecked(true); config.setChecked(true);
} }
} }
@ -97,7 +94,6 @@ public class ImplementMethodRefactoring extends CRefactoring {
return initStatus; return initStatus;
} }
private List<IASTSimpleDeclaration> findUnimplementedMethodDeclarations( private List<IASTSimpleDeclaration> findUnimplementedMethodDeclarations(
IASTTranslationUnit unit) { IASTTranslationUnit unit) {
final List<IASTSimpleDeclaration> list = new ArrayList<IASTSimpleDeclaration>(); final List<IASTSimpleDeclaration> list = new ArrayList<IASTSimpleDeclaration>();
@ -111,26 +107,23 @@ public class ImplementMethodRefactoring extends CRefactoring {
if (declaration instanceof IASTSimpleDeclaration) { if (declaration instanceof IASTSimpleDeclaration) {
IASTSimpleDeclaration simpleDeclaration = (IASTSimpleDeclaration) declaration; IASTSimpleDeclaration simpleDeclaration = (IASTSimpleDeclaration) declaration;
try { try {
if(NodeHelper.isMethodDeclaration(simpleDeclaration) && DefinitionFinder.getDefinition(simpleDeclaration, file) == null) { if (NodeHelper.isMethodDeclaration(simpleDeclaration) && DefinitionFinder.getDefinition(simpleDeclaration, file) == null) {
list.add(simpleDeclaration); list.add(simpleDeclaration);
} }
} catch (CoreException e) {} } catch (CoreException e) {}
} }
return ASTVisitor.PROCESS_CONTINUE; return ASTVisitor.PROCESS_CONTINUE;
} }
}); });
return list; return list;
} }
@Override @Override
protected void collectModifications(IProgressMonitor pm, ModificationCollector collector) throws CoreException, OperationCanceledException { protected void collectModifications(IProgressMonitor pm, ModificationCollector collector)
throws CoreException, OperationCanceledException {
List<MethodToImplementConfig> methodsToImplement = data.getMethodsToImplement(); List<MethodToImplementConfig> methodsToImplement = data.getMethodsToImplement();
SubMonitor sm = SubMonitor.convert(pm, 4*methodsToImplement.size()); SubMonitor sm = SubMonitor.convert(pm, 4*methodsToImplement.size());
for(MethodToImplementConfig config : methodsToImplement) { for (MethodToImplementConfig config : methodsToImplement) {
createDefinition(collector, config, sm.newChild(4)); createDefinition(collector, config, sm.newChild(4));
} }
} }
@ -154,22 +147,21 @@ public class ImplementMethodRefactoring extends CRefactoring {
} }
private void createParameterModifications(ASTRewrite methodRewrite, ParameterHandler handler) { private void createParameterModifications(ASTRewrite methodRewrite, ParameterHandler handler) {
for(ParameterInfo actParameterInfo : handler.getParameterInfos()) { for (ParameterInfo actParameterInfo : handler.getParameterInfos()) {
ASTRewrite parameterRewrite = methodRewrite.insertBefore(createdMethodDeclarator, null, actParameterInfo.getParameter(), null); ASTRewrite parameterRewrite = methodRewrite.insertBefore(createdMethodDeclarator, null, actParameterInfo.getParameter(), null);
createNewNameInsertModification(actParameterInfo, parameterRewrite); createNewNameInsertModification(actParameterInfo, parameterRewrite);
createRemoveDefaultValueModification(actParameterInfo, parameterRewrite); createRemoveDefaultValueModification(actParameterInfo, parameterRewrite);
} }
} }
private void createRemoveDefaultValueModification(ParameterInfo parameterInfo, ASTRewrite parameterRewrite) { private void createRemoveDefaultValueModification(ParameterInfo parameterInfo, ASTRewrite parameterRewrite) {
if(parameterInfo.hasDefaultValue()) { if (parameterInfo.hasDefaultValue()) {
parameterRewrite.remove(parameterInfo.getDefaultValueNode(), null); parameterRewrite.remove(parameterInfo.getDefaultValueNode(), null);
} }
} }
private void createNewNameInsertModification(ParameterInfo parameterInfo, ASTRewrite parameterRewrite) { private void createNewNameInsertModification(ParameterInfo parameterInfo, ASTRewrite parameterRewrite) {
if(parameterInfo.hasNewName()) { if (parameterInfo.hasNewName()) {
IASTNode insertNode = parameterInfo.getNewNameNode(); IASTNode insertNode = parameterInfo.getNewNameNode();
IASTName replaceNode = parameterInfo.getNameNode(); IASTName replaceNode = parameterInfo.getNameNode();
parameterRewrite.replace(replaceNode, insertNode, null); parameterRewrite.replace(replaceNode, insertNode, null);
@ -196,20 +188,19 @@ public class ImplementMethodRefactoring extends CRefactoring {
private IASTDeclaration createFunctionDefinition(IASTDeclSpecifier declSpecifier, ICPPASTFunctionDeclarator functionDeclarator, private IASTDeclaration createFunctionDefinition(IASTDeclSpecifier declSpecifier, ICPPASTFunctionDeclarator functionDeclarator,
IASTNode declarationParent, IASTTranslationUnit unit) throws CoreException { IASTNode declarationParent, IASTTranslationUnit unit) throws CoreException {
IASTFunctionDefinition func = new CPPASTFunctionDefinition(); IASTFunctionDefinition func = new CPPASTFunctionDefinition();
func.setParent(unit); func.setParent(unit);
if(declSpecifier instanceof ICPPASTDeclSpecifier) { if (declSpecifier instanceof ICPPASTDeclSpecifier) {
((ICPPASTDeclSpecifier) declSpecifier).setVirtual(false); ((ICPPASTDeclSpecifier) declSpecifier).setVirtual(false);
} }
String currentFileName = declarationParent.getNodeLocations()[0].asFileLocation().getFileName(); String currentFileName = declarationParent.getNodeLocations()[0].asFileLocation().getFileName();
if(Path.fromOSString(currentFileName).equals(insertLocation.getInsertFile().getLocation())) { if (Path.fromOSString(currentFileName).equals(insertLocation.getInsertFile().getLocation())) {
declSpecifier.setInline(true); declSpecifier.setInline(true);
} }
if(declSpecifier.getStorageClass() == IASTDeclSpecifier.sc_static) { if (declSpecifier.getStorageClass() == IASTDeclSpecifier.sc_static) {
declSpecifier.setStorageClass(IASTDeclSpecifier.sc_unspecified); declSpecifier.setStorageClass(IASTDeclSpecifier.sc_unspecified);
} }
@ -220,18 +211,18 @@ public class ImplementMethodRefactoring extends CRefactoring {
createdMethodDeclarator = new CPPASTFunctionDeclarator(); createdMethodDeclarator = new CPPASTFunctionDeclarator();
createdMethodDeclarator.setName(qname); createdMethodDeclarator.setName(qname);
createdMethodDeclarator.setConst(functionDeclarator.isConst()); createdMethodDeclarator.setConst(functionDeclarator.isConst());
for(IASTPointerOperator pop : functionDeclarator.getPointerOperators()) { for (IASTPointerOperator pop : functionDeclarator.getPointerOperators()) {
createdMethodDeclarator.addPointerOperator(pop.copy()); createdMethodDeclarator.addPointerOperator(pop.copy());
} }
func.setDeclarator(createdMethodDeclarator); func.setDeclarator(createdMethodDeclarator);
func.setBody(new CPPASTCompoundStatement()); func.setBody(new CPPASTCompoundStatement());
if(NodeHelper.isContainedInTemplateDeclaration(declarationParent)) { if (NodeHelper.isContainedInTemplateDeclaration(declarationParent)) {
CPPASTTemplateDeclaration templateDeclaration = new CPPASTTemplateDeclaration(); CPPASTTemplateDeclaration templateDeclaration = new CPPASTTemplateDeclaration();
templateDeclaration.setParent(unit); templateDeclaration.setParent(unit);
for(ICPPASTTemplateParameter templateParameter : ((ICPPASTTemplateDeclaration) declarationParent.getParent().getParent() ).getTemplateParameters()) { for (ICPPASTTemplateParameter templateParameter : ((ICPPASTTemplateDeclaration) declarationParent.getParent().getParent() ).getTemplateParameters()) {
templateDeclaration.addTemplateParameter(templateParameter.copy()); templateDeclaration.addTemplateParameter(templateParameter.copy());
} }
@ -241,8 +232,8 @@ public class ImplementMethodRefactoring extends CRefactoring {
return func; return func;
} }
private ICPPASTQualifiedName createQualifiedNameFor(IASTFunctionDeclarator functionDeclarator, IASTNode declarationParent) private ICPPASTQualifiedName createQualifiedNameFor(IASTFunctionDeclarator functionDeclarator,
throws CoreException { IASTNode declarationParent) throws CoreException {
int insertOffset = insertLocation.getInsertPosition(); int insertOffset = insertLocation.getInsertPosition();
return NameHelper.createQualifiedNameFor(functionDeclarator.getName(), file, functionDeclarator.getFileLocation().getNodeOffset(), insertLocation.getInsertFile(), insertOffset); return NameHelper.createQualifiedNameFor(functionDeclarator.getName(), file, functionDeclarator.getFileLocation().getNodeOffset(), insertLocation.getInsertFile(), insertOffset);
} }