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

Use shared AST in Hide Method refactoring.

This commit is contained in:
Sergey Prigogin 2012-02-22 20:16:12 -08:00
parent d7ed01e939
commit 68b5958f0c
30 changed files with 487 additions and 782 deletions

View file

@ -15,7 +15,9 @@
package org.eclipse.cdt.core.parser.util; package org.eclipse.cdt.core.parser.util;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection;
import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.Assert;
@ -301,6 +303,19 @@ public abstract class ArrayUtil {
return dest; return dest;
} }
/**
* Adds all elements of an array to a collection.
* @since 5.4
*/
public static <T> void addAll(Collection<T> collection, T[] array) {
if (collection instanceof ArrayList) {
((ArrayList<T>) collection).ensureCapacity(collection.size() + array.length);
}
for (T element : array) {
collection.add(element);
}
}
/** /**
* Returns whether the specified array contains the specified object. Comparison is by * Returns whether the specified array contains the specified object. Comparison is by
* object identity. * object identity.

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2009, 2010 Google, Inc and others. * Copyright (c) 2009, 2012 Google, Inc and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at * which accompanies this distribution, and is available at
@ -46,6 +46,18 @@ public class AccessContext {
return new AccessContext(from).isAccessible(binding); return new AccessContext(from).isAccessible(binding);
} }
/**
* Checks if a binding is accessible from a given name.
* @param binding A binding to check access for.
* @param bindingVisibility visibility of the binding in the containing composite type.
* Used instead of calling {@link ICPPMember#getVisibility()}.
* @param from A name corresponding to the binding.
* @return <code>true</code> if the binding is accessible.
*/
public static boolean isAccessible(IBinding binding, int bindingVisibility, IASTName from) {
return new AccessContext(from).isAccessible(binding, bindingVisibility);
}
private final IASTName name; private final IASTName name;
/** /**
* A chain of nested classes or/and a function that determine accessibility of private/protected members * A chain of nested classes or/and a function that determine accessibility of private/protected members
@ -72,6 +84,24 @@ public class AccessContext {
* @return <code>true</code> if the binding is accessible. * @return <code>true</code> if the binding is accessible.
*/ */
public boolean isAccessible(IBinding binding) { public boolean isAccessible(IBinding binding) {
int bindingVisibility;
if (binding instanceof ICPPMember) {
bindingVisibility = ((ICPPMember) binding).getVisibility();
} else {
// TODO(sprigogin): Handle visibility of nested types
bindingVisibility = v_public;
}
return isAccessible(binding, bindingVisibility);
}
/**
* Checks if a binding is accessible in a given context.
* @param binding A binding to check access for.
* @param bindingVisibility visibility of the binding in the containing composite type.
* Used instead of calling {@link ICPPMember#getVisibility()}.
* @return <code>true</code> if the binding is accessible.
*/
public boolean isAccessible(IBinding binding, int bindingVisibility) {
IBinding owner; IBinding owner;
while ((owner = binding.getOwner()) instanceof ICompositeType && while ((owner = binding.getOwner()) instanceof ICompositeType &&
((ICompositeType) owner).isAnonymous()) { ((ICompositeType) owner).isAnonymous()) {
@ -87,7 +117,8 @@ public class AccessContext {
if (namingClass == null) { if (namingClass == null) {
return true; return true;
} }
return isAccessible(binding, (ICPPClassType) owner, namingClass, v_public, 0); return isAccessible(binding, bindingVisibility, (ICPPClassType) owner, namingClass,
v_public, 0);
} }
/** /**
@ -111,20 +142,16 @@ public class AccessContext {
return true; return true;
} }
private boolean isAccessible(IBinding binding, ICPPClassType owner, ICPPClassType derivedClass, private boolean isAccessible(IBinding binding, int bindingVisibility, ICPPClassType owner,
int accessLevel, int depth) { ICPPClassType derivedClass, int accessLevel, int depth) {
if (depth > CPPSemantics.MAX_INHERITANCE_DEPTH) if (depth > CPPSemantics.MAX_INHERITANCE_DEPTH)
return false; return false;
accessLevel = getMemberAccessLevel(derivedClass, accessLevel); accessLevel = getMemberAccessLevel(derivedClass, accessLevel);
if (owner.isSameType(derivedClass)) { if (owner.isSameType(derivedClass)) {
if (binding instanceof ICPPMember) { return isAccessible(bindingVisibility, accessLevel);
return isAccessible(((ICPPMember) binding).getVisibility(), accessLevel);
} else {
// TODO(sprigogin): Handle visibility of nested types
return true;
} }
} else {
ICPPBase[] bases = derivedClass.getBases(); ICPPBase[] bases = derivedClass.getBases();
if (bases != null) { if (bases != null) {
for (ICPPBase base : bases) { for (ICPPBase base : bases) {
@ -139,15 +166,14 @@ public class AccessContext {
if (!isAccessible(base.getVisibility(), accessLevel)) { if (!isAccessible(base.getVisibility(), accessLevel)) {
continue; continue;
} }
if (isAccessible(binding, owner, (ICPPClassType) baseBinding, if (isAccessible(binding, bindingVisibility, owner,
accessLevel == v_private ? v_protected : accessLevel, depth + 1)) { (ICPPClassType) baseBinding, accessLevel == v_private ? v_protected : accessLevel, depth + 1)) {
return true; return true;
} }
} }
} }
return false; return false;
} }
}
/** /**
* Returns access level to the members of a class. * Returns access level to the members of a class.

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2004, 2011 IBM Corporation and others. * Copyright (c) 2004, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at * which accompanies this distribution, and is available at
@ -20,6 +20,7 @@ import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUti
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getUltimateTypeUptoPointers; import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getUltimateTypeUptoPointers;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@ -1500,11 +1501,9 @@ public class CPPVisitor extends ASTQueries {
} }
if (bindings != null) { if (bindings != null) {
if (isDeclarationsBinding(name.resolveBinding())) { if (isDeclarationBinding(name.resolveBinding())) {
if (decls.length == idx) { if (decls.length == idx) {
IASTName[] temp = new IASTName[decls.length * 2]; decls = Arrays.copyOf(decls, decls.length * 2);
System.arraycopy(decls, 0, temp, 0, decls.length);
decls = temp;
} }
decls[idx++] = name; decls[idx++] = name;
} }
@ -1512,10 +1511,10 @@ public class CPPVisitor extends ASTQueries {
return PROCESS_CONTINUE; return PROCESS_CONTINUE;
} }
private boolean isDeclarationsBinding(IBinding nameBinding) { private boolean isDeclarationBinding(IBinding nameBinding) {
if (nameBinding != null) { if (nameBinding != null) {
for (IBinding binding : bindings) { for (IBinding binding : bindings) {
if (areEquivalentBindings(nameBinding, binding)) { if (areEquivalentBindings(nameBinding, binding, index)) {
return true; return true;
} }
// A using declaration is a declaration for the references of its delegates // A using declaration is a declaration for the references of its delegates
@ -1529,12 +1528,19 @@ public class CPPVisitor extends ASTQueries {
return false; return false;
} }
private boolean areEquivalentBindings(IBinding binding1, IBinding binding2) { public IASTName[] getDeclarations() {
if (idx < decls.length) {
decls = Arrays.copyOf(decls, idx);
}
return decls;
}
}
private static boolean areEquivalentBindings(IBinding binding1, IBinding binding2, IIndex index) {
if (binding1.equals(binding2)) { if (binding1.equals(binding2)) {
return true; return true;
} }
if ((binding1 instanceof IIndexBinding) != (binding2 instanceof IIndexBinding) && if ((binding1 instanceof IIndexBinding) != (binding2 instanceof IIndexBinding) && index != null) {
index != null) {
if (binding1 instanceof IIndexBinding) { if (binding1 instanceof IIndexBinding) {
binding2 = index.adaptBinding(binding2); binding2 = index.adaptBinding(binding2);
} else { } else {
@ -1550,17 +1556,6 @@ public class CPPVisitor extends ASTQueries {
return false; return false;
} }
public IASTName[] getDeclarations() {
if (idx < decls.length) {
IASTName[] temp = new IASTName[idx];
System.arraycopy(decls, 0, temp, 0, idx);
decls = temp;
}
return decls;
}
}
protected static IBinding unwindBinding(IBinding binding) { protected static IBinding unwindBinding(IBinding binding) {
while (true) { while (true) {
if (binding instanceof ICPPSpecialization) { if (binding instanceof ICPPSpecialization) {
@ -1578,6 +1573,7 @@ public class CPPVisitor extends ASTQueries {
private IBinding[] bindings; private IBinding[] bindings;
private int idx = 0; private int idx = 0;
private int kind; private int kind;
private IIndex index;
private static final int KIND_LABEL = 1; private static final int KIND_LABEL = 1;
private static final int KIND_OBJ_FN = 2; private static final int KIND_OBJ_FN = 2;
@ -1586,11 +1582,12 @@ public class CPPVisitor extends ASTQueries {
private static final int KIND_COMPOSITE = 5; private static final int KIND_COMPOSITE = 5;
public CollectReferencesAction(IBinding binding) { public CollectReferencesAction(IBinding binding) {
shouldVisitTranslationUnit = true;
shouldVisitNames = true; shouldVisitNames = true;
this.refs = new IASTName[DEFAULT_LIST_SIZE]; this.refs = new IASTName[DEFAULT_LIST_SIZE];
binding = unwindBinding(binding); binding = unwindBinding(binding);
this.bindings = new IBinding[] {binding}; this.bindings = new IBinding[] { binding };
if (binding instanceof ICPPUsingDeclaration) { if (binding instanceof ICPPUsingDeclaration) {
this.bindings= ((ICPPUsingDeclaration) binding).getDelegates(); this.bindings= ((ICPPUsingDeclaration) binding).getDelegates();
@ -1610,7 +1607,12 @@ public class CPPVisitor extends ASTQueries {
} }
} }
@SuppressWarnings("fallthrough") @Override
public int visit(IASTTranslationUnit tu) {
index = tu.getIndex();
return PROCESS_CONTINUE;
}
@Override @Override
public int visit(IASTName name) { public int visit(IASTName name) {
if (name instanceof ICPPASTQualifiedName || name instanceof ICPPASTTemplateId) if (name instanceof ICPPASTQualifiedName || name instanceof ICPPASTTemplateId)
@ -1628,6 +1630,7 @@ public class CPPVisitor extends ASTQueries {
if (prop == IASTGotoStatement.NAME) if (prop == IASTGotoStatement.NAME)
break; break;
return PROCESS_CONTINUE; return PROCESS_CONTINUE;
case KIND_TYPE: case KIND_TYPE:
case KIND_COMPOSITE: case KIND_COMPOSITE:
if (prop == IASTNamedTypeSpecifier.NAME || if (prop == IASTNamedTypeSpecifier.NAME ||
@ -1640,15 +1643,13 @@ public class CPPVisitor extends ASTQueries {
} else if (prop == IASTElaboratedTypeSpecifier.TYPE_NAME) { } else if (prop == IASTElaboratedTypeSpecifier.TYPE_NAME) {
IASTNode p = name.getParent().getParent(); IASTNode p = name.getParent().getParent();
if (!(p instanceof IASTSimpleDeclaration) || if (!(p instanceof IASTSimpleDeclaration) ||
((IASTSimpleDeclaration) p).getDeclarators().length > 0) ((IASTSimpleDeclaration) p).getDeclarators().length > 0) {
{
break; break;
} }
} }
if (kind == KIND_TYPE) if (kind == KIND_TYPE)
return PROCESS_CONTINUE; return PROCESS_CONTINUE;
// fall through //$FALL-THROUGH$
case KIND_OBJ_FN: case KIND_OBJ_FN:
if (prop == IASTIdExpression.ID_NAME || if (prop == IASTIdExpression.ID_NAME ||
prop == IASTFieldReference.FIELD_NAME || prop == IASTFieldReference.FIELD_NAME ||
@ -1663,6 +1664,7 @@ public class CPPVisitor extends ASTQueries {
break; break;
} }
return PROCESS_CONTINUE; return PROCESS_CONTINUE;
case KIND_NAMESPACE: case KIND_NAMESPACE:
if (prop == ICPPASTUsingDirective.QUALIFIED_NAME || if (prop == ICPPASTUsingDirective.QUALIFIED_NAME ||
prop == ICPPASTNamespaceAlias.MAPPING_NAME || prop == ICPPASTNamespaceAlias.MAPPING_NAME ||
@ -1676,9 +1678,7 @@ public class CPPVisitor extends ASTQueries {
if (bindings != null) { if (bindings != null) {
if (isReferenceBinding(name.resolveBinding())) { if (isReferenceBinding(name.resolveBinding())) {
if (refs.length == idx) { if (refs.length == idx) {
IASTName[] temp = new IASTName[refs.length * 2]; refs = Arrays.copyOf(refs, refs.length * 2);
System.arraycopy(refs, 0, temp, 0, refs.length);
refs = temp;
} }
refs[idx++] = name; refs[idx++] = name;
} }
@ -1690,7 +1690,7 @@ public class CPPVisitor extends ASTQueries {
nameBinding= unwindBinding(nameBinding); nameBinding= unwindBinding(nameBinding);
if (nameBinding != null) { if (nameBinding != null) {
for (IBinding binding : bindings) { for (IBinding binding : bindings) {
if (nameBinding.equals(binding)) { if (areEquivalentBindings(nameBinding, binding, index)) {
return true; return true;
} }
} }
@ -1701,9 +1701,6 @@ public class CPPVisitor extends ASTQueries {
return true; return true;
} }
} }
return false;
} else {
return false;
} }
} }
return false; return false;
@ -1711,9 +1708,7 @@ public class CPPVisitor extends ASTQueries {
public IASTName[] getReferences() { public IASTName[] getReferences() {
if (idx < refs.length) { if (idx < refs.length) {
IASTName[] temp = new IASTName[idx]; refs = Arrays.copyOf(refs, idx);
System.arraycopy(refs, 0, temp, 0, idx);
refs = temp;
} }
return refs; return refs;
} }
@ -2448,8 +2443,8 @@ public class CPPVisitor extends ASTQueries {
isNonSimpleElabDecl= true; isNonSimpleElabDecl= true;
final IASTNode parent= node.getParent(); final IASTNode parent= node.getParent();
if (parent instanceof IASTSimpleDeclaration) { if (parent instanceof IASTSimpleDeclaration) {
final IASTSimpleDeclaration sdecl = (IASTSimpleDeclaration) parent; final IASTSimpleDeclaration decl = (IASTSimpleDeclaration) parent;
if (sdecl.getDeclarators().length == 0) { if (decl.getDeclarators().length == 0) {
isNonSimpleElabDecl= false; isNonSimpleElabDecl= false;
} }
} }

View file

@ -39,7 +39,7 @@ public class HideMethodRefactoringTest extends RefactoringTestBase {
@Override @Override
protected Refactoring createRefactoring() { protected Refactoring createRefactoring() {
return new HideMethodRefactoring(getSelectedFile(), getSelection(), null, getCProject()); return new HideMethodRefactoring(getSelectedTranslationUnit(), getSelection(), getCProject());
} }
//A.h //A.h
@ -979,13 +979,11 @@ public class HideMethodRefactoringTest extends RefactoringTestBase {
// //
//class HideMethod { //class HideMethod {
//public: //public:
// HideMethod();
// virtual ~HideMethod();
// void /*$*/method2/*$$*/(); // void /*$*/method2/*$$*/();
// void method3(); // void method3();
//}; //};
// //
//class test{ //class test {
//public: //public:
// void call() { // void call() {
// HideMethod hm; // HideMethod hm;
@ -1000,15 +998,13 @@ public class HideMethodRefactoringTest extends RefactoringTestBase {
// //
//class HideMethod { //class HideMethod {
//public: //public:
// HideMethod();
// virtual ~HideMethod();
// void method3(); // void method3();
// //
//private: //private:
// void method2(); // void method2();
//}; //};
// //
//class test{ //class test {
//public: //public:
// void call() { // void call() {
// HideMethod hm; // HideMethod hm;

View file

@ -15,12 +15,12 @@ import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration; import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICElement;
@ -64,7 +64,7 @@ public class DefinitionFinderTest extends RefactoringTestBase {
} }
@Override @Override
protected Refactoring createRefactoring() { protected CRefactoring2 createRefactoring() {
return new DummyRefactoring(getSelectedTranslationUnit(), getSelection(), getCProject()); return new DummyRefactoring(getSelectedTranslationUnit(), getSelection(), getCProject());
} }
@ -82,13 +82,13 @@ public class DefinitionFinderTest extends RefactoringTestBase {
//void foo() { //void foo() {
//} //}
public void testFindFunctionDefinition() throws Exception { public void testFindFunctionDefinition() throws Exception {
CRefactoringContext refactoringContext = new CRefactoringContext((CRefactoring2) createRefactoring()); CRefactoringContext refactoringContext = new CRefactoringContext(createRefactoring());
try { try {
IASTTranslationUnit ast = refactoringContext.getAST(getSelectedTranslationUnit(), null); IASTTranslationUnit ast = refactoringContext.getAST(getSelectedTranslationUnit(), null);
for (IASTDeclaration declaration : ast.getDeclarations()) { for (IASTDeclaration declaration : ast.getDeclarations()) {
if (declaration instanceof IASTSimpleDeclaration) { if (declaration instanceof IASTSimpleDeclaration) {
assertNotNull(DefinitionFinder.getDefinition((IASTSimpleDeclaration) declaration, IASTName name = ((IASTSimpleDeclaration) declaration).getDeclarators()[0].getName();
refactoringContext, NULL_PROGRESS_MONITOR)); assertNotNull(DefinitionFinder.getDefinition(name, refactoringContext, NULL_PROGRESS_MONITOR));
} }
} }
} finally { } finally {

View file

@ -11,8 +11,6 @@
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring; package org.eclipse.cdt.internal.ui.refactoring;
import java.util.ArrayList;
import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.CoreException;
@ -32,7 +30,6 @@ import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration; import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTExpression;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTProblem; import org.eclipse.cdt.core.dom.ast.IASTProblem;
import org.eclipse.cdt.core.dom.ast.IASTProblemDeclaration; import org.eclipse.cdt.core.dom.ast.IASTProblemDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTProblemExpression; import org.eclipse.cdt.core.dom.ast.IASTProblemExpression;
@ -41,7 +38,6 @@ import org.eclipse.cdt.core.dom.ast.IASTProblemTypeId;
import org.eclipse.cdt.core.dom.ast.IASTStatement; import org.eclipse.cdt.core.dom.ast.IASTStatement;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.IASTTypeId; import org.eclipse.cdt.core.dom.ast.IASTTypeId;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName;
import org.eclipse.cdt.core.index.IIndex; import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.CoreModel;
@ -307,25 +303,4 @@ public abstract class CRefactoring extends Refactoring {
public IASTTranslationUnit getUnit() { public IASTTranslationUnit getUnit() {
return ast; return ast;
} }
protected ArrayList<IASTName> findAllMarkedNames() {
final ArrayList<IASTName> namesVector = new ArrayList<IASTName>();
ast.accept(new ASTVisitor() {
{
shouldVisitNames = true;
}
@Override
public int visit(IASTName name) {
if (SelectionHelper.isInSameFileSelection(region, name, file)) {
if (!(name instanceof ICPPASTQualifiedName)) {
namesVector.add(name);
}
}
return super.visit(name);
}
});
return namesVector;
}
} }

View file

@ -105,7 +105,7 @@ public abstract class CRefactoring2 extends Refactoring {
} }
@Override @Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) public final RefactoringStatus checkFinalConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException { throws CoreException, OperationCanceledException {
if (pm == null) if (pm == null)
pm = new NullProgressMonitor(); pm = new NullProgressMonitor();
@ -125,8 +125,10 @@ public abstract class CRefactoring2 extends Refactoring {
return result; return result;
} }
protected abstract RefactoringStatus checkFinalConditions(IProgressMonitor subProgressMonitor, protected RefactoringStatus checkFinalConditions(IProgressMonitor subProgressMonitor,
CheckConditionsContext checkContext) throws CoreException, OperationCanceledException; CheckConditionsContext checkContext) throws CoreException, OperationCanceledException {
return new RefactoringStatus();
}
@Override @Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) public RefactoringStatus checkInitialConditions(IProgressMonitor pm)

View file

@ -19,13 +19,10 @@ import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.IScope; import org.eclipse.cdt.core.dom.ast.IScope;
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.ICPPASTQualifiedName; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTVisibilityLabel;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPBase; import org.eclipse.cdt.core.dom.ast.cpp.ICPPBase;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPMember;
import org.eclipse.cdt.internal.core.dom.parser.ASTInternal; import org.eclipse.cdt.internal.core.dom.parser.ASTInternal;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTVisibilityLabel;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPInternalBinding; import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPInternalBinding;
/** /**
@ -51,8 +48,8 @@ public class MethodContext {
this.type = type; this.type = type;
} }
public void setMethodDeclarationName(IASTName tmpname) { public void setMethodDeclarationName(IASTName name) {
this.declarationName = tmpname; this.declarationName = name;
} }
public IASTName getMethodDeclarationName() { public IASTName getMethodDeclarationName() {
@ -67,13 +64,6 @@ public class MethodContext {
return null; return null;
} }
public ICPPASTVisibilityLabel getMethodDeclarationASTVisibility() {
ICPPASTVisibilityLabel label = new CPPASTVisibilityLabel();
ICPPMember member = (ICPPMember) qname.resolveBinding();
label.setVisibility(member.getVisibility());
return label;
}
public Visibility getMethodDeclarationVisibility() { public Visibility getMethodDeclarationVisibility() {
return Visibility.getVisibility(declarationName); return Visibility.getVisibility(declarationName);
} }

View file

@ -27,7 +27,6 @@ import org.eclipse.jface.text.Region;
import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.text.edits.TextEditGroup; import org.eclipse.text.edits.TextEditGroup;
import org.eclipse.cdt.core.dom.ast.ASTNodeFactoryFactory; import org.eclipse.cdt.core.dom.ast.ASTNodeFactoryFactory;
@ -65,6 +64,7 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTLiteralExpression;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTName; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTName;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclaration; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclaration;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPMethod; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPMethod;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor; import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
@ -172,7 +172,7 @@ public class ExtractConstantRefactoring extends CRefactoring2 {
private ArrayList<String> findAllDeclaredNames() { private ArrayList<String> findAllDeclaredNames() {
ArrayList<String>names = new ArrayList<String>(); ArrayList<String>names = new ArrayList<String>();
IASTFunctionDefinition funcDef = NodeHelper.findFunctionDefinitionInAncestors(target); IASTFunctionDefinition funcDef = CPPVisitor.findAncestorWithType(target, IASTFunctionDefinition.class);
ICPPASTCompositeTypeSpecifier comTypeSpec = getCompositeTypeSpecifier(funcDef); ICPPASTCompositeTypeSpecifier comTypeSpec = getCompositeTypeSpecifier(funcDef);
if (comTypeSpec != null) { if (comTypeSpec != null) {
for(IASTDeclaration dec : comTypeSpec.getMembers()) { for(IASTDeclaration dec : comTypeSpec.getMembers()) {
@ -297,12 +297,6 @@ public class ExtractConstantRefactoring extends CRefactoring2 {
return result; return result;
} }
@Override
protected RefactoringStatus checkFinalConditions(IProgressMonitor subProgressMonitor,
CheckConditionsContext checkContext) throws CoreException, OperationCanceledException {
return new RefactoringStatus();
}
@Override @Override
protected void collectModifications(IProgressMonitor pm, ModificationCollector collector) protected void collectModifications(IProgressMonitor pm, ModificationCollector collector)
throws CoreException, OperationCanceledException{ throws CoreException, OperationCanceledException{

View file

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

View file

@ -101,6 +101,7 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTQualifiedName;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTReturnStatement; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTReturnStatement;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclaration; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTSimpleDeclaration;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTemplateDeclaration; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTemplateDeclaration;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil; import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil;
import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ASTWriterVisitor; import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ASTWriterVisitor;
@ -282,7 +283,7 @@ public class ExtractFunctionRefactoring extends CRefactoring2 {
@Override @Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext checkContext) public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext checkContext)
throws CoreException, OperationCanceledException { throws CoreException, OperationCanceledException {
RefactoringStatus finalConditions = new RefactoringStatus(); RefactoringStatus status = new RefactoringStatus();
final IASTName methodName = new CPPASTName(info.getMethodName().toCharArray()); final IASTName methodName = new CPPASTName(info.getMethodName().toCharArray());
MethodContext context = info.getMethodContext(); MethodContext context = info.getMethodContext();
@ -293,10 +294,10 @@ public class ExtractFunctionRefactoring extends CRefactoring2 {
IASTSimpleDeclaration methodDeclaration = getDeclaration(methodName); IASTSimpleDeclaration methodDeclaration = getDeclaration(methodName);
if (isMethodAllreadyDefined(methodDeclaration, classDeclaration, getIndex())) { if (isMethodAllreadyDefined(methodDeclaration, classDeclaration, getIndex())) {
finalConditions.addError(Messages.ExtractFunctionRefactoring_name_in_use); status.addError(Messages.ExtractFunctionRefactoring_name_in_use);
} }
} }
return finalConditions; return status;
} }
@Override @Override
@ -379,7 +380,7 @@ public class ExtractFunctionRefactoring extends CRefactoring2 {
private void createMethodDefinition(final IASTName methodName, MethodContext context, private void createMethodDefinition(final IASTName methodName, MethodContext context,
IASTNode firstNode, ModificationCollector collector) { IASTNode firstNode, ModificationCollector collector) {
IASTFunctionDefinition node = NodeHelper.findFunctionDefinitionInAncestors(firstNode); IASTFunctionDefinition node = CPPVisitor.findAncestorWithType(firstNode, IASTFunctionDefinition.class);
if (node != null) { if (node != null) {
String title; String title;
if (context.getType() == MethodContext.ContextType.METHOD) { if (context.getType() == MethodContext.ContextType.METHOD) {
@ -740,8 +741,7 @@ public class ExtractFunctionRefactoring extends CRefactoring2 {
private IASTNode getReturnAssignment(IASTExpressionStatement stmt, private IASTNode getReturnAssignment(IASTExpressionStatement stmt,
IASTFunctionCallExpression callExpression, IASTName retname) { IASTFunctionCallExpression callExpression, IASTName retname) {
if (info.getReturnVariable().equals(info.getMandatoryReturnVariable())) { if (info.getReturnVariable().equals(info.getMandatoryReturnVariable())) {
IASTSimpleDeclaration orgDecl = NodeHelper.findSimpleDeclarationInParents( IASTSimpleDeclaration orgDecl = CPPVisitor.findAncestorWithType(info.getReturnVariable().getDeclarationName(), IASTSimpleDeclaration.class);
info.getReturnVariable().getDeclarationName());
IASTSimpleDeclaration decl = new CPPASTSimpleDeclaration(); IASTSimpleDeclaration decl = new CPPASTSimpleDeclaration();
decl.setDeclSpecifier(orgDecl.getDeclSpecifier().copy(CopyStyle.withLocations)); decl.setDeclSpecifier(orgDecl.getDeclSpecifier().copy(CopyStyle.withLocations));
@ -813,7 +813,7 @@ public class ExtractFunctionRefactoring extends CRefactoring2 {
@Override @Override
public int visit(IASTStatement stmt) { public int visit(IASTStatement stmt) {
if (SelectionHelper.isNodeInsideSelection(stmt, selectedRegion)) { if (isNodeInsideSelection(stmt)) {
container.add(stmt); container.add(stmt);
return PROCESS_SKIP; return PROCESS_SKIP;
} }
@ -822,7 +822,7 @@ public class ExtractFunctionRefactoring extends CRefactoring2 {
@Override @Override
public int visit(IASTExpression expression) { public int visit(IASTExpression expression) {
if (SelectionHelper.isNodeInsideSelection(expression, selectedRegion)) { if (isNodeInsideSelection(expression)) {
container.add(expression); container.add(expression);
return PROCESS_SKIP; return PROCESS_SKIP;
} }
@ -832,6 +832,10 @@ public class ExtractFunctionRefactoring extends CRefactoring2 {
return container; return container;
} }
private boolean isNodeInsideSelection(IASTNode node) {
return node.isPartOfTranslationUnitFile() && SelectionHelper.isNodeInsideRegion(node, selectedRegion);
}
public List<IASTInitializerClause> getCallParameters() { public List<IASTInitializerClause> getCallParameters() {
List<IASTInitializerClause> args = new ArrayList<IASTInitializerClause>(); List<IASTInitializerClause> args = new ArrayList<IASTInitializerClause>();
Set<IASTName> declarations = new HashSet<IASTName>(); Set<IASTName> declarations = new HashSet<IASTName>();

View file

@ -27,8 +27,7 @@ public class ExtractFunctionRefactoringContribution extends CRefactoringContribu
String comment, Map arguments, int flags) throws IllegalArgumentException { String comment, Map arguments, int flags) throws IllegalArgumentException {
if (id.equals(ExtractFunctionRefactoring.ID)) { if (id.equals(ExtractFunctionRefactoring.ID)) {
return new ExtractFunctionRefactoringDescriptor(project, description, comment, arguments); return new ExtractFunctionRefactoringDescriptor(project, description, comment, arguments);
} else { }
return null; return null;
} }
}
} }

View file

@ -25,7 +25,6 @@ import org.eclipse.jface.text.Region;
import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.text.edits.TextEditGroup; import org.eclipse.text.edits.TextEditGroup;
import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.ASTVisitor;
@ -66,6 +65,7 @@ import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTIdExpression;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTLiteralExpression; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTLiteralExpression;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTName; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTName;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPFunction; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPFunction;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor; import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
@ -147,7 +147,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
private ArrayList<String> findAllDeclaredNames() { private ArrayList<String> findAllDeclaredNames() {
ArrayList<String> names = new ArrayList<String>(); ArrayList<String> names = new ArrayList<String>();
IASTFunctionDefinition funcDef = NodeHelper.findFunctionDefinitionInAncestors(target); IASTFunctionDefinition funcDef = CPPVisitor.findAncestorWithType(target, IASTFunctionDefinition.class);
ICPPASTCompositeTypeSpecifier comTypeSpec = getCompositeTypeSpecifier(funcDef); ICPPASTCompositeTypeSpecifier comTypeSpec = getCompositeTypeSpecifier(funcDef);
if (comTypeSpec != null) { if (comTypeSpec != null) {
for (IASTDeclaration decl : comTypeSpec.getMembers()) { for (IASTDeclaration decl : comTypeSpec.getMembers()) {
@ -162,12 +162,6 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
return names; return names;
} }
@Override
protected RefactoringStatus checkFinalConditions(IProgressMonitor subProgressMonitor,
CheckConditionsContext checkContext) throws CoreException, OperationCanceledException {
return new RefactoringStatus();
}
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();
@ -239,7 +233,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
@Override @Override
public int visit(IASTExpression expression) { public int visit(IASTExpression expression) {
if (SelectionHelper.isNodeInsideSelection(expression, selectedRegion)) { if (isNodeInsideSelection(expression)) {
container.add(expression); container.add(expression);
return PROCESS_SKIP; return PROCESS_SKIP;
} }
@ -251,6 +245,10 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
return container; return container;
} }
private boolean isNodeInsideSelection(IASTNode node) {
return node.isPartOfTranslationUnitFile() && SelectionHelper.isNodeInsideRegion(node, selectedRegion);
}
@Override @Override
protected void collectModifications(IProgressMonitor pm, ModificationCollector collector) protected void collectModifications(IProgressMonitor pm, ModificationCollector collector)
throws CoreException, OperationCanceledException { throws CoreException, OperationCanceledException {
@ -339,7 +337,7 @@ public class ExtractLocalVariableRefactoring extends CRefactoring2 {
public String[] guessTempNames() { public String[] guessTempNames() {
final List<String> guessedTempNames = new ArrayList<String>(); final List<String> guessedTempNames = new ArrayList<String>();
final List<String> usedNames = new ArrayList<String>(); final List<String> usedNames = new ArrayList<String>();
IASTFunctionDefinition funcDef = NodeHelper.findFunctionDefinitionInAncestors(target); IASTFunctionDefinition funcDef = CPPVisitor.findAncestorWithType(target, IASTFunctionDefinition.class);
final IScope scope; final IScope scope;
if (funcDef != null && funcDef.getBody() instanceof IASTCompoundStatement) { if (funcDef != null && funcDef.getBody() instanceof IASTCompoundStatement) {
IASTCompoundStatement body = (IASTCompoundStatement) funcDef.getBody(); IASTCompoundStatement body = (IASTCompoundStatement) funcDef.getBody();

View file

@ -27,8 +27,7 @@ public class ExtractLocalVariableRefactoringContribution extends CRefactoringCon
String comment, Map arguments, int flags) throws IllegalArgumentException { String comment, Map arguments, int flags) throws IllegalArgumentException {
if (id.equals(ExtractLocalVariableRefactoring.ID)) { if (id.equals(ExtractLocalVariableRefactoring.ID)) {
return new ExtractLocalVariableRefactoringDescriptor(project, description, comment, arguments); return new ExtractLocalVariableRefactoringDescriptor(project, description, comment, arguments);
} else { }
return null; return null;
} }
}
} }

View file

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

View file

@ -119,16 +119,16 @@ public class GenerateGettersAndSettersRefactoring extends CRefactoring2 {
@Override @Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm, public RefactoringStatus checkFinalConditions(IProgressMonitor pm,
CheckConditionsContext checkContext) throws CoreException, OperationCanceledException { CheckConditionsContext checkContext) throws CoreException, OperationCanceledException {
RefactoringStatus result = new RefactoringStatus(); RefactoringStatus status = new RefactoringStatus();
if (context.isDefinitionSeparate()) { if (context.isDefinitionSeparate()) {
findDefinitionInsertLocation(pm); findDefinitionInsertLocation(pm);
if (definitionInsertLocation == null || if (definitionInsertLocation == null ||
definitionInsertLocation.getTranslationUnit() == null) { definitionInsertLocation.getTranslationUnit() == null) {
result.addInfo(Messages.GenerateGettersAndSettersRefactoring_NoImplFile); status.addInfo(Messages.GenerateGettersAndSettersRefactoring_NoImplFile);
} }
} }
Checks.addModifiedFilesToChecker(getAllFilesToModify(), checkContext); Checks.addModifiedFilesToChecker(getAllFilesToModify(), checkContext);
return result; return status;
} }
private IFile[] getAllFilesToModify() { private IFile[] getAllFilesToModify() {
@ -289,7 +289,7 @@ public class GenerateGettersAndSettersRefactoring extends CRefactoring2 {
@Override @Override
protected RefactoringDescriptor getRefactoringDescriptor() { protected RefactoringDescriptor getRefactoringDescriptor() {
// TODO egraf add Descriptor // TODO egraf Add descriptor
return null; return null;
} }
} }

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2008, 2009 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others * Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -8,14 +8,17 @@
* *
* Contributors: * Contributors:
* Institute for Software - initial API and implementation * Institute for Software - initial API and implementation
* Sergey Prigogin (Google)
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.hidemethod; package org.eclipse.cdt.internal.ui.refactoring.hidemethod;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.OperationCanceledException;
@ -23,53 +26,60 @@ import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.text.edits.TextEditGroup; import org.eclipse.text.edits.TextEditGroup;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier; import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement;
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;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator; import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition; import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition;
import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
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.ICPPASTQualifiedName; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTVisibilityLabel; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTVisibilityLabel;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPMember;
import org.eclipse.cdt.core.dom.rewrite.ASTRewrite; import org.eclipse.cdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexBinding;
import org.eclipse.cdt.core.index.IIndexName; import org.eclipse.cdt.core.index.IIndexName;
import org.eclipse.cdt.core.model.CoreModelUtil;
import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.parser.util.ArrayUtil;
import org.eclipse.cdt.internal.core.dom.parser.ASTQueries; import org.eclipse.cdt.internal.core.dom.parser.ASTQueries;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.AccessContext;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor; import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMName; import org.eclipse.cdt.internal.corext.util.CModelUtil;
import org.eclipse.cdt.internal.ui.editor.ITranslationUnitEditorInput;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
import org.eclipse.cdt.internal.ui.refactoring.ClassMemberInserter; import org.eclipse.cdt.internal.ui.refactoring.ClassMemberInserter;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescription;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.utils.DeclarationFinder; import org.eclipse.cdt.internal.ui.refactoring.utils.DefinitionFinder;
import org.eclipse.cdt.internal.ui.refactoring.utils.DeclarationFinderDO; import org.eclipse.cdt.internal.ui.refactoring.utils.SelectionHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.ExpressionFinder;
import org.eclipse.cdt.internal.ui.refactoring.utils.NodeHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.TranslationUnitHelper;
import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum; import org.eclipse.cdt.internal.ui.refactoring.utils.VisibilityEnum;
import org.eclipse.cdt.internal.ui.util.EditorUtility;
/** /**
* @author Guido Zgraggen IFS * @author Guido Zgraggen IFS
*/ */
public class HideMethodRefactoring extends CRefactoring { public class HideMethodRefactoring extends CRefactoring2 {
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 methodName;
private IASTDeclaration methodToHideDecl; private IASTDeclaration methodDeclaration;
private DeclarationFinderDO declData;
public HideMethodRefactoring(IFile file, ISelection selection, ICElement element, ICProject project) { public HideMethodRefactoring(ICElement element, ISelection selection, ICProject project) {
super(file, selection, element, project); super(element, selection, project);
name = Messages.HideMethodRefactoring_HIDE_METHOD; name = Messages.HideMethodRefactoring_HIDE_METHOD;
} }
@ -77,56 +87,49 @@ public class HideMethodRefactoring extends CRefactoring {
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
SubMonitor sm = SubMonitor.convert(pm, 10); SubMonitor sm = SubMonitor.convert(pm, 10);
try { try {
lockIndex(); super.checkInitialConditions(sm.newChild(8));
try {
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; List<IASTName> names = findAllMarkedNames();
ArrayList<IASTName> names = findAllMarkedNames(); if (names.isEmpty()) {
if (names.size() < 1) {
initStatus.addFatalError(Messages.HideMethodRefactoring_NoNameSelected); initStatus.addFatalError(Messages.HideMethodRefactoring_NoNameSelected);
return initStatus; return initStatus;
} }
name = names.get(names.size()-1); IASTName name = names.get(names.size() - 1);
sm.worked(1);
if (isProgressMonitorCanceld(sm, initStatus)) return initStatus;
declData = DeclarationFinder.getDeclaration(name, getIndex()); methodName = DefinitionFinder.getMemberDeclaration(name, refactoringContext, sm.newChild(1));
if (methodName == null) {
if (declData == null || declData.name == null) {
initStatus.addFatalError(Messages.HideMethodRefactoring_NoMethodNameSelected); initStatus.addFatalError(Messages.HideMethodRefactoring_NoMethodNameSelected);
return initStatus; return initStatus;
} }
methodToHide = declData.name; IASTDeclarator decl = (IASTDeclarator) methodName.getParent();
sm.worked(1); decl = CPPVisitor.findOutermostDeclarator(decl);
methodToHideDecl = NodeHelper.findSimpleDeclarationInParents(methodToHide); methodDeclaration = (IASTDeclaration) decl.getParent();
if (methodToHideDecl == null) { if (methodDeclaration == null ||
!(methodDeclaration.getParent() instanceof ICPPASTCompositeTypeSpecifier)) {
initStatus.addFatalError(Messages.HideMethodRefactoring_CanOnlyHideMethods); initStatus.addFatalError(Messages.HideMethodRefactoring_CanOnlyHideMethods);
return initStatus; return initStatus;
} }
if (!(methodToHideDecl.getParent() instanceof ICPPASTCompositeTypeSpecifier)) {
methodToHideDecl = NodeHelper.findFunctionDefinitionInAncestors(methodToHide);
}
if (isProgressMonitorCanceld(sm, initStatus)) return initStatus; if (isProgressMonitorCanceld(sm, initStatus))
sm.worked(1); return initStatus;
if (methodToHideDecl instanceof IASTFunctionDefinition) { if (methodDeclaration instanceof IASTFunctionDefinition) {
IASTDeclarator declarator = ((IASTFunctionDefinition)methodToHideDecl).getDeclarator(); IASTDeclarator declarator = ((IASTFunctionDefinition) methodDeclaration).getDeclarator();
if (ASTQueries.findInnermostDeclarator(declarator).getName().getRawSignature().equals(name.getRawSignature())) { if (ASTQueries.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 (methodDeclaration instanceof IASTSimpleDeclaration) {
for(IASTDeclarator declarator : ((IASTSimpleDeclaration) methodToHideDecl).getDeclarators()) { for (IASTDeclarator declarator : ((IASTSimpleDeclaration) methodDeclaration).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);
@ -139,24 +142,19 @@ public class HideMethodRefactoring extends CRefactoring {
return initStatus; return initStatus;
} }
sm.worked(1); IASTCompositeTypeSpecifier classNode =
CPPVisitor.findAncestorWithType(methodName, IASTCompositeTypeSpecifier.class);
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, methodDeclaration)) {
initStatus.addError(Messages.HideMethodRefactoring_IsAlreadyPrivate); initStatus.addError(Messages.HideMethodRefactoring_IsAlreadyPrivate);
} }
sm.done();
} finally {
unlockIndex();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return initStatus; return initStatus;
} finally {
sm.done();
}
} }
private boolean checkIfPrivate(IASTCompositeTypeSpecifier classNode, IASTDeclaration decl) { private boolean checkIfPrivate(IASTCompositeTypeSpecifier classNode, IASTDeclaration decl) {
@ -183,123 +181,110 @@ public class HideMethodRefactoring extends CRefactoring {
} }
@Override @Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { public RefactoringStatus checkFinalConditions(IProgressMonitor pm,
RefactoringStatus finalConditions = null; CheckConditionsContext checkContext) throws CoreException, OperationCanceledException {
SubMonitor sm = SubMonitor.convert(pm, 10);
try { try {
lockIndex(); RefactoringStatus status = new RefactoringStatus();
try { IIndex index = getIndex();
finalConditions = super.checkFinalConditions(pm); IIndexBinding methodBinding = index.adaptBinding(methodName.resolveBinding());
if (methodBinding == null)
for(IIndexName pdomref : declData.allNamesPDom) { return null;
declData.filename = pdomref.getFileLocation().getFileName(); List<IASTName> references = new ArrayList<IASTName>();
Set<String> searchedFiles = new HashSet<String>();
if (pdomref instanceof PDOMName) { IEditorPart[] dirtyEditors = EditorUtility.getDirtyEditors(true);
PDOMName pdomName = (PDOMName)pdomref; SubMonitor loopProgress = sm.newChild(3).setWorkRemaining(dirtyEditors.length);
if (pdomName.isDeclaration()) { for (IEditorPart editor : dirtyEditors) {
continue; if (sm.isCanceled()) {
throw new OperationCanceledException();
}
IEditorInput editorInput = editor.getEditorInput();
if (editorInput instanceof ITranslationUnitEditorInput) {
ITranslationUnit tu =
CModelUtil.toWorkingCopy(((ITranslationUnitEditorInput) editorInput).getTranslationUnit());
searchedFiles.add(tu.getLocation().toOSString());
IASTTranslationUnit ast = getAST(tu, loopProgress.newChild(1));
for (IASTName reference : ast.getReferences(methodBinding)) {
if (!AccessContext.isAccessible(methodBinding, ICPPMember.v_private, reference)) {
status.addWarning(Messages.HideMethodRefactoring_HasExternalReferences);
return status;
}
} }
if (pdomName.isDefinition()) {
continue;
} }
} }
IASTTranslationUnit transUtmp = TranslationUnitHelper.loadTranslationUnit(declData.filename, false); IIndexName[] referencesFromIndex = index.findReferences(methodBinding);
IASTName expName = ExpressionFinder.findExpressionInTranslationUnit(transUtmp, pdomref); int remainingCount = referencesFromIndex.length;
loopProgress = sm.newChild(6).setWorkRemaining(remainingCount);
IASTFunctionDeclarator funcDec = findEnclosingFunction(expName); for (IIndexName name : referencesFromIndex) {
IASTCompositeTypeSpecifier encClass2; if (sm.isCanceled()) {
if (funcDec == null) { throw new OperationCanceledException();
encClass2 = NodeHelper.findClassInAncestors(expName);
} }
else { ITranslationUnit tu = CoreModelUtil.findTranslationUnitForLocation(
encClass2 = NodeHelper.findClassInAncestors(funcDec); name.getFile().getLocation(), null);
} if (searchedFiles.add(tu.getLocation().toOSString())) {
IASTTranslationUnit ast = getAST(tu, loopProgress.newChild(1));
IASTCompositeTypeSpecifier encClass = NodeHelper.findClassInAncestors(methodToHide); for (IASTName reference : ast.getReferences(methodBinding)) {
if (!AccessContext.isAccessible(methodBinding, ICPPMember.v_private, reference)) {
if (!NodeHelper.isSameNode(encClass, encClass2)) { status.addWarning(Messages.HideMethodRefactoring_HasExternalReferences);
finalConditions.addWarning(Messages.HideMethodRefactoring_HasExternalReferences); return status;
break;
} }
} }
ArrayUtil.addAll(references, ast.getReferences(methodBinding));
}
loopProgress.setWorkRemaining(--remainingCount);
}
return finalConditions; return status;
} finally { } finally {
unlockIndex(); sm.done();
} }
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return finalConditions;
}
private IASTFunctionDeclarator findEnclosingFunction(IASTNode node) throws CoreException {
IASTCompoundStatement compStat = NodeHelper.findCompoundStatementInAncestors(node);
if (compStat == null) {
return null;
}
IASTNode parent = compStat.getParent();
if (parent instanceof IASTFunctionDefinition) {
IASTDeclarator declarator = ((IASTFunctionDefinition)parent).getDeclarator();
IASTName declaratorName = getLastName(ASTQueries.findInnermostDeclarator(declarator));
DeclarationFinderDO data = DeclarationFinder.getDeclaration(declaratorName, getIndex());
if (data == null || data.name == null) {
return null;
}
if (data.name.getParent() instanceof IASTFunctionDeclarator) {
return (IASTFunctionDeclarator) data.name.getParent();
}
return null;
} else if (parent instanceof IASTTranslationUnit) {
return null;
}
return findEnclosingFunction(parent);
}
private IASTName getLastName(IASTDeclarator declarator) {
IASTName declaratorName = declarator.getName();
if (declaratorName instanceof ICPPASTQualifiedName) {
IASTName[] declaratorNames = ((ICPPASTQualifiedName) declaratorName).getNames();
declaratorName = declaratorNames[declaratorNames.length-1];
}
return declaratorName;
} }
@Override @Override
protected void collectModifications(IProgressMonitor pm, ModificationCollector collector) throws CoreException, OperationCanceledException { protected void collectModifications(IProgressMonitor pm, ModificationCollector collector) throws CoreException, OperationCanceledException {
try { ASTRewrite rewriter = collector.rewriterForTranslationUnit(methodName.getTranslationUnit());
lockIndex(); TextEditGroup editGroup = new TextEditGroup(Messages.HideMethodRefactoring_FILE_CHANGE_TEXT+ methodName.getRawSignature());
try {
ASTRewrite rewriter = collector.rewriterForTranslationUnit(declData.transUnit);
TextEditGroup editGroup = new TextEditGroup(Messages.HideMethodRefactoring_FILE_CHANGE_TEXT+ methodToHide.getRawSignature());
ICPPASTCompositeTypeSpecifier classDefinition = (ICPPASTCompositeTypeSpecifier) methodToHideDecl.getParent(); ICPPASTCompositeTypeSpecifier classDefinition = (ICPPASTCompositeTypeSpecifier) methodDeclaration.getParent();
ClassMemberInserter.createChange(classDefinition, VisibilityEnum.v_private, methodToHideDecl, false, collector); ClassMemberInserter.createChange(classDefinition, VisibilityEnum.v_private, methodDeclaration, false, collector);
rewriter.remove(methodToHideDecl, editGroup); rewriter.remove(methodDeclaration, editGroup);
} finally {
unlockIndex();
} }
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); private List<IASTName> findAllMarkedNames() throws OperationCanceledException, CoreException {
final ArrayList<IASTName> namesVector = new ArrayList<IASTName>();
IASTTranslationUnit ast = getAST(tu, null);
ast.accept(new ASTVisitor() {
{
shouldVisitNames = true;
} }
@Override
public int visit(IASTName name) {
if (name.isPartOfTranslationUnitFile() && SelectionHelper.doesNodeOverlapWithRegion(name, selectedRegion)) {
if (!(name instanceof ICPPASTQualifiedName)) {
namesVector.add(name);
}
}
return super.visit(name);
}
});
return namesVector;
} }
@Override @Override
protected RefactoringDescriptor getRefactoringDescriptor() { protected RefactoringDescriptor getRefactoringDescriptor() {
Map<String, String> arguments = getArgumentMap(); Map<String, String> arguments = getArgumentMap();
RefactoringDescriptor desc = new HideMethodRefactoringDescription( project.getProject().getName(), "Hide Method Refactoring", "Hide Method " + methodToHide.getRawSignature(), arguments); //$NON-NLS-1$//$NON-NLS-2$ RefactoringDescriptor desc = new HideMethodRefactoringDescriptor( project.getProject().getName(), "Hide Method Refactoring", "Hide Method " + methodName.getRawSignature(), arguments); //$NON-NLS-1$//$NON-NLS-2$
return desc; return desc;
} }
private Map<String, String> getArgumentMap() { private Map<String, String> getArgumentMap() {
Map<String, String> arguments = new HashMap<String, String>(); Map<String, String> arguments = new HashMap<String, String>();
arguments.put(CRefactoringDescription.FILE_NAME, file.getLocationURI().toString()); arguments.put(CRefactoringDescriptor.FILE_NAME, tu.getLocationURI().toString());
arguments.put(CRefactoringDescription.SELECTION, region.getOffset() + "," + region.getLength()); //$NON-NLS-1$ arguments.put(CRefactoringDescriptor.SELECTION, selectedRegion.getOffset() + "," + selectedRegion.getLength()); //$NON-NLS-1$
return arguments; return arguments;
} }
} }

View file

@ -21,15 +21,13 @@ import org.eclipse.cdt.internal.ui.refactoring.CRefactoringContribution;
* @author Emanuel Graf IFS * @author Emanuel Graf IFS
*/ */
public class HideMethodRefactoringContribution extends CRefactoringContribution { public class HideMethodRefactoringContribution extends CRefactoringContribution {
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
@Override @Override
public RefactoringDescriptor createDescriptor(String id, String project, String description, public RefactoringDescriptor createDescriptor(String id, String project, String description,
String comment, Map arguments, int flags) throws IllegalArgumentException { String comment, Map arguments, int flags) throws IllegalArgumentException {
if (id.equals(HideMethodRefactoring.ID)) { if (id.equals(HideMethodRefactoring.ID)) {
return new HideMethodRefactoringDescription(project, description, comment, arguments); return new HideMethodRefactoringDescriptor(project, description, comment, arguments);
} else { }
return null; return null;
} }
}
} }

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2009 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2009, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others. * Rapperswil, University of applied sciences and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -8,42 +8,36 @@
* *
* Contributors: * Contributors:
* Institute for Software (IFS)- initial API and implementation * Institute for Software (IFS)- initial API and implementation
* Sergey Prigogin (Google)
******************************************************************************/ ******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.hidemethod; package org.eclipse.cdt.internal.ui.refactoring.hidemethod;
import java.util.Map; import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescription; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoringDescriptor;
/** /**
* @author Emanuel Graf IFS * @author Emanuel Graf IFS
*
*/ */
public class HideMethodRefactoringDescription extends CRefactoringDescription { public class HideMethodRefactoringDescriptor extends CRefactoringDescriptor {
public HideMethodRefactoringDescription(String project, String description, String comment, public HideMethodRefactoringDescriptor(String project, String description, String comment,
Map<String, String> arguments) { Map<String, String> arguments) {
super(HideMethodRefactoring.ID, project, description, comment, RefactoringDescriptor.STRUCTURAL_CHANGE, arguments); super(HideMethodRefactoring.ID, project, description, comment, RefactoringDescriptor.STRUCTURAL_CHANGE, arguments);
} }
@Override @Override
public Refactoring createRefactoring(RefactoringStatus status) throws CoreException { public CRefactoring2 createRefactoring(RefactoringStatus status) throws CoreException {
IFile file;
ICProject proj;
proj = getCProject();
file = getFile();
ISelection selection = getSelection(); ISelection selection = getSelection();
return new HideMethodRefactoring(file, selection, null, proj); ICProject proj = getCProject();
return new HideMethodRefactoring(getTranslationUnit(), selection, proj);
} }
} }

View file

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

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2008 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others * Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -16,16 +16,15 @@ import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
/** /**
* @author Guido Zgraggen IFS * @author Guido Zgraggen IFS
*
*/ */
public class HideMethodRefactoringWizard extends RefactoringWizard { public class HideMethodWizard extends RefactoringWizard {
public HideMethodRefactoringWizard(Refactoring refactoring) { public HideMethodWizard(Refactoring refactoring) {
super(refactoring, WIZARD_BASED_USER_INTERFACE); super(refactoring, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
} }
@Override @Override
protected void addUserInputPages() { protected void addUserInputPages() {
//No spezial User Wizard to add // No pages to add
} }
} }

View file

@ -13,7 +13,7 @@ HideMethodRefactoring_HasExternalReferences=This method might be referenced from
HideMethodRefactoring_HIDE_METHOD=Hide Method HideMethodRefactoring_HIDE_METHOD=Hide Method
HideMethodRefactoring_NoNameSelected=No names selected. HideMethodRefactoring_NoNameSelected=No names selected.
HideMethodRefactoring_NoMethodNameSelected=No method name selected. HideMethodRefactoring_NoMethodNameSelected=No method name selected.
HideMethodRefactoring_CanOnlyHideMethods=Hide Method can only hide Member Functions. HideMethodRefactoring_CanOnlyHideMethods=Hide Method refactoring can only hide member functions.
HideMethodRefactoring_FILE_CHANGE_TEXT=Hide HideMethodRefactoring_FILE_CHANGE_TEXT=Hide
HideMethodRefactoring_EnclosingClassNotFound=Enclosing class not found. HideMethodRefactoring_EnclosingClassNotFound=Enclosing class not found.
HideMethodRefactoring_IsAlreadyPrivate=Method is already private. HideMethodRefactoring_IsAlreadyPrivate=Method is already private.

View file

@ -58,6 +58,8 @@ import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2; import org.eclipse.cdt.internal.ui.refactoring.CRefactoring2;
import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector; import org.eclipse.cdt.internal.ui.refactoring.ModificationCollector;
import org.eclipse.cdt.internal.ui.refactoring.utils.Checks; import org.eclipse.cdt.internal.ui.refactoring.utils.Checks;
@ -272,7 +274,7 @@ public class ImplementMethodRefactoring extends CRefactoring2 {
IASTFunctionDefinition functionDefinition = nodeFactory.newFunctionDefinition(declSpecifier, createdMethodDeclarator, nodeFactory.newCompoundStatement()); IASTFunctionDefinition functionDefinition = nodeFactory.newFunctionDefinition(declSpecifier, createdMethodDeclarator, nodeFactory.newCompoundStatement());
functionDefinition.setParent(unit); functionDefinition.setParent(unit);
ICPPASTTemplateDeclaration templateDeclaration = NodeHelper.findContainedTemplateDecalaration(declarationParent); ICPPASTTemplateDeclaration templateDeclaration = CPPVisitor.findAncestorWithType(declarationParent, ICPPASTTemplateDeclaration.class);
if (templateDeclaration != null) { if (templateDeclaration != null) {
ICPPASTTemplateDeclaration newTemplateDeclaration = nodeFactory.newTemplateDeclaration(functionDefinition); ICPPASTTemplateDeclaration newTemplateDeclaration = nodeFactory.newTemplateDeclaration(functionDefinition);
newTemplateDeclaration.setParent(unit); newTemplateDeclaration.setParent(unit);

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others * Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -53,7 +53,7 @@ public class MethodDefinitionInsertLocationFinder {
new HashMap<IASTSimpleDeclaration, IASTName>(); new HashMap<IASTSimpleDeclaration, IASTName>();
public InsertLocation find(ITranslationUnit declarationTu, IASTFileLocation methodDeclarationLocation, public InsertLocation find(ITranslationUnit declarationTu, IASTFileLocation methodDeclarationLocation,
IASTNode parent, CRefactoringContext astCache, IProgressMonitor pm) throws CoreException { IASTNode parent, CRefactoringContext refactoringContext, IProgressMonitor pm) throws CoreException {
IASTDeclaration[] declarations = NodeHelper.getDeclarations(parent); IASTDeclaration[] declarations = NodeHelper.getDeclarations(parent);
InsertLocation insertLocation = new InsertLocation(); InsertLocation insertLocation = new InsertLocation();
@ -71,7 +71,8 @@ public class MethodDefinitionInsertLocationFinder {
if (cachedDeclarationToDefinition.containsKey(simpleDeclaration)) { if (cachedDeclarationToDefinition.containsKey(simpleDeclaration)) {
definition = cachedDeclarationToDefinition.get(simpleDeclaration); definition = cachedDeclarationToDefinition.get(simpleDeclaration);
} else { } else {
definition = DefinitionFinder.getDefinition(simpleDeclaration, astCache, pm); IASTName name = simpleDeclaration.getDeclarators()[0].getName();
definition = DefinitionFinder.getDefinition(name, refactoringContext, pm);
if (definition != null) { if (definition != null) {
cachedDeclarationToDefinition.put(simpleDeclaration, definition); cachedDeclarationToDefinition.put(simpleDeclaration, definition);
} }
@ -92,7 +93,8 @@ public class MethodDefinitionInsertLocationFinder {
if (cachedDeclarationToDefinition.containsKey(simpleDeclaration)) { if (cachedDeclarationToDefinition.containsKey(simpleDeclaration)) {
definition = cachedDeclarationToDefinition.get(simpleDeclaration); definition = cachedDeclarationToDefinition.get(simpleDeclaration);
} else { } else {
definition = DefinitionFinder.getDefinition(simpleDeclaration, astCache, pm); IASTName name = simpleDeclaration.getDeclarators()[0].getName();
definition = DefinitionFinder.getDefinition(name, refactoringContext, pm);
if (definition != null) { if (definition != null) {
cachedDeclarationToDefinition.put(simpleDeclaration, definition); cachedDeclarationToDefinition.put(simpleDeclaration, definition);
} }
@ -107,9 +109,9 @@ public class MethodDefinitionInsertLocationFinder {
if (insertLocation.getTranslationUnit() == null) { if (insertLocation.getTranslationUnit() == null) {
if (declarationTu.isHeaderUnit()) { if (declarationTu.isHeaderUnit()) {
ITranslationUnit partner = SourceHeaderPartnerFinder.getPartnerTranslationUnit( ITranslationUnit partner = SourceHeaderPartnerFinder.getPartnerTranslationUnit(
declarationTu, astCache); declarationTu, refactoringContext);
if (partner != null) { if (partner != null) {
insertLocation.setParentNode(astCache.getAST(partner, null), partner); insertLocation.setParentNode(refactoringContext.getAST(partner, null), partner);
} }
} else { } else {
insertLocation.setParentNode(parent.getTranslationUnit(), declarationTu); insertLocation.setParentNode(parent.getTranslationUnit(), declarationTu);

View file

@ -1,73 +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.utils;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNodeLocation;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexBinding;
import org.eclipse.cdt.core.index.IIndexName;
import org.eclipse.cdt.internal.ui.refactoring.Container;
/**
* @author Guido Zgraggen IFS
*/
public class DeclarationFinder {
public static DeclarationFinderDO getDeclaration(IASTName name, IIndex index) throws CoreException {
IIndexBinding binding = index.findBinding(name);
IIndexName[] pdomref = index.findDeclarations(binding);
IIndexName[] allNamesPDom = index.findNames(binding, IIndex.FIND_REFERENCES);
if (pdomref == null || pdomref.length < 1) {
return null;
}
String filename2 = pdomref[0].getFileLocation().getFileName();
IASTTranslationUnit transUnit = TranslationUnitHelper.loadTranslationUnit(filename2, false);
IASTName declName = DeclarationFinder.findDeclarationInTranslationUnit(transUnit, pdomref[0]);
return new DeclarationFinderDO(allNamesPDom, transUnit, filename2, declName);
}
public static IASTName findDeclarationInTranslationUnit(IASTTranslationUnit transUnit, final IIndexName indexName) {
final Container<IASTName> defName = new Container<IASTName>();
transUnit.accept(new ASTVisitor() {
{
shouldVisitNames = true;
}
@Override
public int visit(IASTName name) {
if (name.isDeclaration() && name.getNodeLocations().length > 0) {
IASTNodeLocation nodeLocation = name.getNodeLocations()[0];
if (indexName.getNodeOffset() == nodeLocation.getNodeOffset()
&& indexName.getNodeLength() == nodeLocation.getNodeLength()
&& new Path(indexName.getFileLocation().getFileName()).equals(new Path(nodeLocation.asFileLocation().getFileName()))) {
defName.setObject(name);
return ASTVisitor.PROCESS_ABORT;
}
}
return ASTVisitor.PROCESS_CONTINUE;
}
});
return defName.getObject();
}
}

View file

@ -1,34 +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.utils;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.index.IIndexName;
/**
* @author Guido Zgraggen IFS
*
*/
public class DeclarationFinderDO {
public IASTTranslationUnit transUnit = null;
public String filename = null;
public IIndexName[] allNamesPDom = null;
public IASTName name = null;
public DeclarationFinderDO(IIndexName[] allNamesPDom2, IASTTranslationUnit transUnit2, String filename2, IASTName name2) {
this.transUnit = transUnit2;
this.filename = filename2;
this.allNamesPDom = allNamesPDom2;
this.name = name2;
}
}

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2011 Google, Inc and others. * Copyright (c) 2011, 2012 Google, Inc and others.
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at * which accompanies this distribution, and is available at
@ -18,20 +18,25 @@ import java.util.Set;
import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorPart;
import org.eclipse.cdt.core.dom.IName; import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTDeclarator; import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPMember;
import org.eclipse.cdt.core.index.IIndex; import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexBinding; import org.eclipse.cdt.core.index.IIndexBinding;
import org.eclipse.cdt.core.index.IIndexName; import org.eclipse.cdt.core.index.IIndexName;
import org.eclipse.cdt.core.model.CoreModelUtil; import org.eclipse.cdt.core.model.CoreModelUtil;
import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.parser.util.ArrayUtil;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
import org.eclipse.cdt.internal.corext.util.CModelUtil; import org.eclipse.cdt.internal.corext.util.CModelUtil;
import org.eclipse.cdt.internal.ui.editor.ITranslationUnitEditorInput; import org.eclipse.cdt.internal.ui.editor.ITranslationUnitEditorInput;
@ -39,70 +44,100 @@ import org.eclipse.cdt.internal.ui.refactoring.CRefactoringContext;
import org.eclipse.cdt.internal.ui.util.EditorUtility; import org.eclipse.cdt.internal.ui.util.EditorUtility;
/** /**
* Helper class for finding definitions. * Helper class for finding definitions and class member declarations
*/ */
public class DefinitionFinder { public class DefinitionFinder {
public static IASTName getDefinition(IASTSimpleDeclaration simpleDeclaration, public static IASTName getDefinition(IASTName name, CRefactoringContext context,
CRefactoringContext refactoringContext, IProgressMonitor pm) throws CoreException { IProgressMonitor pm) throws CoreException {
IIndex index = refactoringContext.getIndex(); IIndex index = context.getIndex();
if (index == null) { if (index == null) {
return null; return null;
} }
IASTDeclarator declarator = simpleDeclaration.getDeclarators()[0]; IBinding binding = name.resolveBinding();
IIndexBinding binding = index.adaptBinding(declarator.getName().resolveBinding());
if (binding == null) { if (binding == null) {
return null; return null;
} }
return getDefinition(binding, refactoringContext, index, pm); return getDefinition(binding, context, index, pm);
} }
private static IASTName getDefinition(IIndexBinding binding, private static IASTName getDefinition(IBinding binding, CRefactoringContext context,
CRefactoringContext refactoringContext, IIndex index, IProgressMonitor pm) throws CoreException { IIndex index, IProgressMonitor pm) throws CoreException {
SubMonitor sm = SubMonitor.convert(pm, 10);
IIndexBinding indexBinding = index.adaptBinding(binding);
if (binding == null)
return null;
Set<String> searchedFiles = new HashSet<String>(); Set<String> searchedFiles = new HashSet<String>();
List<IASTName> definitions = new ArrayList<IASTName>(); List<IASTName> definitions = new ArrayList<IASTName>();
// TODO(sprigogin): Check index before dirty editors.
IEditorPart[] dirtyEditors = EditorUtility.getDirtyEditors(true); IEditorPart[] dirtyEditors = EditorUtility.getDirtyEditors(true);
SubMonitor loopProgress = sm.newChild(3).setWorkRemaining(dirtyEditors.length);
for (IEditorPart editor : dirtyEditors) { for (IEditorPart editor : dirtyEditors) {
if (pm != null && pm.isCanceled()) { if (sm.isCanceled()) {
throw new OperationCanceledException(); throw new OperationCanceledException();
} }
IEditorInput editorInput = editor.getEditorInput(); IEditorInput editorInput = editor.getEditorInput();
if (editorInput instanceof ITranslationUnitEditorInput) { if (editorInput instanceof ITranslationUnitEditorInput) {
ITranslationUnit tu = ITranslationUnit tu =
CModelUtil.toWorkingCopy(((ITranslationUnitEditorInput) editorInput).getTranslationUnit()); CModelUtil.toWorkingCopy(((ITranslationUnitEditorInput) editorInput).getTranslationUnit());
findDefinitionsInTranslationUnit(binding, tu, refactoringContext, definitions, null); findDefinitionsInTranslationUnit(indexBinding, tu, context, definitions, loopProgress.newChild(1));
searchedFiles.add(tu.getLocation().toOSString()); searchedFiles.add(tu.getLocation().toOSString());
} }
} }
IIndexName[] definitionsFromIndex = index.findDefinitions(binding); IIndexName[] definitionsFromIndex = index.findDefinitions(indexBinding);
int remainingCount = definitionsFromIndex.length;
loopProgress = sm.newChild(6).setWorkRemaining(remainingCount);
for (IIndexName name : definitionsFromIndex) { for (IIndexName name : definitionsFromIndex) {
if (pm != null && pm.isCanceled()) { if (sm.isCanceled()) {
throw new OperationCanceledException(); throw new OperationCanceledException();
} }
ITranslationUnit tu = CoreModelUtil.findTranslationUnitForLocation( ITranslationUnit tu = CoreModelUtil.findTranslationUnitForLocation(
name.getFile().getLocation(), null); name.getFile().getLocation(), null);
if (searchedFiles.add(tu.getLocation().toOSString())) { if (searchedFiles.add(tu.getLocation().toOSString())) {
findDefinitionsInTranslationUnit(binding, tu, refactoringContext, definitions, pm); findDefinitionsInTranslationUnit(indexBinding, tu, context, definitions, pm);
} }
loopProgress.setWorkRemaining(--remainingCount);
} }
return definitions.size() == 1 ? definitions.get(0) : null; return definitions.size() == 1 ? definitions.get(0) : null;
} }
private static void findDefinitionsInTranslationUnit(IIndexBinding binding, ITranslationUnit tu, private static void findDefinitionsInTranslationUnit(IIndexBinding binding, ITranslationUnit tu,
CRefactoringContext refactoringContext, List<IASTName> definitions, IProgressMonitor pm) CRefactoringContext context, List<IASTName> definitions, IProgressMonitor pm)
throws OperationCanceledException, CoreException { throws OperationCanceledException, CoreException {
IASTTranslationUnit ast = refactoringContext.getAST(tu, pm); IASTTranslationUnit ast = context.getAST(tu, pm);
findDefinitionsInAST(binding, ast, tu, definitions); ArrayUtil.addAll(definitions, ast.getDefinitionsInAST(binding));
} }
private static void findDefinitionsInAST(IIndexBinding binding, IASTTranslationUnit ast, public static IASTName getMemberDeclaration(IASTName memberName, CRefactoringContext context,
ITranslationUnit tu, List<IASTName> definitions) { IProgressMonitor pm) throws CoreException {
for (IName definition : ast.getDefinitions(binding)) { IIndex index = context.getIndex();
if (definition instanceof IASTName) { if (index == null)
definitions.add((IASTName) definition); return null;
IBinding binding = memberName.resolveBinding();
if (!(binding instanceof ICPPMember))
return null;
return getMemberDeclaration((ICPPMember) binding, context, index, pm);
}
private static IASTName getMemberDeclaration(ICPPMember member, CRefactoringContext context,
IIndex index, IProgressMonitor pm) throws CoreException {
IASTName classDefintionName = getDefinition(member.getClassOwner(), context, index, pm);
if (classDefintionName == null)
return null;
IASTCompositeTypeSpecifier compositeTypeSpecifier =
CPPVisitor.findAncestorWithType(classDefintionName, IASTCompositeTypeSpecifier.class);
IASTTranslationUnit ast = classDefintionName.getTranslationUnit();
IASTName[] memberDeclarationNames = ast.getDeclarationsInAST(index.adaptBinding(member));
for (IASTName name : memberDeclarationNames) {
if (name.getPropertyInParent() == IASTDeclarator.DECLARATOR_NAME) {
IASTDeclaration declaration = CPPVisitor.findAncestorWithType(name, IASTDeclaration.class);
if (declaration.getParent() == compositeTypeSpecifier) {
return name;
} }
} }
} }
return null;
}
} }

View file

@ -16,10 +16,7 @@ import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Path;
import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration; import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTFileLocation;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator; import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition; import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition;
import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTName;
@ -32,14 +29,7 @@ import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateDeclaration; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateDeclaration;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod; import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexFileLocation;
import org.eclipse.cdt.core.index.IIndexName;
import org.eclipse.cdt.core.model.CoreModelUtil;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.core.dom.parser.ASTQueries;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTNamespaceDefinition; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTNamespaceDefinition;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTranslationUnit; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTranslationUnit;
import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor; import org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.CPPVisitor;
@ -97,16 +87,6 @@ public class NodeHelper {
&& new Path(node1.getFileLocation().getFileName()).equals(new Path(node2.getFileLocation().getFileName())); && new Path(node1.getFileLocation().getFileName()).equals(new Path(node2.getFileLocation().getFileName()));
} }
public static IASTSimpleDeclaration findSimpleDeclarationInParents(IASTNode node) {
while (node != null) {
if (node instanceof IASTSimpleDeclaration) {
return (IASTSimpleDeclaration) node;
}
node = node.getParent();
}
return null;
}
public static MethodContext findMethodContext(IASTNode node, CRefactoringContext refactoringContext, public static MethodContext findMethodContext(IASTNode node, CRefactoringContext refactoringContext,
IProgressMonitor pm) throws CoreException { IProgressMonitor pm) throws CoreException {
IASTTranslationUnit translationUnit = node.getTranslationUnit(); IASTTranslationUnit translationUnit = node.getTranslationUnit();
@ -139,142 +119,10 @@ public class NodeHelper {
IBinding binding = name.resolveBinding(); IBinding binding = name.resolveBinding();
if (binding instanceof ICPPMethod) { if (binding instanceof ICPPMethod) {
context.setType(MethodContext.ContextType.METHOD); context.setType(MethodContext.ContextType.METHOD);
IIndex index = refactoringContext.getIndex(); IASTName declName = DefinitionFinder.getMemberDeclaration(name, refactoringContext, pm);
IIndexName[] declarations = index.findDeclarations(binding);
if (declarations.length == 0) {
context.setMethodDeclarationName(name);
} else {
IASTFileLocation tuFileLocation = ast.getFileLocation();
ICProject cProject = ast.getOriginatingTranslationUnit().getCProject();
for (IIndexName decl : declarations) {
IASTTranslationUnit ast2 = ast;
if (!tuFileLocation.equals(decl.getFileLocation())) {
IIndexFileLocation fileLocation = decl.getFile().getLocation();
ITranslationUnit locTu =
CoreModelUtil.findTranslationUnitForLocation(fileLocation, cProject);
ast2 = refactoringContext.getAST(locTu, pm);
}
IASTName declName = DeclarationFinder.findDeclarationInTranslationUnit(ast2, decl);
if (declName != null) {
IASTNode methodDeclaration = declName.getParent().getParent();
if (methodDeclaration instanceof IASTSimpleDeclaration ||
methodDeclaration instanceof IASTFunctionDefinition) {
context.setMethodDeclarationName(declName); context.setMethodDeclarationName(declName);
} }
} }
}
}
}
}
/**
* @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();
IASTName name = null;
while (node != null && !found) {
node = node.getParent();
if (node instanceof IASTFunctionDeclarator) {
name = ((IASTFunctionDeclarator) node).getName();
found = true;
context.setType(MethodContext.ContextType.FUNCTION);
} else if (node instanceof IASTFunctionDefinition) {
name = ASTQueries.findInnermostDeclarator(((IASTFunctionDefinition) node).getDeclarator()).getName();
found = true;
context.setType(MethodContext.ContextType.FUNCTION);
}
}
if (index != null) {
getMethodContextWithIndex(index, translationUnit, context, name);
} else {
getMethodContext(translationUnit, context, name);
}
return context;
}
@Deprecated
private static void getMethodContextWithIndex(IIndex index, IASTTranslationUnit translationUnit,
MethodContext context, IASTName name) throws CoreException {
IBinding bind = name.resolveBinding();
if (bind instanceof ICPPMethod) {
context.setType(MethodContext.ContextType.METHOD);
IIndexName[] decl;
decl = index.findDeclarations(bind);
String tuFileLoc = translationUnit.getFileLocation().getFileName();
if (decl.length == 0) {
context.setMethodDeclarationName(name);
}
for (IIndexName tmpname : decl) {
IASTTranslationUnit locTu = translationUnit;
if (!tuFileLoc.equals(tmpname.getFileLocation().getFileName())) {
locTu = TranslationUnitHelper.loadTranslationUnit(tmpname.getFileLocation().getFileName(), false);
}
IASTName declName = DeclarationFinder.findDeclarationInTranslationUnit(locTu, tmpname);
if (declName != null) {
IASTNode methoddefinition = declName.getParent().getParent();
if (methoddefinition instanceof IASTSimpleDeclaration ||
methoddefinition instanceof IASTFunctionDefinition) {
context.setMethodDeclarationName(declName);
}
}
}
}
if (name instanceof ICPPASTQualifiedName) {
ICPPASTQualifiedName qname = (ICPPASTQualifiedName) name;
context.setMethodQName(qname);
}
}
private static void getMethodContext(IASTTranslationUnit translationUnit, MethodContext context,
IASTName name) {
if (name instanceof ICPPASTQualifiedName) {
ICPPASTQualifiedName qname = (ICPPASTQualifiedName) name;
context.setMethodQName(qname);
IBinding bind = qname.resolveBinding();
IASTName[] decl = translationUnit.getDeclarationsInAST(bind);
for (IASTName tmpname : decl) {
IASTNode methodDefinition = tmpname.getParent().getParent();
if (methodDefinition instanceof IASTSimpleDeclaration) {
context.setMethodDeclarationName(tmpname);
context.setType(MethodContext.ContextType.METHOD);
}
}
}
}
public static IASTCompoundStatement findCompoundStatementInAncestors(IASTNode node) {
while (node != null) {
if (node instanceof IASTCompoundStatement) {
return (IASTCompoundStatement) node;
}
node = node.getParent();
}
return null;
}
public static IASTCompositeTypeSpecifier findClassInAncestors(IASTNode node) {
while (!(node instanceof IASTCompositeTypeSpecifier)) {
if (node instanceof IASTTranslationUnit) {
return null;
}
node = node.getParent();
}
return (IASTCompositeTypeSpecifier) node;
}
public static IASTFunctionDefinition findFunctionDefinitionInAncestors(IASTNode node) {
while (node != null) {
if (node instanceof IASTFunctionDefinition) {
return (IASTFunctionDefinition) node;
}
node = node.getParent();
}
return null;
}
public static boolean isMethodDeclaration(IASTSimpleDeclaration simpleDeclaration) { public static boolean isMethodDeclaration(IASTSimpleDeclaration simpleDeclaration) {
if (simpleDeclaration == null) { if (simpleDeclaration == null) {
@ -285,16 +133,6 @@ public class NodeHelper {
} }
public static boolean isContainedInTemplateDeclaration(IASTNode node) { public static boolean isContainedInTemplateDeclaration(IASTNode node) {
return findContainedTemplateDecalaration(node) != null; return CPPVisitor.findAncestorWithType(node, ICPPASTTemplateDeclaration.class) != null;
}
public static ICPPASTTemplateDeclaration findContainedTemplateDecalaration(IASTNode node) {
while (node != null) {
if (node instanceof ICPPASTTemplateDeclaration) {
return (ICPPASTTemplateDeclaration) node;
}
node = node.getParent();
}
return null;
} }
} }

View file

@ -12,11 +12,6 @@
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring.utils; package org.eclipse.cdt.internal.ui.refactoring.utils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.Region; import org.eclipse.jface.text.Region;
import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelection;
@ -96,21 +91,6 @@ public class SelectionHelper {
offset1 <= offset2 + region2.getLength(); offset1 <= offset2 + region2.getLength();
} }
public static boolean isInSameFile(IASTNode node, IFile file) {
IPath path = new Path(node.getContainingFilename());
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IFile locFile = workspaceRoot.getFile(file.getLocation());
IFile tmpFile = workspaceRoot.getFile(path);
return locFile.equals(tmpFile);
}
public static boolean isInSameFileSelection(Region textSelection, IASTNode node, IFile file) {
if (isInSameFile(node, file)) {
return doesNodeOverlapWithRegion(node, textSelection);
}
return false;
}
public static boolean isNodeInsideSelection(IASTNode node, Region selection) { public static boolean isNodeInsideSelection(IASTNode node, Region selection) {
return node.isPartOfTranslationUnitFile() && isNodeInsideRegion(node, selection); return node.isPartOfTranslationUnitFile() && isNodeInsideRegion(node, selection);
} }

View file

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright (c) 2008, 2009 Institute for Software, HSR Hochschule fuer Technik * Copyright (c) 2008, 2012 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others * Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
@ -8,11 +8,10 @@
* *
* Contributors: * Contributors:
* Institute for Software - initial API and implementation * Institute for Software - initial API and implementation
* Sergey Prigogin (Google)
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.ui.refactoring.actions; package org.eclipse.cdt.ui.refactoring.actions;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.window.IShellProvider; import org.eclipse.jface.window.IShellProvider;
@ -24,7 +23,7 @@ import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.internal.ui.refactoring.hidemethod.HideMethodRefactoringRunner; import org.eclipse.cdt.internal.ui.refactoring.hidemethod.HideMethodRefactoringRunner;
/** /**
* Launches a HideMethod refacoring * Launches a Hide Method refactoring
* @author Guido Zgraggen IFS * @author Guido Zgraggen IFS
* *
* @noextend This class is not intended to be subclassed by clients. * @noextend This class is not intended to be subclassed by clients.
@ -39,26 +38,22 @@ public class HideMethodAction extends RefactoringAction {
@Override @Override
public void run(IShellProvider shellProvider, ICElement elem) { public void run(IShellProvider shellProvider, ICElement elem) {
if (elem instanceof ISourceReference) { if (elem instanceof ISourceReference) {
new HideMethodRefactoringRunner(null, null, elem, shellProvider, elem.getCProject()).run(); new HideMethodRefactoringRunner(elem, null, shellProvider, elem.getCProject()).run();
} }
} }
@Override @Override
public void run(IShellProvider shellProvider, IWorkingCopy wc, ITextSelection s) { public void run(IShellProvider shellProvider, IWorkingCopy wc, ITextSelection selection) {
IResource res= wc.getResource(); if (wc.getResource() != null) {
if (res instanceof IFile) { new HideMethodRefactoringRunner(wc, selection, shellProvider, wc.getCProject()).run();
new HideMethodRefactoringRunner((IFile) res,
fEditor.getSelectionProvider().getSelection(), null,
fEditor.getSite().getWorkbenchWindow(), wc.getCProject()).run();
} }
} }
@Override @Override
public void updateSelection(ICElement elem) { public void updateSelection(ICElement elem) {
super.updateSelection(elem); super.updateSelection(elem);
if (elem instanceof IMethodDeclaration == false if (!(elem instanceof IMethodDeclaration) || !(elem instanceof ISourceReference) ||
|| elem instanceof ISourceReference == false ((ISourceReference) elem).getTranslationUnit().getResource() == null) {
|| ((ISourceReference) elem).getTranslationUnit().getResource() instanceof IFile == false) {
setEnabled(false); setEnabled(false);
} }
} }